##// END OF EJS Templates
Merge pull request #10105 from srinivasreddy/dead_code...
Thomas Kluyver -
r23070:748d7071 merge
parent child Browse files
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -1,257 +1,256 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 os
23 import os
24 import re
24 import re
25 import sys
25 import sys
26
26
27 from traitlets.config.configurable import Configurable
27 from traitlets.config.configurable import Configurable
28 from IPython.core.error import UsageError
28 from IPython.core.error import UsageError
29
29
30 from IPython.utils.py3compat import string_types
31 from traitlets import List, Instance
30 from traitlets import List, Instance
32 from logging import error
31 from logging import error
33
32
34 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
35 # Utilities
34 # Utilities
36 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
37
36
38 # 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.
39 shell_line_split = re.compile(r'^(\s*)()(\S+)(.*$)')
38 shell_line_split = re.compile(r'^(\s*)()(\S+)(.*$)')
40
39
41 def default_aliases():
40 def default_aliases():
42 """Return list of shell aliases to auto-define.
41 """Return list of shell aliases to auto-define.
43 """
42 """
44 # 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
45 # 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
46 # 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
47 # their case. For example, things like 'less' or 'clear' that manipulate
46 # their case. For example, things like 'less' or 'clear' that manipulate
48 # 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
49 # 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.
50
49
51 if os.name == 'posix':
50 if os.name == 'posix':
52 default_aliases = [('mkdir', 'mkdir'), ('rmdir', 'rmdir'),
51 default_aliases = [('mkdir', 'mkdir'), ('rmdir', 'rmdir'),
53 ('mv', 'mv'), ('rm', 'rm'), ('cp', 'cp'),
52 ('mv', 'mv'), ('rm', 'rm'), ('cp', 'cp'),
54 ('cat', 'cat'),
53 ('cat', 'cat'),
55 ]
54 ]
56 # 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
57 # different, so we make aliases that provide as similar as possible
56 # different, so we make aliases that provide as similar as possible
58 # behavior in ipython, by passing the right flags for each platform
57 # behavior in ipython, by passing the right flags for each platform
59 if sys.platform.startswith('linux'):
58 if sys.platform.startswith('linux'):
60 ls_aliases = [('ls', 'ls -F --color'),
59 ls_aliases = [('ls', 'ls -F --color'),
61 # long ls
60 # long ls
62 ('ll', 'ls -F -o --color'),
61 ('ll', 'ls -F -o --color'),
63 # ls normal files only
62 # ls normal files only
64 ('lf', 'ls -F -o --color %l | grep ^-'),
63 ('lf', 'ls -F -o --color %l | grep ^-'),
65 # ls symbolic links
64 # ls symbolic links
66 ('lk', 'ls -F -o --color %l | grep ^l'),
65 ('lk', 'ls -F -o --color %l | grep ^l'),
67 # directories or links to directories,
66 # directories or links to directories,
68 ('ldir', 'ls -F -o --color %l | grep /$'),
67 ('ldir', 'ls -F -o --color %l | grep /$'),
69 # things which are executable
68 # things which are executable
70 ('lx', 'ls -F -o --color %l | grep ^-..x'),
69 ('lx', 'ls -F -o --color %l | grep ^-..x'),
71 ]
70 ]
72 elif sys.platform.startswith('openbsd') or sys.platform.startswith('netbsd'):
71 elif sys.platform.startswith('openbsd') or sys.platform.startswith('netbsd'):
73 # OpenBSD, NetBSD. The ls implementation on these platforms do not support
72 # OpenBSD, NetBSD. The ls implementation on these platforms do not support
74 # the -G switch and lack the ability to use colorized output.
73 # the -G switch and lack the ability to use colorized output.
75 ls_aliases = [('ls', 'ls -F'),
74 ls_aliases = [('ls', 'ls -F'),
76 # long ls
75 # long ls
77 ('ll', 'ls -F -l'),
76 ('ll', 'ls -F -l'),
78 # ls normal files only
77 # ls normal files only
79 ('lf', 'ls -F -l %l | grep ^-'),
78 ('lf', 'ls -F -l %l | grep ^-'),
80 # ls symbolic links
79 # ls symbolic links
81 ('lk', 'ls -F -l %l | grep ^l'),
80 ('lk', 'ls -F -l %l | grep ^l'),
82 # directories or links to directories,
81 # directories or links to directories,
83 ('ldir', 'ls -F -l %l | grep /$'),
82 ('ldir', 'ls -F -l %l | grep /$'),
84 # things which are executable
83 # things which are executable
85 ('lx', 'ls -F -l %l | grep ^-..x'),
84 ('lx', 'ls -F -l %l | grep ^-..x'),
86 ]
85 ]
87 else:
86 else:
88 # BSD, OSX, etc.
87 # BSD, OSX, etc.
89 ls_aliases = [('ls', 'ls -F -G'),
88 ls_aliases = [('ls', 'ls -F -G'),
90 # long ls
89 # long ls
91 ('ll', 'ls -F -l -G'),
90 ('ll', 'ls -F -l -G'),
92 # ls normal files only
91 # ls normal files only
93 ('lf', 'ls -F -l -G %l | grep ^-'),
92 ('lf', 'ls -F -l -G %l | grep ^-'),
94 # ls symbolic links
93 # ls symbolic links
95 ('lk', 'ls -F -l -G %l | grep ^l'),
94 ('lk', 'ls -F -l -G %l | grep ^l'),
96 # directories or links to directories,
95 # directories or links to directories,
97 ('ldir', 'ls -F -G -l %l | grep /$'),
96 ('ldir', 'ls -F -G -l %l | grep /$'),
98 # things which are executable
97 # things which are executable
99 ('lx', 'ls -F -l -G %l | grep ^-..x'),
98 ('lx', 'ls -F -l -G %l | grep ^-..x'),
100 ]
99 ]
101 default_aliases = default_aliases + ls_aliases
100 default_aliases = default_aliases + ls_aliases
102 elif os.name in ['nt', 'dos']:
101 elif os.name in ['nt', 'dos']:
103 default_aliases = [('ls', 'dir /on'),
102 default_aliases = [('ls', 'dir /on'),
104 ('ddir', 'dir /ad /on'), ('ldir', 'dir /ad /on'),
103 ('ddir', 'dir /ad /on'), ('ldir', 'dir /ad /on'),
105 ('mkdir', 'mkdir'), ('rmdir', 'rmdir'),
104 ('mkdir', 'mkdir'), ('rmdir', 'rmdir'),
106 ('echo', 'echo'), ('ren', 'ren'), ('copy', 'copy'),
105 ('echo', 'echo'), ('ren', 'ren'), ('copy', 'copy'),
107 ]
106 ]
108 else:
107 else:
109 default_aliases = []
108 default_aliases = []
110
109
111 return default_aliases
110 return default_aliases
112
111
113
112
114 class AliasError(Exception):
113 class AliasError(Exception):
115 pass
114 pass
116
115
117
116
118 class InvalidAliasError(AliasError):
117 class InvalidAliasError(AliasError):
119 pass
118 pass
120
119
121 class Alias(object):
120 class Alias(object):
122 """Callable object storing the details of one alias.
121 """Callable object storing the details of one alias.
123
122
124 Instances are registered as magic functions to allow use of aliases.
123 Instances are registered as magic functions to allow use of aliases.
125 """
124 """
126
125
127 # Prepare blacklist
126 # Prepare blacklist
128 blacklist = {'cd','popd','pushd','dhist','alias','unalias'}
127 blacklist = {'cd','popd','pushd','dhist','alias','unalias'}
129
128
130 def __init__(self, shell, name, cmd):
129 def __init__(self, shell, name, cmd):
131 self.shell = shell
130 self.shell = shell
132 self.name = name
131 self.name = name
133 self.cmd = cmd
132 self.cmd = cmd
134 self.__doc__ = "Alias for `!{}`".format(cmd)
133 self.__doc__ = "Alias for `!{}`".format(cmd)
135 self.nargs = self.validate()
134 self.nargs = self.validate()
136
135
137 def validate(self):
136 def validate(self):
138 """Validate the alias, and return the number of arguments."""
137 """Validate the alias, and return the number of arguments."""
139 if self.name in self.blacklist:
138 if self.name in self.blacklist:
140 raise InvalidAliasError("The name %s can't be aliased "
139 raise InvalidAliasError("The name %s can't be aliased "
141 "because it is a keyword or builtin." % self.name)
140 "because it is a keyword or builtin." % self.name)
142 try:
141 try:
143 caller = self.shell.magics_manager.magics['line'][self.name]
142 caller = self.shell.magics_manager.magics['line'][self.name]
144 except KeyError:
143 except KeyError:
145 pass
144 pass
146 else:
145 else:
147 if not isinstance(caller, Alias):
146 if not isinstance(caller, Alias):
148 raise InvalidAliasError("The name %s can't be aliased "
147 raise InvalidAliasError("The name %s can't be aliased "
149 "because it is another magic command." % self.name)
148 "because it is another magic command." % self.name)
150
149
151 if not (isinstance(self.cmd, string_types)):
150 if not (isinstance(self.cmd, str)):
152 raise InvalidAliasError("An alias command must be a string, "
151 raise InvalidAliasError("An alias command must be a string, "
153 "got: %r" % self.cmd)
152 "got: %r" % self.cmd)
154
153
155 nargs = self.cmd.count('%s') - self.cmd.count('%%s')
154 nargs = self.cmd.count('%s') - self.cmd.count('%%s')
156
155
157 if (nargs > 0) and (self.cmd.find('%l') >= 0):
156 if (nargs > 0) and (self.cmd.find('%l') >= 0):
158 raise InvalidAliasError('The %s and %l specifiers are mutually '
157 raise InvalidAliasError('The %s and %l specifiers are mutually '
159 'exclusive in alias definitions.')
158 'exclusive in alias definitions.')
160
159
161 return nargs
160 return nargs
162
161
163 def __repr__(self):
162 def __repr__(self):
164 return "<alias {} for {!r}>".format(self.name, self.cmd)
163 return "<alias {} for {!r}>".format(self.name, self.cmd)
165
164
166 def __call__(self, rest=''):
165 def __call__(self, rest=''):
167 cmd = self.cmd
166 cmd = self.cmd
168 nargs = self.nargs
167 nargs = self.nargs
169 # Expand the %l special to be the user's input line
168 # Expand the %l special to be the user's input line
170 if cmd.find('%l') >= 0:
169 if cmd.find('%l') >= 0:
171 cmd = cmd.replace('%l', rest)
170 cmd = cmd.replace('%l', rest)
172 rest = ''
171 rest = ''
173
172
174 if nargs==0:
173 if nargs==0:
175 if cmd.find('%%s') >= 1:
174 if cmd.find('%%s') >= 1:
176 cmd = cmd.replace('%%s', '%s')
175 cmd = cmd.replace('%%s', '%s')
177 # Simple, argument-less aliases
176 # Simple, argument-less aliases
178 cmd = '%s %s' % (cmd, rest)
177 cmd = '%s %s' % (cmd, rest)
179 else:
178 else:
180 # Handle aliases with positional arguments
179 # Handle aliases with positional arguments
181 args = rest.split(None, nargs)
180 args = rest.split(None, nargs)
182 if len(args) < nargs:
181 if len(args) < nargs:
183 raise UsageError('Alias <%s> requires %s arguments, %s given.' %
182 raise UsageError('Alias <%s> requires %s arguments, %s given.' %
184 (self.name, nargs, len(args)))
183 (self.name, nargs, len(args)))
185 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
184 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
186
185
187 self.shell.system(cmd)
186 self.shell.system(cmd)
188
187
189 #-----------------------------------------------------------------------------
188 #-----------------------------------------------------------------------------
190 # Main AliasManager class
189 # Main AliasManager class
191 #-----------------------------------------------------------------------------
190 #-----------------------------------------------------------------------------
192
191
193 class AliasManager(Configurable):
192 class AliasManager(Configurable):
194
193
195 default_aliases = List(default_aliases()).tag(config=True)
194 default_aliases = List(default_aliases()).tag(config=True)
196 user_aliases = List(default_value=[]).tag(config=True)
195 user_aliases = List(default_value=[]).tag(config=True)
197 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
196 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
198
197
199 def __init__(self, shell=None, **kwargs):
198 def __init__(self, shell=None, **kwargs):
200 super(AliasManager, self).__init__(shell=shell, **kwargs)
199 super(AliasManager, self).__init__(shell=shell, **kwargs)
201 # For convenient access
200 # For convenient access
202 self.linemagics = self.shell.magics_manager.magics['line']
201 self.linemagics = self.shell.magics_manager.magics['line']
203 self.init_aliases()
202 self.init_aliases()
204
203
205 def init_aliases(self):
204 def init_aliases(self):
206 # Load default & user aliases
205 # Load default & user aliases
207 for name, cmd in self.default_aliases + self.user_aliases:
206 for name, cmd in self.default_aliases + self.user_aliases:
208 self.soft_define_alias(name, cmd)
207 self.soft_define_alias(name, cmd)
209
208
210 @property
209 @property
211 def aliases(self):
210 def aliases(self):
212 return [(n, func.cmd) for (n, func) in self.linemagics.items()
211 return [(n, func.cmd) for (n, func) in self.linemagics.items()
213 if isinstance(func, Alias)]
212 if isinstance(func, Alias)]
214
213
215 def soft_define_alias(self, name, cmd):
214 def soft_define_alias(self, name, cmd):
216 """Define an alias, but don't raise on an AliasError."""
215 """Define an alias, but don't raise on an AliasError."""
217 try:
216 try:
218 self.define_alias(name, cmd)
217 self.define_alias(name, cmd)
219 except AliasError as e:
218 except AliasError as e:
220 error("Invalid alias: %s" % e)
219 error("Invalid alias: %s" % e)
221
220
222 def define_alias(self, name, cmd):
221 def define_alias(self, name, cmd):
223 """Define a new alias after validating it.
222 """Define a new alias after validating it.
224
223
225 This will raise an :exc:`AliasError` if there are validation
224 This will raise an :exc:`AliasError` if there are validation
226 problems.
225 problems.
227 """
226 """
228 caller = Alias(shell=self.shell, name=name, cmd=cmd)
227 caller = Alias(shell=self.shell, name=name, cmd=cmd)
229 self.shell.magics_manager.register_function(caller, magic_kind='line',
228 self.shell.magics_manager.register_function(caller, magic_kind='line',
230 magic_name=name)
229 magic_name=name)
231
230
232 def get_alias(self, name):
231 def get_alias(self, name):
233 """Return an alias, or None if no alias by that name exists."""
232 """Return an alias, or None if no alias by that name exists."""
234 aname = self.linemagics.get(name, None)
233 aname = self.linemagics.get(name, None)
235 return aname if isinstance(aname, Alias) else None
234 return aname if isinstance(aname, Alias) else None
236
235
237 def is_alias(self, name):
236 def is_alias(self, name):
238 """Return whether or not a given name has been defined as an alias"""
237 """Return whether or not a given name has been defined as an alias"""
239 return self.get_alias(name) is not None
238 return self.get_alias(name) is not None
240
239
241 def undefine_alias(self, name):
240 def undefine_alias(self, name):
242 if self.is_alias(name):
241 if self.is_alias(name):
243 del self.linemagics[name]
242 del self.linemagics[name]
244 else:
243 else:
245 raise ValueError('%s is not an alias' % name)
244 raise ValueError('%s is not an alias' % name)
246
245
247 def clear_aliases(self):
246 def clear_aliases(self):
248 for name, cmd in self.aliases:
247 for name, cmd in self.aliases:
249 self.undefine_alias(name)
248 self.undefine_alias(name)
250
249
251 def retrieve_alias(self, name):
250 def retrieve_alias(self, name):
252 """Retrieve the command to which an alias expands."""
251 """Retrieve the command to which an alias expands."""
253 caller = self.get_alias(name)
252 caller = self.get_alias(name)
254 if caller:
253 if caller:
255 return caller.cmd
254 return caller.cmd
256 else:
255 else:
257 raise ValueError('%s is not an alias' % name)
256 raise ValueError('%s is not an alias' % name)
@@ -1,458 +1,458 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 An application for IPython.
3 An application for IPython.
4
4
5 All top-level applications should use the classes in this module for
5 All top-level applications should use the classes in this module for
6 handling configuration and creating configurables.
6 handling configuration and creating configurables.
7
7
8 The job of an :class:`Application` is to create the master configuration
8 The job of an :class:`Application` is to create the master configuration
9 object and then create the configurable objects, passing the config to them.
9 object and then create the configurable objects, passing the config to them.
10 """
10 """
11
11
12 # Copyright (c) IPython Development Team.
12 # Copyright (c) IPython Development Team.
13 # Distributed under the terms of the Modified BSD License.
13 # Distributed under the terms of the Modified BSD License.
14
14
15 import atexit
15 import atexit
16 from copy import deepcopy
16 from copy import deepcopy
17 import glob
17 import glob
18 import logging
18 import logging
19 import os
19 import os
20 import shutil
20 import shutil
21 import sys
21 import sys
22
22
23 from traitlets.config.application import Application, catch_config_error
23 from traitlets.config.application import Application, catch_config_error
24 from traitlets.config.loader import ConfigFileNotFound, PyFileConfigLoader
24 from traitlets.config.loader import ConfigFileNotFound, PyFileConfigLoader
25 from IPython.core import release, crashhandler
25 from IPython.core import release, crashhandler
26 from IPython.core.profiledir import ProfileDir, ProfileDirError
26 from IPython.core.profiledir import ProfileDir, ProfileDirError
27 from IPython.paths import get_ipython_dir, get_ipython_package_dir
27 from IPython.paths import get_ipython_dir, get_ipython_package_dir
28 from IPython.utils.path import ensure_dir_exists
28 from IPython.utils.path import ensure_dir_exists
29 from IPython.utils import py3compat
29 from IPython.utils import py3compat
30 from traitlets import (
30 from traitlets import (
31 List, Unicode, Type, Bool, Dict, Set, Instance, Undefined,
31 List, Unicode, Type, Bool, Dict, Set, Instance, Undefined,
32 default, observe,
32 default, observe,
33 )
33 )
34
34
35 if os.name == 'nt':
35 if os.name == 'nt':
36 programdata = os.environ.get('PROGRAMDATA', None)
36 programdata = os.environ.get('PROGRAMDATA', None)
37 if programdata:
37 if programdata:
38 SYSTEM_CONFIG_DIRS = [os.path.join(programdata, 'ipython')]
38 SYSTEM_CONFIG_DIRS = [os.path.join(programdata, 'ipython')]
39 else: # PROGRAMDATA is not defined by default on XP.
39 else: # PROGRAMDATA is not defined by default on XP.
40 SYSTEM_CONFIG_DIRS = []
40 SYSTEM_CONFIG_DIRS = []
41 else:
41 else:
42 SYSTEM_CONFIG_DIRS = [
42 SYSTEM_CONFIG_DIRS = [
43 "/usr/local/etc/ipython",
43 "/usr/local/etc/ipython",
44 "/etc/ipython",
44 "/etc/ipython",
45 ]
45 ]
46
46
47 _envvar = os.environ.get('IPYTHON_SUPPRESS_CONFIG_ERRORS')
47 _envvar = os.environ.get('IPYTHON_SUPPRESS_CONFIG_ERRORS')
48 if _envvar in {None, ''}:
48 if _envvar in {None, ''}:
49 IPYTHON_SUPPRESS_CONFIG_ERRORS = None
49 IPYTHON_SUPPRESS_CONFIG_ERRORS = None
50 else:
50 else:
51 if _envvar.lower() in {'1','true'}:
51 if _envvar.lower() in {'1','true'}:
52 IPYTHON_SUPPRESS_CONFIG_ERRORS = True
52 IPYTHON_SUPPRESS_CONFIG_ERRORS = True
53 elif _envvar.lower() in {'0','false'} :
53 elif _envvar.lower() in {'0','false'} :
54 IPYTHON_SUPPRESS_CONFIG_ERRORS = False
54 IPYTHON_SUPPRESS_CONFIG_ERRORS = False
55 else:
55 else:
56 sys.exit("Unsupported value for environment variable: 'IPYTHON_SUPPRESS_CONFIG_ERRORS' is set to '%s' which is none of {'0', '1', 'false', 'true', ''}."% _envvar )
56 sys.exit("Unsupported value for environment variable: 'IPYTHON_SUPPRESS_CONFIG_ERRORS' is set to '%s' which is none of {'0', '1', 'false', 'true', ''}."% _envvar )
57
57
58 # aliases and flags
58 # aliases and flags
59
59
60 base_aliases = {
60 base_aliases = {
61 'profile-dir' : 'ProfileDir.location',
61 'profile-dir' : 'ProfileDir.location',
62 'profile' : 'BaseIPythonApplication.profile',
62 'profile' : 'BaseIPythonApplication.profile',
63 'ipython-dir' : 'BaseIPythonApplication.ipython_dir',
63 'ipython-dir' : 'BaseIPythonApplication.ipython_dir',
64 'log-level' : 'Application.log_level',
64 'log-level' : 'Application.log_level',
65 'config' : 'BaseIPythonApplication.extra_config_file',
65 'config' : 'BaseIPythonApplication.extra_config_file',
66 }
66 }
67
67
68 base_flags = dict(
68 base_flags = dict(
69 debug = ({'Application' : {'log_level' : logging.DEBUG}},
69 debug = ({'Application' : {'log_level' : logging.DEBUG}},
70 "set log level to logging.DEBUG (maximize logging output)"),
70 "set log level to logging.DEBUG (maximize logging output)"),
71 quiet = ({'Application' : {'log_level' : logging.CRITICAL}},
71 quiet = ({'Application' : {'log_level' : logging.CRITICAL}},
72 "set log level to logging.CRITICAL (minimize logging output)"),
72 "set log level to logging.CRITICAL (minimize logging output)"),
73 init = ({'BaseIPythonApplication' : {
73 init = ({'BaseIPythonApplication' : {
74 'copy_config_files' : True,
74 'copy_config_files' : True,
75 'auto_create' : True}
75 'auto_create' : True}
76 }, """Initialize profile with default config files. This is equivalent
76 }, """Initialize profile with default config files. This is equivalent
77 to running `ipython profile create <profile>` prior to startup.
77 to running `ipython profile create <profile>` prior to startup.
78 """)
78 """)
79 )
79 )
80
80
81 class ProfileAwareConfigLoader(PyFileConfigLoader):
81 class ProfileAwareConfigLoader(PyFileConfigLoader):
82 """A Python file config loader that is aware of IPython profiles."""
82 """A Python file config loader that is aware of IPython profiles."""
83 def load_subconfig(self, fname, path=None, profile=None):
83 def load_subconfig(self, fname, path=None, profile=None):
84 if profile is not None:
84 if profile is not None:
85 try:
85 try:
86 profile_dir = ProfileDir.find_profile_dir_by_name(
86 profile_dir = ProfileDir.find_profile_dir_by_name(
87 get_ipython_dir(),
87 get_ipython_dir(),
88 profile,
88 profile,
89 )
89 )
90 except ProfileDirError:
90 except ProfileDirError:
91 return
91 return
92 path = profile_dir.location
92 path = profile_dir.location
93 return super(ProfileAwareConfigLoader, self).load_subconfig(fname, path=path)
93 return super(ProfileAwareConfigLoader, self).load_subconfig(fname, path=path)
94
94
95 class BaseIPythonApplication(Application):
95 class BaseIPythonApplication(Application):
96
96
97 name = Unicode(u'ipython')
97 name = Unicode(u'ipython')
98 description = Unicode(u'IPython: an enhanced interactive Python shell.')
98 description = Unicode(u'IPython: an enhanced interactive Python shell.')
99 version = Unicode(release.version)
99 version = Unicode(release.version)
100
100
101 aliases = Dict(base_aliases)
101 aliases = Dict(base_aliases)
102 flags = Dict(base_flags)
102 flags = Dict(base_flags)
103 classes = List([ProfileDir])
103 classes = List([ProfileDir])
104
104
105 # enable `load_subconfig('cfg.py', profile='name')`
105 # enable `load_subconfig('cfg.py', profile='name')`
106 python_config_loader_class = ProfileAwareConfigLoader
106 python_config_loader_class = ProfileAwareConfigLoader
107
107
108 # Track whether the config_file has changed,
108 # Track whether the config_file has changed,
109 # because some logic happens only if we aren't using the default.
109 # because some logic happens only if we aren't using the default.
110 config_file_specified = Set()
110 config_file_specified = Set()
111
111
112 config_file_name = Unicode()
112 config_file_name = Unicode()
113 @default('config_file_name')
113 @default('config_file_name')
114 def _config_file_name_default(self):
114 def _config_file_name_default(self):
115 return self.name.replace('-','_') + u'_config.py'
115 return self.name.replace('-','_') + u'_config.py'
116 @observe('config_file_name')
116 @observe('config_file_name')
117 def _config_file_name_changed(self, change):
117 def _config_file_name_changed(self, change):
118 if change['new'] != change['old']:
118 if change['new'] != change['old']:
119 self.config_file_specified.add(change['new'])
119 self.config_file_specified.add(change['new'])
120
120
121 # The directory that contains IPython's builtin profiles.
121 # The directory that contains IPython's builtin profiles.
122 builtin_profile_dir = Unicode(
122 builtin_profile_dir = Unicode(
123 os.path.join(get_ipython_package_dir(), u'config', u'profile', u'default')
123 os.path.join(get_ipython_package_dir(), u'config', u'profile', u'default')
124 )
124 )
125
125
126 config_file_paths = List(Unicode())
126 config_file_paths = List(Unicode())
127 @default('config_file_paths')
127 @default('config_file_paths')
128 def _config_file_paths_default(self):
128 def _config_file_paths_default(self):
129 return [py3compat.getcwd()]
129 return [os.getcwd()]
130
130
131 extra_config_file = Unicode(
131 extra_config_file = Unicode(
132 help="""Path to an extra config file to load.
132 help="""Path to an extra config file to load.
133
133
134 If specified, load this config file in addition to any other IPython config.
134 If specified, load this config file in addition to any other IPython config.
135 """).tag(config=True)
135 """).tag(config=True)
136 @observe('extra_config_file')
136 @observe('extra_config_file')
137 def _extra_config_file_changed(self, change):
137 def _extra_config_file_changed(self, change):
138 old = change['old']
138 old = change['old']
139 new = change['new']
139 new = change['new']
140 try:
140 try:
141 self.config_files.remove(old)
141 self.config_files.remove(old)
142 except ValueError:
142 except ValueError:
143 pass
143 pass
144 self.config_file_specified.add(new)
144 self.config_file_specified.add(new)
145 self.config_files.append(new)
145 self.config_files.append(new)
146
146
147 profile = Unicode(u'default',
147 profile = Unicode(u'default',
148 help="""The IPython profile to use."""
148 help="""The IPython profile to use."""
149 ).tag(config=True)
149 ).tag(config=True)
150
150
151 @observe('profile')
151 @observe('profile')
152 def _profile_changed(self, change):
152 def _profile_changed(self, change):
153 self.builtin_profile_dir = os.path.join(
153 self.builtin_profile_dir = os.path.join(
154 get_ipython_package_dir(), u'config', u'profile', change['new']
154 get_ipython_package_dir(), u'config', u'profile', change['new']
155 )
155 )
156
156
157 ipython_dir = Unicode(
157 ipython_dir = Unicode(
158 help="""
158 help="""
159 The name of the IPython directory. This directory is used for logging
159 The name of the IPython directory. This directory is used for logging
160 configuration (through profiles), history storage, etc. The default
160 configuration (through profiles), history storage, etc. The default
161 is usually $HOME/.ipython. This option can also be specified through
161 is usually $HOME/.ipython. This option can also be specified through
162 the environment variable IPYTHONDIR.
162 the environment variable IPYTHONDIR.
163 """
163 """
164 ).tag(config=True)
164 ).tag(config=True)
165 @default('ipython_dir')
165 @default('ipython_dir')
166 def _ipython_dir_default(self):
166 def _ipython_dir_default(self):
167 d = get_ipython_dir()
167 d = get_ipython_dir()
168 self._ipython_dir_changed({
168 self._ipython_dir_changed({
169 'name': 'ipython_dir',
169 'name': 'ipython_dir',
170 'old': d,
170 'old': d,
171 'new': d,
171 'new': d,
172 })
172 })
173 return d
173 return d
174
174
175 _in_init_profile_dir = False
175 _in_init_profile_dir = False
176 profile_dir = Instance(ProfileDir, allow_none=True)
176 profile_dir = Instance(ProfileDir, allow_none=True)
177 @default('profile_dir')
177 @default('profile_dir')
178 def _profile_dir_default(self):
178 def _profile_dir_default(self):
179 # avoid recursion
179 # avoid recursion
180 if self._in_init_profile_dir:
180 if self._in_init_profile_dir:
181 return
181 return
182 # profile_dir requested early, force initialization
182 # profile_dir requested early, force initialization
183 self.init_profile_dir()
183 self.init_profile_dir()
184 return self.profile_dir
184 return self.profile_dir
185
185
186 overwrite = Bool(False,
186 overwrite = Bool(False,
187 help="""Whether to overwrite existing config files when copying"""
187 help="""Whether to overwrite existing config files when copying"""
188 ).tag(config=True)
188 ).tag(config=True)
189 auto_create = Bool(False,
189 auto_create = Bool(False,
190 help="""Whether to create profile dir if it doesn't exist"""
190 help="""Whether to create profile dir if it doesn't exist"""
191 ).tag(config=True)
191 ).tag(config=True)
192
192
193 config_files = List(Unicode())
193 config_files = List(Unicode())
194 @default('config_files')
194 @default('config_files')
195 def _config_files_default(self):
195 def _config_files_default(self):
196 return [self.config_file_name]
196 return [self.config_file_name]
197
197
198 copy_config_files = Bool(False,
198 copy_config_files = Bool(False,
199 help="""Whether to install the default config files into the profile dir.
199 help="""Whether to install the default config files into the profile dir.
200 If a new profile is being created, and IPython contains config files for that
200 If a new profile is being created, and IPython contains config files for that
201 profile, then they will be staged into the new directory. Otherwise,
201 profile, then they will be staged into the new directory. Otherwise,
202 default config files will be automatically generated.
202 default config files will be automatically generated.
203 """).tag(config=True)
203 """).tag(config=True)
204
204
205 verbose_crash = Bool(False,
205 verbose_crash = Bool(False,
206 help="""Create a massive crash report when IPython encounters what may be an
206 help="""Create a massive crash report when IPython encounters what may be an
207 internal error. The default is to append a short message to the
207 internal error. The default is to append a short message to the
208 usual traceback""").tag(config=True)
208 usual traceback""").tag(config=True)
209
209
210 # The class to use as the crash handler.
210 # The class to use as the crash handler.
211 crash_handler_class = Type(crashhandler.CrashHandler)
211 crash_handler_class = Type(crashhandler.CrashHandler)
212
212
213 @catch_config_error
213 @catch_config_error
214 def __init__(self, **kwargs):
214 def __init__(self, **kwargs):
215 super(BaseIPythonApplication, self).__init__(**kwargs)
215 super(BaseIPythonApplication, self).__init__(**kwargs)
216 # ensure current working directory exists
216 # ensure current working directory exists
217 try:
217 try:
218 py3compat.getcwd()
218 os.getcwd()
219 except:
219 except:
220 # exit if cwd doesn't exist
220 # exit if cwd doesn't exist
221 self.log.error("Current working directory doesn't exist.")
221 self.log.error("Current working directory doesn't exist.")
222 self.exit(1)
222 self.exit(1)
223
223
224 #-------------------------------------------------------------------------
224 #-------------------------------------------------------------------------
225 # Various stages of Application creation
225 # Various stages of Application creation
226 #-------------------------------------------------------------------------
226 #-------------------------------------------------------------------------
227
227
228 deprecated_subcommands = {}
228 deprecated_subcommands = {}
229
229
230 def initialize_subcommand(self, subc, argv=None):
230 def initialize_subcommand(self, subc, argv=None):
231 if subc in self.deprecated_subcommands:
231 if subc in self.deprecated_subcommands:
232 self.log.warning("Subcommand `ipython {sub}` is deprecated and will be removed "
232 self.log.warning("Subcommand `ipython {sub}` is deprecated and will be removed "
233 "in future versions.".format(sub=subc))
233 "in future versions.".format(sub=subc))
234 self.log.warning("You likely want to use `jupyter {sub}` in the "
234 self.log.warning("You likely want to use `jupyter {sub}` in the "
235 "future".format(sub=subc))
235 "future".format(sub=subc))
236 return super(BaseIPythonApplication, self).initialize_subcommand(subc, argv)
236 return super(BaseIPythonApplication, self).initialize_subcommand(subc, argv)
237
237
238 def init_crash_handler(self):
238 def init_crash_handler(self):
239 """Create a crash handler, typically setting sys.excepthook to it."""
239 """Create a crash handler, typically setting sys.excepthook to it."""
240 self.crash_handler = self.crash_handler_class(self)
240 self.crash_handler = self.crash_handler_class(self)
241 sys.excepthook = self.excepthook
241 sys.excepthook = self.excepthook
242 def unset_crashhandler():
242 def unset_crashhandler():
243 sys.excepthook = sys.__excepthook__
243 sys.excepthook = sys.__excepthook__
244 atexit.register(unset_crashhandler)
244 atexit.register(unset_crashhandler)
245
245
246 def excepthook(self, etype, evalue, tb):
246 def excepthook(self, etype, evalue, tb):
247 """this is sys.excepthook after init_crashhandler
247 """this is sys.excepthook after init_crashhandler
248
248
249 set self.verbose_crash=True to use our full crashhandler, instead of
249 set self.verbose_crash=True to use our full crashhandler, instead of
250 a regular traceback with a short message (crash_handler_lite)
250 a regular traceback with a short message (crash_handler_lite)
251 """
251 """
252
252
253 if self.verbose_crash:
253 if self.verbose_crash:
254 return self.crash_handler(etype, evalue, tb)
254 return self.crash_handler(etype, evalue, tb)
255 else:
255 else:
256 return crashhandler.crash_handler_lite(etype, evalue, tb)
256 return crashhandler.crash_handler_lite(etype, evalue, tb)
257
257
258 @observe('ipython_dir')
258 @observe('ipython_dir')
259 def _ipython_dir_changed(self, change):
259 def _ipython_dir_changed(self, change):
260 old = change['old']
260 old = change['old']
261 new = change['new']
261 new = change['new']
262 if old is not Undefined:
262 if old is not Undefined:
263 str_old = py3compat.cast_bytes_py2(os.path.abspath(old),
263 str_old = py3compat.cast_bytes_py2(os.path.abspath(old),
264 sys.getfilesystemencoding()
264 sys.getfilesystemencoding()
265 )
265 )
266 if str_old in sys.path:
266 if str_old in sys.path:
267 sys.path.remove(str_old)
267 sys.path.remove(str_old)
268 str_path = py3compat.cast_bytes_py2(os.path.abspath(new),
268 str_path = py3compat.cast_bytes_py2(os.path.abspath(new),
269 sys.getfilesystemencoding()
269 sys.getfilesystemencoding()
270 )
270 )
271 sys.path.append(str_path)
271 sys.path.append(str_path)
272 ensure_dir_exists(new)
272 ensure_dir_exists(new)
273 readme = os.path.join(new, 'README')
273 readme = os.path.join(new, 'README')
274 readme_src = os.path.join(get_ipython_package_dir(), u'config', u'profile', 'README')
274 readme_src = os.path.join(get_ipython_package_dir(), u'config', u'profile', 'README')
275 if not os.path.exists(readme) and os.path.exists(readme_src):
275 if not os.path.exists(readme) and os.path.exists(readme_src):
276 shutil.copy(readme_src, readme)
276 shutil.copy(readme_src, readme)
277 for d in ('extensions', 'nbextensions'):
277 for d in ('extensions', 'nbextensions'):
278 path = os.path.join(new, d)
278 path = os.path.join(new, d)
279 try:
279 try:
280 ensure_dir_exists(path)
280 ensure_dir_exists(path)
281 except OSError as e:
281 except OSError as e:
282 # this will not be EEXIST
282 # this will not be EEXIST
283 self.log.error("couldn't create path %s: %s", path, e)
283 self.log.error("couldn't create path %s: %s", path, e)
284 self.log.debug("IPYTHONDIR set to: %s" % new)
284 self.log.debug("IPYTHONDIR set to: %s" % new)
285
285
286 def load_config_file(self, suppress_errors=IPYTHON_SUPPRESS_CONFIG_ERRORS):
286 def load_config_file(self, suppress_errors=IPYTHON_SUPPRESS_CONFIG_ERRORS):
287 """Load the config file.
287 """Load the config file.
288
288
289 By default, errors in loading config are handled, and a warning
289 By default, errors in loading config are handled, and a warning
290 printed on screen. For testing, the suppress_errors option is set
290 printed on screen. For testing, the suppress_errors option is set
291 to False, so errors will make tests fail.
291 to False, so errors will make tests fail.
292
292
293 `supress_errors` default value is to be `None` in which case the
293 `supress_errors` default value is to be `None` in which case the
294 behavior default to the one of `traitlets.Application`.
294 behavior default to the one of `traitlets.Application`.
295
295
296 The default value can be set :
296 The default value can be set :
297 - to `False` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '0', or 'false' (case insensitive).
297 - to `False` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '0', or 'false' (case insensitive).
298 - to `True` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '1' or 'true' (case insensitive).
298 - to `True` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '1' or 'true' (case insensitive).
299 - to `None` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '' (empty string) or leaving it unset.
299 - to `None` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '' (empty string) or leaving it unset.
300
300
301 Any other value are invalid, and will make IPython exit with a non-zero return code.
301 Any other value are invalid, and will make IPython exit with a non-zero return code.
302 """
302 """
303
303
304
304
305 self.log.debug("Searching path %s for config files", self.config_file_paths)
305 self.log.debug("Searching path %s for config files", self.config_file_paths)
306 base_config = 'ipython_config.py'
306 base_config = 'ipython_config.py'
307 self.log.debug("Attempting to load config file: %s" %
307 self.log.debug("Attempting to load config file: %s" %
308 base_config)
308 base_config)
309 try:
309 try:
310 if suppress_errors is not None:
310 if suppress_errors is not None:
311 old_value = Application.raise_config_file_errors
311 old_value = Application.raise_config_file_errors
312 Application.raise_config_file_errors = not suppress_errors;
312 Application.raise_config_file_errors = not suppress_errors;
313 Application.load_config_file(
313 Application.load_config_file(
314 self,
314 self,
315 base_config,
315 base_config,
316 path=self.config_file_paths
316 path=self.config_file_paths
317 )
317 )
318 except ConfigFileNotFound:
318 except ConfigFileNotFound:
319 # ignore errors loading parent
319 # ignore errors loading parent
320 self.log.debug("Config file %s not found", base_config)
320 self.log.debug("Config file %s not found", base_config)
321 pass
321 pass
322 if suppress_errors is not None:
322 if suppress_errors is not None:
323 Application.raise_config_file_errors = old_value
323 Application.raise_config_file_errors = old_value
324
324
325 for config_file_name in self.config_files:
325 for config_file_name in self.config_files:
326 if not config_file_name or config_file_name == base_config:
326 if not config_file_name or config_file_name == base_config:
327 continue
327 continue
328 self.log.debug("Attempting to load config file: %s" %
328 self.log.debug("Attempting to load config file: %s" %
329 self.config_file_name)
329 self.config_file_name)
330 try:
330 try:
331 Application.load_config_file(
331 Application.load_config_file(
332 self,
332 self,
333 config_file_name,
333 config_file_name,
334 path=self.config_file_paths
334 path=self.config_file_paths
335 )
335 )
336 except ConfigFileNotFound:
336 except ConfigFileNotFound:
337 # Only warn if the default config file was NOT being used.
337 # Only warn if the default config file was NOT being used.
338 if config_file_name in self.config_file_specified:
338 if config_file_name in self.config_file_specified:
339 msg = self.log.warning
339 msg = self.log.warning
340 else:
340 else:
341 msg = self.log.debug
341 msg = self.log.debug
342 msg("Config file not found, skipping: %s", config_file_name)
342 msg("Config file not found, skipping: %s", config_file_name)
343 except Exception:
343 except Exception:
344 # For testing purposes.
344 # For testing purposes.
345 if not suppress_errors:
345 if not suppress_errors:
346 raise
346 raise
347 self.log.warning("Error loading config file: %s" %
347 self.log.warning("Error loading config file: %s" %
348 self.config_file_name, exc_info=True)
348 self.config_file_name, exc_info=True)
349
349
350 def init_profile_dir(self):
350 def init_profile_dir(self):
351 """initialize the profile dir"""
351 """initialize the profile dir"""
352 self._in_init_profile_dir = True
352 self._in_init_profile_dir = True
353 if self.profile_dir is not None:
353 if self.profile_dir is not None:
354 # already ran
354 # already ran
355 return
355 return
356 if 'ProfileDir.location' not in self.config:
356 if 'ProfileDir.location' not in self.config:
357 # location not specified, find by profile name
357 # location not specified, find by profile name
358 try:
358 try:
359 p = ProfileDir.find_profile_dir_by_name(self.ipython_dir, self.profile, self.config)
359 p = ProfileDir.find_profile_dir_by_name(self.ipython_dir, self.profile, self.config)
360 except ProfileDirError:
360 except ProfileDirError:
361 # not found, maybe create it (always create default profile)
361 # not found, maybe create it (always create default profile)
362 if self.auto_create or self.profile == 'default':
362 if self.auto_create or self.profile == 'default':
363 try:
363 try:
364 p = ProfileDir.create_profile_dir_by_name(self.ipython_dir, self.profile, self.config)
364 p = ProfileDir.create_profile_dir_by_name(self.ipython_dir, self.profile, self.config)
365 except ProfileDirError:
365 except ProfileDirError:
366 self.log.fatal("Could not create profile: %r"%self.profile)
366 self.log.fatal("Could not create profile: %r"%self.profile)
367 self.exit(1)
367 self.exit(1)
368 else:
368 else:
369 self.log.info("Created profile dir: %r"%p.location)
369 self.log.info("Created profile dir: %r"%p.location)
370 else:
370 else:
371 self.log.fatal("Profile %r not found."%self.profile)
371 self.log.fatal("Profile %r not found."%self.profile)
372 self.exit(1)
372 self.exit(1)
373 else:
373 else:
374 self.log.debug("Using existing profile dir: %r"%p.location)
374 self.log.debug("Using existing profile dir: %r"%p.location)
375 else:
375 else:
376 location = self.config.ProfileDir.location
376 location = self.config.ProfileDir.location
377 # location is fully specified
377 # location is fully specified
378 try:
378 try:
379 p = ProfileDir.find_profile_dir(location, self.config)
379 p = ProfileDir.find_profile_dir(location, self.config)
380 except ProfileDirError:
380 except ProfileDirError:
381 # not found, maybe create it
381 # not found, maybe create it
382 if self.auto_create:
382 if self.auto_create:
383 try:
383 try:
384 p = ProfileDir.create_profile_dir(location, self.config)
384 p = ProfileDir.create_profile_dir(location, self.config)
385 except ProfileDirError:
385 except ProfileDirError:
386 self.log.fatal("Could not create profile directory: %r"%location)
386 self.log.fatal("Could not create profile directory: %r"%location)
387 self.exit(1)
387 self.exit(1)
388 else:
388 else:
389 self.log.debug("Creating new profile dir: %r"%location)
389 self.log.debug("Creating new profile dir: %r"%location)
390 else:
390 else:
391 self.log.fatal("Profile directory %r not found."%location)
391 self.log.fatal("Profile directory %r not found."%location)
392 self.exit(1)
392 self.exit(1)
393 else:
393 else:
394 self.log.info("Using existing profile dir: %r"%location)
394 self.log.info("Using existing profile dir: %r"%location)
395 # if profile_dir is specified explicitly, set profile name
395 # if profile_dir is specified explicitly, set profile name
396 dir_name = os.path.basename(p.location)
396 dir_name = os.path.basename(p.location)
397 if dir_name.startswith('profile_'):
397 if dir_name.startswith('profile_'):
398 self.profile = dir_name[8:]
398 self.profile = dir_name[8:]
399
399
400 self.profile_dir = p
400 self.profile_dir = p
401 self.config_file_paths.append(p.location)
401 self.config_file_paths.append(p.location)
402 self._in_init_profile_dir = False
402 self._in_init_profile_dir = False
403
403
404 def init_config_files(self):
404 def init_config_files(self):
405 """[optionally] copy default config files into profile dir."""
405 """[optionally] copy default config files into profile dir."""
406 self.config_file_paths.extend(SYSTEM_CONFIG_DIRS)
406 self.config_file_paths.extend(SYSTEM_CONFIG_DIRS)
407 # copy config files
407 # copy config files
408 path = self.builtin_profile_dir
408 path = self.builtin_profile_dir
409 if self.copy_config_files:
409 if self.copy_config_files:
410 src = self.profile
410 src = self.profile
411
411
412 cfg = self.config_file_name
412 cfg = self.config_file_name
413 if path and os.path.exists(os.path.join(path, cfg)):
413 if path and os.path.exists(os.path.join(path, cfg)):
414 self.log.warning("Staging %r from %s into %r [overwrite=%s]"%(
414 self.log.warning("Staging %r from %s into %r [overwrite=%s]"%(
415 cfg, src, self.profile_dir.location, self.overwrite)
415 cfg, src, self.profile_dir.location, self.overwrite)
416 )
416 )
417 self.profile_dir.copy_config_file(cfg, path=path, overwrite=self.overwrite)
417 self.profile_dir.copy_config_file(cfg, path=path, overwrite=self.overwrite)
418 else:
418 else:
419 self.stage_default_config_file()
419 self.stage_default_config_file()
420 else:
420 else:
421 # Still stage *bundled* config files, but not generated ones
421 # Still stage *bundled* config files, but not generated ones
422 # This is necessary for `ipython profile=sympy` to load the profile
422 # This is necessary for `ipython profile=sympy` to load the profile
423 # on the first go
423 # on the first go
424 files = glob.glob(os.path.join(path, '*.py'))
424 files = glob.glob(os.path.join(path, '*.py'))
425 for fullpath in files:
425 for fullpath in files:
426 cfg = os.path.basename(fullpath)
426 cfg = os.path.basename(fullpath)
427 if self.profile_dir.copy_config_file(cfg, path=path, overwrite=False):
427 if self.profile_dir.copy_config_file(cfg, path=path, overwrite=False):
428 # file was copied
428 # file was copied
429 self.log.warning("Staging bundled %s from %s into %r"%(
429 self.log.warning("Staging bundled %s from %s into %r"%(
430 cfg, self.profile, self.profile_dir.location)
430 cfg, self.profile, self.profile_dir.location)
431 )
431 )
432
432
433
433
434 def stage_default_config_file(self):
434 def stage_default_config_file(self):
435 """auto generate default config file, and stage it into the profile."""
435 """auto generate default config file, and stage it into the profile."""
436 s = self.generate_config_file()
436 s = self.generate_config_file()
437 fname = os.path.join(self.profile_dir.location, self.config_file_name)
437 fname = os.path.join(self.profile_dir.location, self.config_file_name)
438 if self.overwrite or not os.path.exists(fname):
438 if self.overwrite or not os.path.exists(fname):
439 self.log.warning("Generating default config file: %r"%(fname))
439 self.log.warning("Generating default config file: %r"%(fname))
440 with open(fname, 'w') as f:
440 with open(fname, 'w') as f:
441 f.write(s)
441 f.write(s)
442
442
443 @catch_config_error
443 @catch_config_error
444 def initialize(self, argv=None):
444 def initialize(self, argv=None):
445 # don't hook up crash handler before parsing command-line
445 # don't hook up crash handler before parsing command-line
446 self.parse_command_line(argv)
446 self.parse_command_line(argv)
447 self.init_crash_handler()
447 self.init_crash_handler()
448 if self.subapp is not None:
448 if self.subapp is not None:
449 # stop here if subapp is taking over
449 # stop here if subapp is taking over
450 return
450 return
451 # save a copy of CLI config to re-load after config files
451 # save a copy of CLI config to re-load after config files
452 # so that it has highest priority
452 # so that it has highest priority
453 cl_config = deepcopy(self.config)
453 cl_config = deepcopy(self.config)
454 self.init_profile_dir()
454 self.init_profile_dir()
455 self.init_config_files()
455 self.init_config_files()
456 self.load_config_file()
456 self.load_config_file()
457 # enforce cl-opts override configfile opts:
457 # enforce cl-opts override configfile opts:
458 self.update_config(cl_config)
458 self.update_config(cl_config)
@@ -1,103 +1,103 b''
1 """
1 """
2 A context manager for managing things injected into :mod:`__builtin__`.
2 A context manager for managing things injected into :mod:`__builtin__`.
3
3
4 Authors:
4 Authors:
5
5
6 * Brian Granger
6 * Brian Granger
7 * Fernando Perez
7 * Fernando Perez
8 """
8 """
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10 # Copyright (C) 2010-2011 The IPython Development Team.
10 # Copyright (C) 2010-2011 The IPython Development Team.
11 #
11 #
12 # Distributed under the terms of the BSD License.
12 # Distributed under the terms of the BSD License.
13 #
13 #
14 # Complete license in the file COPYING.txt, distributed with this software.
14 # Complete license in the file COPYING.txt, distributed with this software.
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18 # Imports
18 # Imports
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20
20
21 from traitlets.config.configurable import Configurable
21 from traitlets.config.configurable import Configurable
22
22
23 from IPython.utils.py3compat import builtin_mod, iteritems
23 from IPython.utils.py3compat import builtin_mod
24 from traitlets import Instance
24 from traitlets import Instance
25
25
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27 # Classes and functions
27 # Classes and functions
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29
29
30 class __BuiltinUndefined(object): pass
30 class __BuiltinUndefined(object): pass
31 BuiltinUndefined = __BuiltinUndefined()
31 BuiltinUndefined = __BuiltinUndefined()
32
32
33 class __HideBuiltin(object): pass
33 class __HideBuiltin(object): pass
34 HideBuiltin = __HideBuiltin()
34 HideBuiltin = __HideBuiltin()
35
35
36
36
37 class BuiltinTrap(Configurable):
37 class BuiltinTrap(Configurable):
38
38
39 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
39 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
40 allow_none=True)
40 allow_none=True)
41
41
42 def __init__(self, shell=None):
42 def __init__(self, shell=None):
43 super(BuiltinTrap, self).__init__(shell=shell, config=None)
43 super(BuiltinTrap, self).__init__(shell=shell, config=None)
44 self._orig_builtins = {}
44 self._orig_builtins = {}
45 # We define this to track if a single BuiltinTrap is nested.
45 # We define this to track if a single BuiltinTrap is nested.
46 # Only turn off the trap when the outermost call to __exit__ is made.
46 # Only turn off the trap when the outermost call to __exit__ is made.
47 self._nested_level = 0
47 self._nested_level = 0
48 self.shell = shell
48 self.shell = shell
49 # builtins we always add - if set to HideBuiltin, they will just
49 # builtins we always add - if set to HideBuiltin, they will just
50 # be removed instead of being replaced by something else
50 # be removed instead of being replaced by something else
51 self.auto_builtins = {'exit': HideBuiltin,
51 self.auto_builtins = {'exit': HideBuiltin,
52 'quit': HideBuiltin,
52 'quit': HideBuiltin,
53 'get_ipython': self.shell.get_ipython,
53 'get_ipython': self.shell.get_ipython,
54 }
54 }
55
55
56 def __enter__(self):
56 def __enter__(self):
57 if self._nested_level == 0:
57 if self._nested_level == 0:
58 self.activate()
58 self.activate()
59 self._nested_level += 1
59 self._nested_level += 1
60 # I return self, so callers can use add_builtin in a with clause.
60 # I return self, so callers can use add_builtin in a with clause.
61 return self
61 return self
62
62
63 def __exit__(self, type, value, traceback):
63 def __exit__(self, type, value, traceback):
64 if self._nested_level == 1:
64 if self._nested_level == 1:
65 self.deactivate()
65 self.deactivate()
66 self._nested_level -= 1
66 self._nested_level -= 1
67 # Returning False will cause exceptions to propagate
67 # Returning False will cause exceptions to propagate
68 return False
68 return False
69
69
70 def add_builtin(self, key, value):
70 def add_builtin(self, key, value):
71 """Add a builtin and save the original."""
71 """Add a builtin and save the original."""
72 bdict = builtin_mod.__dict__
72 bdict = builtin_mod.__dict__
73 orig = bdict.get(key, BuiltinUndefined)
73 orig = bdict.get(key, BuiltinUndefined)
74 if value is HideBuiltin:
74 if value is HideBuiltin:
75 if orig is not BuiltinUndefined: #same as 'key in bdict'
75 if orig is not BuiltinUndefined: #same as 'key in bdict'
76 self._orig_builtins[key] = orig
76 self._orig_builtins[key] = orig
77 del bdict[key]
77 del bdict[key]
78 else:
78 else:
79 self._orig_builtins[key] = orig
79 self._orig_builtins[key] = orig
80 bdict[key] = value
80 bdict[key] = value
81
81
82 def remove_builtin(self, key, orig):
82 def remove_builtin(self, key, orig):
83 """Remove an added builtin and re-set the original."""
83 """Remove an added builtin and re-set the original."""
84 if orig is BuiltinUndefined:
84 if orig is BuiltinUndefined:
85 del builtin_mod.__dict__[key]
85 del builtin_mod.__dict__[key]
86 else:
86 else:
87 builtin_mod.__dict__[key] = orig
87 builtin_mod.__dict__[key] = orig
88
88
89 def activate(self):
89 def activate(self):
90 """Store ipython references in the __builtin__ namespace."""
90 """Store ipython references in the __builtin__ namespace."""
91
91
92 add_builtin = self.add_builtin
92 add_builtin = self.add_builtin
93 for name, func in iteritems(self.auto_builtins):
93 for name, func in self.auto_builtins.items():
94 add_builtin(name, func)
94 add_builtin(name, func)
95
95
96 def deactivate(self):
96 def deactivate(self):
97 """Remove any builtins which might have been added by add_builtins, or
97 """Remove any builtins which might have been added by add_builtins, or
98 restore overwritten ones to their previous values."""
98 restore overwritten ones to their previous values."""
99 remove_builtin = self.remove_builtin
99 remove_builtin = self.remove_builtin
100 for key, val in iteritems(self._orig_builtins):
100 for key, val in self._orig_builtins.items():
101 remove_builtin(key, val)
101 remove_builtin(key, val)
102 self._orig_builtins.clear()
102 self._orig_builtins.clear()
103 self._builtins_added = False
103 self._builtins_added = False
@@ -1,1229 +1,1229 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Word completion for IPython.
2 """Word completion for IPython.
3
3
4 This module started as fork of the rlcompleter module in the Python standard
4 This module started as fork of the rlcompleter module in the Python standard
5 library. The original enhancements made to rlcompleter have been sent
5 library. The original enhancements made to rlcompleter have been sent
6 upstream and were accepted as of Python 2.3,
6 upstream and were accepted as of Python 2.3,
7
7
8 """
8 """
9
9
10 # Copyright (c) IPython Development Team.
10 # Copyright (c) IPython Development Team.
11 # Distributed under the terms of the Modified BSD License.
11 # Distributed under the terms of the Modified BSD License.
12 #
12 #
13 # Some of this code originated from rlcompleter in the Python standard library
13 # Some of this code originated from rlcompleter in the Python standard library
14 # Copyright (C) 2001 Python Software Foundation, www.python.org
14 # Copyright (C) 2001 Python Software Foundation, www.python.org
15
15
16
16
17 import __main__
17 import __main__
18 import glob
18 import glob
19 import inspect
19 import inspect
20 import itertools
20 import itertools
21 import keyword
21 import keyword
22 import os
22 import os
23 import re
23 import re
24 import sys
24 import sys
25 import unicodedata
25 import unicodedata
26 import string
26 import string
27 import warnings
27 import warnings
28 from importlib import import_module
28 from importlib import import_module
29
29
30 from traitlets.config.configurable import Configurable
30 from traitlets.config.configurable import Configurable
31 from IPython.core.error import TryNext
31 from IPython.core.error import TryNext
32 from IPython.core.inputsplitter import ESC_MAGIC
32 from IPython.core.inputsplitter import ESC_MAGIC
33 from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
33 from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
34 from IPython.utils import generics
34 from IPython.utils import generics
35 from IPython.utils.decorators import undoc
35 from IPython.utils.decorators import undoc
36 from IPython.utils.dir2 import dir2, get_real_method
36 from IPython.utils.dir2 import dir2, get_real_method
37 from IPython.utils.process import arg_split
37 from IPython.utils.process import arg_split
38 from IPython.utils.py3compat import builtin_mod, string_types, PY3, cast_unicode_py2
38 from IPython.utils.py3compat import builtin_mod, PY3, cast_unicode_py2
39 from traitlets import Bool, Enum, observe
39 from traitlets import Bool, Enum, observe
40
40
41 from functools import wraps
41 from functools import wraps
42
42
43 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
44 # Globals
44 # Globals
45 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
46
46
47 # Public API
47 # Public API
48 __all__ = ['Completer','IPCompleter']
48 __all__ = ['Completer','IPCompleter']
49
49
50 if sys.platform == 'win32':
50 if sys.platform == 'win32':
51 PROTECTABLES = ' '
51 PROTECTABLES = ' '
52 else:
52 else:
53 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
53 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
54
54
55
55
56 #-----------------------------------------------------------------------------
56 #-----------------------------------------------------------------------------
57 # Work around BUG decorators.
57 # Work around BUG decorators.
58 #-----------------------------------------------------------------------------
58 #-----------------------------------------------------------------------------
59
59
60 def _strip_single_trailing_space(complete):
60 def _strip_single_trailing_space(complete):
61 """
61 """
62 This is a workaround for a weird IPython/Prompt_toolkit behavior,
62 This is a workaround for a weird IPython/Prompt_toolkit behavior,
63 that can be removed once we rely on a slightly more recent prompt_toolkit
63 that can be removed once we rely on a slightly more recent prompt_toolkit
64 version (likely > 1.0.3). So this can likely be removed in IPython 6.0
64 version (likely > 1.0.3). So this can likely be removed in IPython 6.0
65
65
66 cf https://github.com/ipython/ipython/issues/9658
66 cf https://github.com/ipython/ipython/issues/9658
67 and https://github.com/jonathanslenders/python-prompt-toolkit/pull/328
67 and https://github.com/jonathanslenders/python-prompt-toolkit/pull/328
68
68
69 The bug is due to the fact that in PTK the completer will reinvoke itself
69 The bug is due to the fact that in PTK the completer will reinvoke itself
70 after trying to completer to the longuest common prefix of all the
70 after trying to completer to the longuest common prefix of all the
71 completions, unless only one completion is available.
71 completions, unless only one completion is available.
72
72
73 This logic is faulty if the completion ends with space, which can happen in
73 This logic is faulty if the completion ends with space, which can happen in
74 case like::
74 case like::
75
75
76 from foo import im<ta>
76 from foo import im<ta>
77
77
78 which only matching completion is `import `. Note the leading space at the
78 which only matching completion is `import `. Note the leading space at the
79 end. So leaving a space at the end is a reasonable request, but for now
79 end. So leaving a space at the end is a reasonable request, but for now
80 we'll strip it.
80 we'll strip it.
81 """
81 """
82
82
83 @wraps(complete)
83 @wraps(complete)
84 def comp(*args, **kwargs):
84 def comp(*args, **kwargs):
85 text, matches = complete(*args, **kwargs)
85 text, matches = complete(*args, **kwargs)
86 if len(matches) == 1:
86 if len(matches) == 1:
87 return text, [matches[0].rstrip()]
87 return text, [matches[0].rstrip()]
88 return text, matches
88 return text, matches
89
89
90 return comp
90 return comp
91
91
92
92
93
93
94 #-----------------------------------------------------------------------------
94 #-----------------------------------------------------------------------------
95 # Main functions and classes
95 # Main functions and classes
96 #-----------------------------------------------------------------------------
96 #-----------------------------------------------------------------------------
97
97
98 def has_open_quotes(s):
98 def has_open_quotes(s):
99 """Return whether a string has open quotes.
99 """Return whether a string has open quotes.
100
100
101 This simply counts whether the number of quote characters of either type in
101 This simply counts whether the number of quote characters of either type in
102 the string is odd.
102 the string is odd.
103
103
104 Returns
104 Returns
105 -------
105 -------
106 If there is an open quote, the quote character is returned. Else, return
106 If there is an open quote, the quote character is returned. Else, return
107 False.
107 False.
108 """
108 """
109 # We check " first, then ', so complex cases with nested quotes will get
109 # We check " first, then ', so complex cases with nested quotes will get
110 # the " to take precedence.
110 # the " to take precedence.
111 if s.count('"') % 2:
111 if s.count('"') % 2:
112 return '"'
112 return '"'
113 elif s.count("'") % 2:
113 elif s.count("'") % 2:
114 return "'"
114 return "'"
115 else:
115 else:
116 return False
116 return False
117
117
118
118
119 def protect_filename(s):
119 def protect_filename(s):
120 """Escape a string to protect certain characters."""
120 """Escape a string to protect certain characters."""
121 if set(s) & set(PROTECTABLES):
121 if set(s) & set(PROTECTABLES):
122 if sys.platform == "win32":
122 if sys.platform == "win32":
123 return '"' + s + '"'
123 return '"' + s + '"'
124 else:
124 else:
125 return "".join(("\\" + c if c in PROTECTABLES else c) for c in s)
125 return "".join(("\\" + c if c in PROTECTABLES else c) for c in s)
126 else:
126 else:
127 return s
127 return s
128
128
129
129
130 def expand_user(path):
130 def expand_user(path):
131 """Expand '~'-style usernames in strings.
131 """Expand '~'-style usernames in strings.
132
132
133 This is similar to :func:`os.path.expanduser`, but it computes and returns
133 This is similar to :func:`os.path.expanduser`, but it computes and returns
134 extra information that will be useful if the input was being used in
134 extra information that will be useful if the input was being used in
135 computing completions, and you wish to return the completions with the
135 computing completions, and you wish to return the completions with the
136 original '~' instead of its expanded value.
136 original '~' instead of its expanded value.
137
137
138 Parameters
138 Parameters
139 ----------
139 ----------
140 path : str
140 path : str
141 String to be expanded. If no ~ is present, the output is the same as the
141 String to be expanded. If no ~ is present, the output is the same as the
142 input.
142 input.
143
143
144 Returns
144 Returns
145 -------
145 -------
146 newpath : str
146 newpath : str
147 Result of ~ expansion in the input path.
147 Result of ~ expansion in the input path.
148 tilde_expand : bool
148 tilde_expand : bool
149 Whether any expansion was performed or not.
149 Whether any expansion was performed or not.
150 tilde_val : str
150 tilde_val : str
151 The value that ~ was replaced with.
151 The value that ~ was replaced with.
152 """
152 """
153 # Default values
153 # Default values
154 tilde_expand = False
154 tilde_expand = False
155 tilde_val = ''
155 tilde_val = ''
156 newpath = path
156 newpath = path
157
157
158 if path.startswith('~'):
158 if path.startswith('~'):
159 tilde_expand = True
159 tilde_expand = True
160 rest = len(path)-1
160 rest = len(path)-1
161 newpath = os.path.expanduser(path)
161 newpath = os.path.expanduser(path)
162 if rest:
162 if rest:
163 tilde_val = newpath[:-rest]
163 tilde_val = newpath[:-rest]
164 else:
164 else:
165 tilde_val = newpath
165 tilde_val = newpath
166
166
167 return newpath, tilde_expand, tilde_val
167 return newpath, tilde_expand, tilde_val
168
168
169
169
170 def compress_user(path, tilde_expand, tilde_val):
170 def compress_user(path, tilde_expand, tilde_val):
171 """Does the opposite of expand_user, with its outputs.
171 """Does the opposite of expand_user, with its outputs.
172 """
172 """
173 if tilde_expand:
173 if tilde_expand:
174 return path.replace(tilde_val, '~')
174 return path.replace(tilde_val, '~')
175 else:
175 else:
176 return path
176 return path
177
177
178
178
179 def completions_sorting_key(word):
179 def completions_sorting_key(word):
180 """key for sorting completions
180 """key for sorting completions
181
181
182 This does several things:
182 This does several things:
183
183
184 - Lowercase all completions, so they are sorted alphabetically with
184 - Lowercase all completions, so they are sorted alphabetically with
185 upper and lower case words mingled
185 upper and lower case words mingled
186 - Demote any completions starting with underscores to the end
186 - Demote any completions starting with underscores to the end
187 - Insert any %magic and %%cellmagic completions in the alphabetical order
187 - Insert any %magic and %%cellmagic completions in the alphabetical order
188 by their name
188 by their name
189 """
189 """
190 # Case insensitive sort
190 # Case insensitive sort
191 word = word.lower()
191 word = word.lower()
192
192
193 prio1, prio2 = 0, 0
193 prio1, prio2 = 0, 0
194
194
195 if word.startswith('__'):
195 if word.startswith('__'):
196 prio1 = 2
196 prio1 = 2
197 elif word.startswith('_'):
197 elif word.startswith('_'):
198 prio1 = 1
198 prio1 = 1
199
199
200 if word.endswith('='):
200 if word.endswith('='):
201 prio1 = -1
201 prio1 = -1
202
202
203 if word.startswith('%%'):
203 if word.startswith('%%'):
204 # If there's another % in there, this is something else, so leave it alone
204 # If there's another % in there, this is something else, so leave it alone
205 if not "%" in word[2:]:
205 if not "%" in word[2:]:
206 word = word[2:]
206 word = word[2:]
207 prio2 = 2
207 prio2 = 2
208 elif word.startswith('%'):
208 elif word.startswith('%'):
209 if not "%" in word[1:]:
209 if not "%" in word[1:]:
210 word = word[1:]
210 word = word[1:]
211 prio2 = 1
211 prio2 = 1
212
212
213 return prio1, word, prio2
213 return prio1, word, prio2
214
214
215
215
216 @undoc
216 @undoc
217 class Bunch(object): pass
217 class Bunch(object): pass
218
218
219
219
220 if sys.platform == 'win32':
220 if sys.platform == 'win32':
221 DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?'
221 DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?'
222 else:
222 else:
223 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
223 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
224
224
225 GREEDY_DELIMS = ' =\r\n'
225 GREEDY_DELIMS = ' =\r\n'
226
226
227
227
228 class CompletionSplitter(object):
228 class CompletionSplitter(object):
229 """An object to split an input line in a manner similar to readline.
229 """An object to split an input line in a manner similar to readline.
230
230
231 By having our own implementation, we can expose readline-like completion in
231 By having our own implementation, we can expose readline-like completion in
232 a uniform manner to all frontends. This object only needs to be given the
232 a uniform manner to all frontends. This object only needs to be given the
233 line of text to be split and the cursor position on said line, and it
233 line of text to be split and the cursor position on said line, and it
234 returns the 'word' to be completed on at the cursor after splitting the
234 returns the 'word' to be completed on at the cursor after splitting the
235 entire line.
235 entire line.
236
236
237 What characters are used as splitting delimiters can be controlled by
237 What characters are used as splitting delimiters can be controlled by
238 setting the `delims` attribute (this is a property that internally
238 setting the `delims` attribute (this is a property that internally
239 automatically builds the necessary regular expression)"""
239 automatically builds the necessary regular expression)"""
240
240
241 # Private interface
241 # Private interface
242
242
243 # A string of delimiter characters. The default value makes sense for
243 # A string of delimiter characters. The default value makes sense for
244 # IPython's most typical usage patterns.
244 # IPython's most typical usage patterns.
245 _delims = DELIMS
245 _delims = DELIMS
246
246
247 # The expression (a normal string) to be compiled into a regular expression
247 # The expression (a normal string) to be compiled into a regular expression
248 # for actual splitting. We store it as an attribute mostly for ease of
248 # for actual splitting. We store it as an attribute mostly for ease of
249 # debugging, since this type of code can be so tricky to debug.
249 # debugging, since this type of code can be so tricky to debug.
250 _delim_expr = None
250 _delim_expr = None
251
251
252 # The regular expression that does the actual splitting
252 # The regular expression that does the actual splitting
253 _delim_re = None
253 _delim_re = None
254
254
255 def __init__(self, delims=None):
255 def __init__(self, delims=None):
256 delims = CompletionSplitter._delims if delims is None else delims
256 delims = CompletionSplitter._delims if delims is None else delims
257 self.delims = delims
257 self.delims = delims
258
258
259 @property
259 @property
260 def delims(self):
260 def delims(self):
261 """Return the string of delimiter characters."""
261 """Return the string of delimiter characters."""
262 return self._delims
262 return self._delims
263
263
264 @delims.setter
264 @delims.setter
265 def delims(self, delims):
265 def delims(self, delims):
266 """Set the delimiters for line splitting."""
266 """Set the delimiters for line splitting."""
267 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
267 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
268 self._delim_re = re.compile(expr)
268 self._delim_re = re.compile(expr)
269 self._delims = delims
269 self._delims = delims
270 self._delim_expr = expr
270 self._delim_expr = expr
271
271
272 def split_line(self, line, cursor_pos=None):
272 def split_line(self, line, cursor_pos=None):
273 """Split a line of text with a cursor at the given position.
273 """Split a line of text with a cursor at the given position.
274 """
274 """
275 l = line if cursor_pos is None else line[:cursor_pos]
275 l = line if cursor_pos is None else line[:cursor_pos]
276 return self._delim_re.split(l)[-1]
276 return self._delim_re.split(l)[-1]
277
277
278
278
279 class Completer(Configurable):
279 class Completer(Configurable):
280
280
281 greedy = Bool(False,
281 greedy = Bool(False,
282 help="""Activate greedy completion
282 help="""Activate greedy completion
283 PENDING DEPRECTION. this is now mostly taken care of with Jedi.
283 PENDING DEPRECTION. this is now mostly taken care of with Jedi.
284
284
285 This will enable completion on elements of lists, results of function calls, etc.,
285 This will enable completion on elements of lists, results of function calls, etc.,
286 but can be unsafe because the code is actually evaluated on TAB.
286 but can be unsafe because the code is actually evaluated on TAB.
287 """
287 """
288 ).tag(config=True)
288 ).tag(config=True)
289
289
290
290
291 def __init__(self, namespace=None, global_namespace=None, **kwargs):
291 def __init__(self, namespace=None, global_namespace=None, **kwargs):
292 """Create a new completer for the command line.
292 """Create a new completer for the command line.
293
293
294 Completer(namespace=ns, global_namespace=ns2) -> completer instance.
294 Completer(namespace=ns, global_namespace=ns2) -> completer instance.
295
295
296 If unspecified, the default namespace where completions are performed
296 If unspecified, the default namespace where completions are performed
297 is __main__ (technically, __main__.__dict__). Namespaces should be
297 is __main__ (technically, __main__.__dict__). Namespaces should be
298 given as dictionaries.
298 given as dictionaries.
299
299
300 An optional second namespace can be given. This allows the completer
300 An optional second namespace can be given. This allows the completer
301 to handle cases where both the local and global scopes need to be
301 to handle cases where both the local and global scopes need to be
302 distinguished.
302 distinguished.
303
303
304 Completer instances should be used as the completion mechanism of
304 Completer instances should be used as the completion mechanism of
305 readline via the set_completer() call:
305 readline via the set_completer() call:
306
306
307 readline.set_completer(Completer(my_namespace).complete)
307 readline.set_completer(Completer(my_namespace).complete)
308 """
308 """
309
309
310 # Don't bind to namespace quite yet, but flag whether the user wants a
310 # Don't bind to namespace quite yet, but flag whether the user wants a
311 # specific namespace or to use __main__.__dict__. This will allow us
311 # specific namespace or to use __main__.__dict__. This will allow us
312 # to bind to __main__.__dict__ at completion time, not now.
312 # to bind to __main__.__dict__ at completion time, not now.
313 if namespace is None:
313 if namespace is None:
314 self.use_main_ns = 1
314 self.use_main_ns = 1
315 else:
315 else:
316 self.use_main_ns = 0
316 self.use_main_ns = 0
317 self.namespace = namespace
317 self.namespace = namespace
318
318
319 # The global namespace, if given, can be bound directly
319 # The global namespace, if given, can be bound directly
320 if global_namespace is None:
320 if global_namespace is None:
321 self.global_namespace = {}
321 self.global_namespace = {}
322 else:
322 else:
323 self.global_namespace = global_namespace
323 self.global_namespace = global_namespace
324
324
325 super(Completer, self).__init__(**kwargs)
325 super(Completer, self).__init__(**kwargs)
326
326
327 def complete(self, text, state):
327 def complete(self, text, state):
328 """Return the next possible completion for 'text'.
328 """Return the next possible completion for 'text'.
329
329
330 This is called successively with state == 0, 1, 2, ... until it
330 This is called successively with state == 0, 1, 2, ... until it
331 returns None. The completion should begin with 'text'.
331 returns None. The completion should begin with 'text'.
332
332
333 """
333 """
334 if self.use_main_ns:
334 if self.use_main_ns:
335 self.namespace = __main__.__dict__
335 self.namespace = __main__.__dict__
336
336
337 if state == 0:
337 if state == 0:
338 if "." in text:
338 if "." in text:
339 self.matches = self.attr_matches(text)
339 self.matches = self.attr_matches(text)
340 else:
340 else:
341 self.matches = self.global_matches(text)
341 self.matches = self.global_matches(text)
342 try:
342 try:
343 return self.matches[state]
343 return self.matches[state]
344 except IndexError:
344 except IndexError:
345 return None
345 return None
346
346
347 def global_matches(self, text):
347 def global_matches(self, text):
348 """Compute matches when text is a simple name.
348 """Compute matches when text is a simple name.
349
349
350 Return a list of all keywords, built-in functions and names currently
350 Return a list of all keywords, built-in functions and names currently
351 defined in self.namespace or self.global_namespace that match.
351 defined in self.namespace or self.global_namespace that match.
352
352
353 """
353 """
354 matches = []
354 matches = []
355 match_append = matches.append
355 match_append = matches.append
356 n = len(text)
356 n = len(text)
357 for lst in [keyword.kwlist,
357 for lst in [keyword.kwlist,
358 builtin_mod.__dict__.keys(),
358 builtin_mod.__dict__.keys(),
359 self.namespace.keys(),
359 self.namespace.keys(),
360 self.global_namespace.keys()]:
360 self.global_namespace.keys()]:
361 for word in lst:
361 for word in lst:
362 if word[:n] == text and word != "__builtins__":
362 if word[:n] == text and word != "__builtins__":
363 match_append(word)
363 match_append(word)
364 return [cast_unicode_py2(m) for m in matches]
364 return [cast_unicode_py2(m) for m in matches]
365
365
366 def attr_matches(self, text):
366 def attr_matches(self, text):
367 """Compute matches when text contains a dot.
367 """Compute matches when text contains a dot.
368
368
369 Assuming the text is of the form NAME.NAME....[NAME], and is
369 Assuming the text is of the form NAME.NAME....[NAME], and is
370 evaluatable in self.namespace or self.global_namespace, it will be
370 evaluatable in self.namespace or self.global_namespace, it will be
371 evaluated and its attributes (as revealed by dir()) are used as
371 evaluated and its attributes (as revealed by dir()) are used as
372 possible completions. (For class instances, class members are are
372 possible completions. (For class instances, class members are are
373 also considered.)
373 also considered.)
374
374
375 WARNING: this can still invoke arbitrary C code, if an object
375 WARNING: this can still invoke arbitrary C code, if an object
376 with a __getattr__ hook is evaluated.
376 with a __getattr__ hook is evaluated.
377
377
378 """
378 """
379
379
380 # Another option, seems to work great. Catches things like ''.<tab>
380 # Another option, seems to work great. Catches things like ''.<tab>
381 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
381 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
382
382
383 if m:
383 if m:
384 expr, attr = m.group(1, 3)
384 expr, attr = m.group(1, 3)
385 elif self.greedy:
385 elif self.greedy:
386 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
386 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
387 if not m2:
387 if not m2:
388 return []
388 return []
389 expr, attr = m2.group(1,2)
389 expr, attr = m2.group(1,2)
390 else:
390 else:
391 return []
391 return []
392
392
393 try:
393 try:
394 obj = eval(expr, self.namespace)
394 obj = eval(expr, self.namespace)
395 except:
395 except:
396 try:
396 try:
397 obj = eval(expr, self.global_namespace)
397 obj = eval(expr, self.global_namespace)
398 except:
398 except:
399 return []
399 return []
400
400
401 if self.limit_to__all__ and hasattr(obj, '__all__'):
401 if self.limit_to__all__ and hasattr(obj, '__all__'):
402 words = get__all__entries(obj)
402 words = get__all__entries(obj)
403 else:
403 else:
404 words = dir2(obj)
404 words = dir2(obj)
405
405
406 try:
406 try:
407 words = generics.complete_object(obj, words)
407 words = generics.complete_object(obj, words)
408 except TryNext:
408 except TryNext:
409 pass
409 pass
410 except Exception:
410 except Exception:
411 # Silence errors from completion function
411 # Silence errors from completion function
412 #raise # dbg
412 #raise # dbg
413 pass
413 pass
414 # Build match list to return
414 # Build match list to return
415 n = len(attr)
415 n = len(attr)
416 return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
416 return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
417
417
418
418
419 def get__all__entries(obj):
419 def get__all__entries(obj):
420 """returns the strings in the __all__ attribute"""
420 """returns the strings in the __all__ attribute"""
421 try:
421 try:
422 words = getattr(obj, '__all__')
422 words = getattr(obj, '__all__')
423 except:
423 except:
424 return []
424 return []
425
425
426 return [cast_unicode_py2(w) for w in words if isinstance(w, string_types)]
426 return [cast_unicode_py2(w) for w in words if isinstance(w, str)]
427
427
428
428
429 def match_dict_keys(keys, prefix, delims):
429 def match_dict_keys(keys, prefix, delims):
430 """Used by dict_key_matches, matching the prefix to a list of keys"""
430 """Used by dict_key_matches, matching the prefix to a list of keys"""
431 if not prefix:
431 if not prefix:
432 return None, 0, [repr(k) for k in keys
432 return None, 0, [repr(k) for k in keys
433 if isinstance(k, (string_types, bytes))]
433 if isinstance(k, (str, bytes))]
434 quote_match = re.search('["\']', prefix)
434 quote_match = re.search('["\']', prefix)
435 quote = quote_match.group()
435 quote = quote_match.group()
436 try:
436 try:
437 prefix_str = eval(prefix + quote, {})
437 prefix_str = eval(prefix + quote, {})
438 except Exception:
438 except Exception:
439 return None, 0, []
439 return None, 0, []
440
440
441 pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
441 pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
442 token_match = re.search(pattern, prefix, re.UNICODE)
442 token_match = re.search(pattern, prefix, re.UNICODE)
443 token_start = token_match.start()
443 token_start = token_match.start()
444 token_prefix = token_match.group()
444 token_prefix = token_match.group()
445
445
446 # TODO: support bytes in Py3k
446 # TODO: support bytes in Py3k
447 matched = []
447 matched = []
448 for key in keys:
448 for key in keys:
449 try:
449 try:
450 if not key.startswith(prefix_str):
450 if not key.startswith(prefix_str):
451 continue
451 continue
452 except (AttributeError, TypeError, UnicodeError):
452 except (AttributeError, TypeError, UnicodeError):
453 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
453 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
454 continue
454 continue
455
455
456 # reformat remainder of key to begin with prefix
456 # reformat remainder of key to begin with prefix
457 rem = key[len(prefix_str):]
457 rem = key[len(prefix_str):]
458 # force repr wrapped in '
458 # force repr wrapped in '
459 rem_repr = repr(rem + '"')
459 rem_repr = repr(rem + '"')
460 if rem_repr.startswith('u') and prefix[0] not in 'uU':
460 if rem_repr.startswith('u') and prefix[0] not in 'uU':
461 # Found key is unicode, but prefix is Py2 string.
461 # Found key is unicode, but prefix is Py2 string.
462 # Therefore attempt to interpret key as string.
462 # Therefore attempt to interpret key as string.
463 try:
463 try:
464 rem_repr = repr(rem.encode('ascii') + '"')
464 rem_repr = repr(rem.encode('ascii') + '"')
465 except UnicodeEncodeError:
465 except UnicodeEncodeError:
466 continue
466 continue
467
467
468 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
468 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
469 if quote == '"':
469 if quote == '"':
470 # The entered prefix is quoted with ",
470 # The entered prefix is quoted with ",
471 # but the match is quoted with '.
471 # but the match is quoted with '.
472 # A contained " hence needs escaping for comparison:
472 # A contained " hence needs escaping for comparison:
473 rem_repr = rem_repr.replace('"', '\\"')
473 rem_repr = rem_repr.replace('"', '\\"')
474
474
475 # then reinsert prefix from start of token
475 # then reinsert prefix from start of token
476 matched.append('%s%s' % (token_prefix, rem_repr))
476 matched.append('%s%s' % (token_prefix, rem_repr))
477 return quote, token_start, matched
477 return quote, token_start, matched
478
478
479
479
480 def _safe_isinstance(obj, module, class_name):
480 def _safe_isinstance(obj, module, class_name):
481 """Checks if obj is an instance of module.class_name if loaded
481 """Checks if obj is an instance of module.class_name if loaded
482 """
482 """
483 return (module in sys.modules and
483 return (module in sys.modules and
484 isinstance(obj, getattr(import_module(module), class_name)))
484 isinstance(obj, getattr(import_module(module), class_name)))
485
485
486
486
487 def back_unicode_name_matches(text):
487 def back_unicode_name_matches(text):
488 u"""Match unicode characters back to unicode name
488 u"""Match unicode characters back to unicode name
489
489
490 This does ☃ -> \\snowman
490 This does ☃ -> \\snowman
491
491
492 Note that snowman is not a valid python3 combining character but will be expanded.
492 Note that snowman is not a valid python3 combining character but will be expanded.
493 Though it will not recombine back to the snowman character by the completion machinery.
493 Though it will not recombine back to the snowman character by the completion machinery.
494
494
495 This will not either back-complete standard sequences like \\n, \\b ...
495 This will not either back-complete standard sequences like \\n, \\b ...
496
496
497 Used on Python 3 only.
497 Used on Python 3 only.
498 """
498 """
499 if len(text)<2:
499 if len(text)<2:
500 return u'', ()
500 return u'', ()
501 maybe_slash = text[-2]
501 maybe_slash = text[-2]
502 if maybe_slash != '\\':
502 if maybe_slash != '\\':
503 return u'', ()
503 return u'', ()
504
504
505 char = text[-1]
505 char = text[-1]
506 # no expand on quote for completion in strings.
506 # no expand on quote for completion in strings.
507 # nor backcomplete standard ascii keys
507 # nor backcomplete standard ascii keys
508 if char in string.ascii_letters or char in ['"',"'"]:
508 if char in string.ascii_letters or char in ['"',"'"]:
509 return u'', ()
509 return u'', ()
510 try :
510 try :
511 unic = unicodedata.name(char)
511 unic = unicodedata.name(char)
512 return '\\'+char,['\\'+unic]
512 return '\\'+char,['\\'+unic]
513 except KeyError:
513 except KeyError:
514 pass
514 pass
515 return u'', ()
515 return u'', ()
516
516
517 def back_latex_name_matches(text):
517 def back_latex_name_matches(text):
518 u"""Match latex characters back to unicode name
518 u"""Match latex characters back to unicode name
519
519
520 This does ->\\sqrt
520 This does ->\\sqrt
521
521
522 Used on Python 3 only.
522 Used on Python 3 only.
523 """
523 """
524 if len(text)<2:
524 if len(text)<2:
525 return u'', ()
525 return u'', ()
526 maybe_slash = text[-2]
526 maybe_slash = text[-2]
527 if maybe_slash != '\\':
527 if maybe_slash != '\\':
528 return u'', ()
528 return u'', ()
529
529
530
530
531 char = text[-1]
531 char = text[-1]
532 # no expand on quote for completion in strings.
532 # no expand on quote for completion in strings.
533 # nor backcomplete standard ascii keys
533 # nor backcomplete standard ascii keys
534 if char in string.ascii_letters or char in ['"',"'"]:
534 if char in string.ascii_letters or char in ['"',"'"]:
535 return u'', ()
535 return u'', ()
536 try :
536 try :
537 latex = reverse_latex_symbol[char]
537 latex = reverse_latex_symbol[char]
538 # '\\' replace the \ as well
538 # '\\' replace the \ as well
539 return '\\'+char,[latex]
539 return '\\'+char,[latex]
540 except KeyError:
540 except KeyError:
541 pass
541 pass
542 return u'', ()
542 return u'', ()
543
543
544
544
545 class IPCompleter(Completer):
545 class IPCompleter(Completer):
546 """Extension of the completer class with IPython-specific features"""
546 """Extension of the completer class with IPython-specific features"""
547
547
548 @observe('greedy')
548 @observe('greedy')
549 def _greedy_changed(self, change):
549 def _greedy_changed(self, change):
550 """update the splitter and readline delims when greedy is changed"""
550 """update the splitter and readline delims when greedy is changed"""
551 if change['new']:
551 if change['new']:
552 self.splitter.delims = GREEDY_DELIMS
552 self.splitter.delims = GREEDY_DELIMS
553 else:
553 else:
554 self.splitter.delims = DELIMS
554 self.splitter.delims = DELIMS
555
555
556 merge_completions = Bool(True,
556 merge_completions = Bool(True,
557 help="""Whether to merge completion results into a single list
557 help="""Whether to merge completion results into a single list
558
558
559 If False, only the completion results from the first non-empty
559 If False, only the completion results from the first non-empty
560 completer will be returned.
560 completer will be returned.
561 """
561 """
562 ).tag(config=True)
562 ).tag(config=True)
563 omit__names = Enum((0,1,2), default_value=2,
563 omit__names = Enum((0,1,2), default_value=2,
564 help="""Instruct the completer to omit private method names
564 help="""Instruct the completer to omit private method names
565
565
566 Specifically, when completing on ``object.<tab>``.
566 Specifically, when completing on ``object.<tab>``.
567
567
568 When 2 [default]: all names that start with '_' will be excluded.
568 When 2 [default]: all names that start with '_' will be excluded.
569
569
570 When 1: all 'magic' names (``__foo__``) will be excluded.
570 When 1: all 'magic' names (``__foo__``) will be excluded.
571
571
572 When 0: nothing will be excluded.
572 When 0: nothing will be excluded.
573 """
573 """
574 ).tag(config=True)
574 ).tag(config=True)
575 limit_to__all__ = Bool(False,
575 limit_to__all__ = Bool(False,
576 help="""
576 help="""
577 DEPRECATED as of version 5.0.
577 DEPRECATED as of version 5.0.
578
578
579 Instruct the completer to use __all__ for the completion
579 Instruct the completer to use __all__ for the completion
580
580
581 Specifically, when completing on ``object.<tab>``.
581 Specifically, when completing on ``object.<tab>``.
582
582
583 When True: only those names in obj.__all__ will be included.
583 When True: only those names in obj.__all__ will be included.
584
584
585 When False [default]: the __all__ attribute is ignored
585 When False [default]: the __all__ attribute is ignored
586 """,
586 """,
587 ).tag(config=True)
587 ).tag(config=True)
588
588
589 def __init__(self, shell=None, namespace=None, global_namespace=None,
589 def __init__(self, shell=None, namespace=None, global_namespace=None,
590 use_readline=False, config=None, **kwargs):
590 use_readline=False, config=None, **kwargs):
591 """IPCompleter() -> completer
591 """IPCompleter() -> completer
592
592
593 Return a completer object suitable for use by the readline library
593 Return a completer object suitable for use by the readline library
594 via readline.set_completer().
594 via readline.set_completer().
595
595
596 Inputs:
596 Inputs:
597
597
598 - shell: a pointer to the ipython shell itself. This is needed
598 - shell: a pointer to the ipython shell itself. This is needed
599 because this completer knows about magic functions, and those can
599 because this completer knows about magic functions, and those can
600 only be accessed via the ipython instance.
600 only be accessed via the ipython instance.
601
601
602 - namespace: an optional dict where completions are performed.
602 - namespace: an optional dict where completions are performed.
603
603
604 - global_namespace: secondary optional dict for completions, to
604 - global_namespace: secondary optional dict for completions, to
605 handle cases (such as IPython embedded inside functions) where
605 handle cases (such as IPython embedded inside functions) where
606 both Python scopes are visible.
606 both Python scopes are visible.
607
607
608 use_readline : bool, optional
608 use_readline : bool, optional
609 DEPRECATED, ignored.
609 DEPRECATED, ignored.
610 """
610 """
611
611
612 self.magic_escape = ESC_MAGIC
612 self.magic_escape = ESC_MAGIC
613 self.splitter = CompletionSplitter()
613 self.splitter = CompletionSplitter()
614
614
615 if use_readline:
615 if use_readline:
616 warnings.warn('The use_readline parameter is deprecated and ignored since IPython 6.0.',
616 warnings.warn('The use_readline parameter is deprecated and ignored since IPython 6.0.',
617 DeprecationWarning, stacklevel=2)
617 DeprecationWarning, stacklevel=2)
618
618
619 # _greedy_changed() depends on splitter and readline being defined:
619 # _greedy_changed() depends on splitter and readline being defined:
620 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
620 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
621 config=config, **kwargs)
621 config=config, **kwargs)
622
622
623 # List where completion matches will be stored
623 # List where completion matches will be stored
624 self.matches = []
624 self.matches = []
625 self.shell = shell
625 self.shell = shell
626 # Regexp to split filenames with spaces in them
626 # Regexp to split filenames with spaces in them
627 self.space_name_re = re.compile(r'([^\\] )')
627 self.space_name_re = re.compile(r'([^\\] )')
628 # Hold a local ref. to glob.glob for speed
628 # Hold a local ref. to glob.glob for speed
629 self.glob = glob.glob
629 self.glob = glob.glob
630
630
631 # Determine if we are running on 'dumb' terminals, like (X)Emacs
631 # Determine if we are running on 'dumb' terminals, like (X)Emacs
632 # buffers, to avoid completion problems.
632 # buffers, to avoid completion problems.
633 term = os.environ.get('TERM','xterm')
633 term = os.environ.get('TERM','xterm')
634 self.dumb_terminal = term in ['dumb','emacs']
634 self.dumb_terminal = term in ['dumb','emacs']
635
635
636 # Special handling of backslashes needed in win32 platforms
636 # Special handling of backslashes needed in win32 platforms
637 if sys.platform == "win32":
637 if sys.platform == "win32":
638 self.clean_glob = self._clean_glob_win32
638 self.clean_glob = self._clean_glob_win32
639 else:
639 else:
640 self.clean_glob = self._clean_glob
640 self.clean_glob = self._clean_glob
641
641
642 #regexp to parse docstring for function signature
642 #regexp to parse docstring for function signature
643 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
643 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
644 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
644 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
645 #use this if positional argument name is also needed
645 #use this if positional argument name is also needed
646 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
646 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
647
647
648 # All active matcher routines for completion
648 # All active matcher routines for completion
649 self.matchers = [
649 self.matchers = [
650 self.python_matches,
650 self.python_matches,
651 self.file_matches,
651 self.file_matches,
652 self.magic_matches,
652 self.magic_matches,
653 self.python_func_kw_matches,
653 self.python_func_kw_matches,
654 self.dict_key_matches,
654 self.dict_key_matches,
655 ]
655 ]
656
656
657 # This is set externally by InteractiveShell
657 # This is set externally by InteractiveShell
658 self.custom_completers = None
658 self.custom_completers = None
659
659
660 def all_completions(self, text):
660 def all_completions(self, text):
661 """
661 """
662 Wrapper around the complete method for the benefit of emacs.
662 Wrapper around the complete method for the benefit of emacs.
663 """
663 """
664 return self.complete(text)[1]
664 return self.complete(text)[1]
665
665
666 def _clean_glob(self, text):
666 def _clean_glob(self, text):
667 return self.glob("%s*" % text)
667 return self.glob("%s*" % text)
668
668
669 def _clean_glob_win32(self,text):
669 def _clean_glob_win32(self,text):
670 return [f.replace("\\","/")
670 return [f.replace("\\","/")
671 for f in self.glob("%s*" % text)]
671 for f in self.glob("%s*" % text)]
672
672
673 def file_matches(self, text):
673 def file_matches(self, text):
674 """Match filenames, expanding ~USER type strings.
674 """Match filenames, expanding ~USER type strings.
675
675
676 Most of the seemingly convoluted logic in this completer is an
676 Most of the seemingly convoluted logic in this completer is an
677 attempt to handle filenames with spaces in them. And yet it's not
677 attempt to handle filenames with spaces in them. And yet it's not
678 quite perfect, because Python's readline doesn't expose all of the
678 quite perfect, because Python's readline doesn't expose all of the
679 GNU readline details needed for this to be done correctly.
679 GNU readline details needed for this to be done correctly.
680
680
681 For a filename with a space in it, the printed completions will be
681 For a filename with a space in it, the printed completions will be
682 only the parts after what's already been typed (instead of the
682 only the parts after what's already been typed (instead of the
683 full completions, as is normally done). I don't think with the
683 full completions, as is normally done). I don't think with the
684 current (as of Python 2.3) Python readline it's possible to do
684 current (as of Python 2.3) Python readline it's possible to do
685 better."""
685 better."""
686
686
687 # chars that require escaping with backslash - i.e. chars
687 # chars that require escaping with backslash - i.e. chars
688 # that readline treats incorrectly as delimiters, but we
688 # that readline treats incorrectly as delimiters, but we
689 # don't want to treat as delimiters in filename matching
689 # don't want to treat as delimiters in filename matching
690 # when escaped with backslash
690 # when escaped with backslash
691 if text.startswith('!'):
691 if text.startswith('!'):
692 text = text[1:]
692 text = text[1:]
693 text_prefix = u'!'
693 text_prefix = u'!'
694 else:
694 else:
695 text_prefix = u''
695 text_prefix = u''
696
696
697 text_until_cursor = self.text_until_cursor
697 text_until_cursor = self.text_until_cursor
698 # track strings with open quotes
698 # track strings with open quotes
699 open_quotes = has_open_quotes(text_until_cursor)
699 open_quotes = has_open_quotes(text_until_cursor)
700
700
701 if '(' in text_until_cursor or '[' in text_until_cursor:
701 if '(' in text_until_cursor or '[' in text_until_cursor:
702 lsplit = text
702 lsplit = text
703 else:
703 else:
704 try:
704 try:
705 # arg_split ~ shlex.split, but with unicode bugs fixed by us
705 # arg_split ~ shlex.split, but with unicode bugs fixed by us
706 lsplit = arg_split(text_until_cursor)[-1]
706 lsplit = arg_split(text_until_cursor)[-1]
707 except ValueError:
707 except ValueError:
708 # typically an unmatched ", or backslash without escaped char.
708 # typically an unmatched ", or backslash without escaped char.
709 if open_quotes:
709 if open_quotes:
710 lsplit = text_until_cursor.split(open_quotes)[-1]
710 lsplit = text_until_cursor.split(open_quotes)[-1]
711 else:
711 else:
712 return []
712 return []
713 except IndexError:
713 except IndexError:
714 # tab pressed on empty line
714 # tab pressed on empty line
715 lsplit = ""
715 lsplit = ""
716
716
717 if not open_quotes and lsplit != protect_filename(lsplit):
717 if not open_quotes and lsplit != protect_filename(lsplit):
718 # if protectables are found, do matching on the whole escaped name
718 # if protectables are found, do matching on the whole escaped name
719 has_protectables = True
719 has_protectables = True
720 text0,text = text,lsplit
720 text0,text = text,lsplit
721 else:
721 else:
722 has_protectables = False
722 has_protectables = False
723 text = os.path.expanduser(text)
723 text = os.path.expanduser(text)
724
724
725 if text == "":
725 if text == "":
726 return [text_prefix + cast_unicode_py2(protect_filename(f)) for f in self.glob("*")]
726 return [text_prefix + cast_unicode_py2(protect_filename(f)) for f in self.glob("*")]
727
727
728 # Compute the matches from the filesystem
728 # Compute the matches from the filesystem
729 if sys.platform == 'win32':
729 if sys.platform == 'win32':
730 m0 = self.clean_glob(text)
730 m0 = self.clean_glob(text)
731 else:
731 else:
732 m0 = self.clean_glob(text.replace('\\', ''))
732 m0 = self.clean_glob(text.replace('\\', ''))
733
733
734 if has_protectables:
734 if has_protectables:
735 # If we had protectables, we need to revert our changes to the
735 # If we had protectables, we need to revert our changes to the
736 # beginning of filename so that we don't double-write the part
736 # beginning of filename so that we don't double-write the part
737 # of the filename we have so far
737 # of the filename we have so far
738 len_lsplit = len(lsplit)
738 len_lsplit = len(lsplit)
739 matches = [text_prefix + text0 +
739 matches = [text_prefix + text0 +
740 protect_filename(f[len_lsplit:]) for f in m0]
740 protect_filename(f[len_lsplit:]) for f in m0]
741 else:
741 else:
742 if open_quotes:
742 if open_quotes:
743 # if we have a string with an open quote, we don't need to
743 # if we have a string with an open quote, we don't need to
744 # protect the names at all (and we _shouldn't_, as it
744 # protect the names at all (and we _shouldn't_, as it
745 # would cause bugs when the filesystem call is made).
745 # would cause bugs when the filesystem call is made).
746 matches = m0
746 matches = m0
747 else:
747 else:
748 matches = [text_prefix +
748 matches = [text_prefix +
749 protect_filename(f) for f in m0]
749 protect_filename(f) for f in m0]
750
750
751 # Mark directories in input list by appending '/' to their names.
751 # Mark directories in input list by appending '/' to their names.
752 return [cast_unicode_py2(x+'/') if os.path.isdir(x) else x for x in matches]
752 return [cast_unicode_py2(x+'/') if os.path.isdir(x) else x for x in matches]
753
753
754 def magic_matches(self, text):
754 def magic_matches(self, text):
755 """Match magics"""
755 """Match magics"""
756 # Get all shell magics now rather than statically, so magics loaded at
756 # Get all shell magics now rather than statically, so magics loaded at
757 # runtime show up too.
757 # runtime show up too.
758 lsm = self.shell.magics_manager.lsmagic()
758 lsm = self.shell.magics_manager.lsmagic()
759 line_magics = lsm['line']
759 line_magics = lsm['line']
760 cell_magics = lsm['cell']
760 cell_magics = lsm['cell']
761 pre = self.magic_escape
761 pre = self.magic_escape
762 pre2 = pre+pre
762 pre2 = pre+pre
763
763
764 # Completion logic:
764 # Completion logic:
765 # - user gives %%: only do cell magics
765 # - user gives %%: only do cell magics
766 # - user gives %: do both line and cell magics
766 # - user gives %: do both line and cell magics
767 # - no prefix: do both
767 # - no prefix: do both
768 # In other words, line magics are skipped if the user gives %% explicitly
768 # In other words, line magics are skipped if the user gives %% explicitly
769 bare_text = text.lstrip(pre)
769 bare_text = text.lstrip(pre)
770 comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
770 comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
771 if not text.startswith(pre2):
771 if not text.startswith(pre2):
772 comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
772 comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
773 return [cast_unicode_py2(c) for c in comp]
773 return [cast_unicode_py2(c) for c in comp]
774
774
775
775
776 def python_matches(self, text):
776 def python_matches(self, text):
777 """Match attributes or global python names"""
777 """Match attributes or global python names"""
778 if "." in text:
778 if "." in text:
779 try:
779 try:
780 matches = self.attr_matches(text)
780 matches = self.attr_matches(text)
781 if text.endswith('.') and self.omit__names:
781 if text.endswith('.') and self.omit__names:
782 if self.omit__names == 1:
782 if self.omit__names == 1:
783 # true if txt is _not_ a __ name, false otherwise:
783 # true if txt is _not_ a __ name, false otherwise:
784 no__name = (lambda txt:
784 no__name = (lambda txt:
785 re.match(r'.*\.__.*?__',txt) is None)
785 re.match(r'.*\.__.*?__',txt) is None)
786 else:
786 else:
787 # true if txt is _not_ a _ name, false otherwise:
787 # true if txt is _not_ a _ name, false otherwise:
788 no__name = (lambda txt:
788 no__name = (lambda txt:
789 re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
789 re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
790 matches = filter(no__name, matches)
790 matches = filter(no__name, matches)
791 except NameError:
791 except NameError:
792 # catches <undefined attributes>.<tab>
792 # catches <undefined attributes>.<tab>
793 matches = []
793 matches = []
794 else:
794 else:
795 matches = self.global_matches(text)
795 matches = self.global_matches(text)
796 return matches
796 return matches
797
797
798 def _default_arguments_from_docstring(self, doc):
798 def _default_arguments_from_docstring(self, doc):
799 """Parse the first line of docstring for call signature.
799 """Parse the first line of docstring for call signature.
800
800
801 Docstring should be of the form 'min(iterable[, key=func])\n'.
801 Docstring should be of the form 'min(iterable[, key=func])\n'.
802 It can also parse cython docstring of the form
802 It can also parse cython docstring of the form
803 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
803 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
804 """
804 """
805 if doc is None:
805 if doc is None:
806 return []
806 return []
807
807
808 #care only the firstline
808 #care only the firstline
809 line = doc.lstrip().splitlines()[0]
809 line = doc.lstrip().splitlines()[0]
810
810
811 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
811 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
812 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
812 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
813 sig = self.docstring_sig_re.search(line)
813 sig = self.docstring_sig_re.search(line)
814 if sig is None:
814 if sig is None:
815 return []
815 return []
816 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
816 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
817 sig = sig.groups()[0].split(',')
817 sig = sig.groups()[0].split(',')
818 ret = []
818 ret = []
819 for s in sig:
819 for s in sig:
820 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
820 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
821 ret += self.docstring_kwd_re.findall(s)
821 ret += self.docstring_kwd_re.findall(s)
822 return ret
822 return ret
823
823
824 def _default_arguments(self, obj):
824 def _default_arguments(self, obj):
825 """Return the list of default arguments of obj if it is callable,
825 """Return the list of default arguments of obj if it is callable,
826 or empty list otherwise."""
826 or empty list otherwise."""
827 call_obj = obj
827 call_obj = obj
828 ret = []
828 ret = []
829 if inspect.isbuiltin(obj):
829 if inspect.isbuiltin(obj):
830 pass
830 pass
831 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
831 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
832 if inspect.isclass(obj):
832 if inspect.isclass(obj):
833 #for cython embededsignature=True the constructor docstring
833 #for cython embededsignature=True the constructor docstring
834 #belongs to the object itself not __init__
834 #belongs to the object itself not __init__
835 ret += self._default_arguments_from_docstring(
835 ret += self._default_arguments_from_docstring(
836 getattr(obj, '__doc__', ''))
836 getattr(obj, '__doc__', ''))
837 # for classes, check for __init__,__new__
837 # for classes, check for __init__,__new__
838 call_obj = (getattr(obj, '__init__', None) or
838 call_obj = (getattr(obj, '__init__', None) or
839 getattr(obj, '__new__', None))
839 getattr(obj, '__new__', None))
840 # for all others, check if they are __call__able
840 # for all others, check if they are __call__able
841 elif hasattr(obj, '__call__'):
841 elif hasattr(obj, '__call__'):
842 call_obj = obj.__call__
842 call_obj = obj.__call__
843 ret += self._default_arguments_from_docstring(
843 ret += self._default_arguments_from_docstring(
844 getattr(call_obj, '__doc__', ''))
844 getattr(call_obj, '__doc__', ''))
845
845
846 _keeps = (inspect.Parameter.KEYWORD_ONLY,
846 _keeps = (inspect.Parameter.KEYWORD_ONLY,
847 inspect.Parameter.POSITIONAL_OR_KEYWORD)
847 inspect.Parameter.POSITIONAL_OR_KEYWORD)
848
848
849 try:
849 try:
850 sig = inspect.signature(call_obj)
850 sig = inspect.signature(call_obj)
851 ret.extend(k for k, v in sig.parameters.items() if
851 ret.extend(k for k, v in sig.parameters.items() if
852 v.kind in _keeps)
852 v.kind in _keeps)
853 except ValueError:
853 except ValueError:
854 pass
854 pass
855
855
856 return list(set(ret))
856 return list(set(ret))
857
857
858 def python_func_kw_matches(self,text):
858 def python_func_kw_matches(self,text):
859 """Match named parameters (kwargs) of the last open function"""
859 """Match named parameters (kwargs) of the last open function"""
860
860
861 if "." in text: # a parameter cannot be dotted
861 if "." in text: # a parameter cannot be dotted
862 return []
862 return []
863 try: regexp = self.__funcParamsRegex
863 try: regexp = self.__funcParamsRegex
864 except AttributeError:
864 except AttributeError:
865 regexp = self.__funcParamsRegex = re.compile(r'''
865 regexp = self.__funcParamsRegex = re.compile(r'''
866 '.*?(?<!\\)' | # single quoted strings or
866 '.*?(?<!\\)' | # single quoted strings or
867 ".*?(?<!\\)" | # double quoted strings or
867 ".*?(?<!\\)" | # double quoted strings or
868 \w+ | # identifier
868 \w+ | # identifier
869 \S # other characters
869 \S # other characters
870 ''', re.VERBOSE | re.DOTALL)
870 ''', re.VERBOSE | re.DOTALL)
871 # 1. find the nearest identifier that comes before an unclosed
871 # 1. find the nearest identifier that comes before an unclosed
872 # parenthesis before the cursor
872 # parenthesis before the cursor
873 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
873 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
874 tokens = regexp.findall(self.text_until_cursor)
874 tokens = regexp.findall(self.text_until_cursor)
875 iterTokens = reversed(tokens); openPar = 0
875 iterTokens = reversed(tokens); openPar = 0
876
876
877 for token in iterTokens:
877 for token in iterTokens:
878 if token == ')':
878 if token == ')':
879 openPar -= 1
879 openPar -= 1
880 elif token == '(':
880 elif token == '(':
881 openPar += 1
881 openPar += 1
882 if openPar > 0:
882 if openPar > 0:
883 # found the last unclosed parenthesis
883 # found the last unclosed parenthesis
884 break
884 break
885 else:
885 else:
886 return []
886 return []
887 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
887 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
888 ids = []
888 ids = []
889 isId = re.compile(r'\w+$').match
889 isId = re.compile(r'\w+$').match
890
890
891 while True:
891 while True:
892 try:
892 try:
893 ids.append(next(iterTokens))
893 ids.append(next(iterTokens))
894 if not isId(ids[-1]):
894 if not isId(ids[-1]):
895 ids.pop(); break
895 ids.pop(); break
896 if not next(iterTokens) == '.':
896 if not next(iterTokens) == '.':
897 break
897 break
898 except StopIteration:
898 except StopIteration:
899 break
899 break
900
900
901 # Find all named arguments already assigned to, as to avoid suggesting
901 # Find all named arguments already assigned to, as to avoid suggesting
902 # them again
902 # them again
903 usedNamedArgs = set()
903 usedNamedArgs = set()
904 par_level = -1
904 par_level = -1
905 for token, next_token in zip(tokens, tokens[1:]):
905 for token, next_token in zip(tokens, tokens[1:]):
906 if token == '(':
906 if token == '(':
907 par_level += 1
907 par_level += 1
908 elif token == ')':
908 elif token == ')':
909 par_level -= 1
909 par_level -= 1
910
910
911 if par_level != 0:
911 if par_level != 0:
912 continue
912 continue
913
913
914 if next_token != '=':
914 if next_token != '=':
915 continue
915 continue
916
916
917 usedNamedArgs.add(token)
917 usedNamedArgs.add(token)
918
918
919 # lookup the candidate callable matches either using global_matches
919 # lookup the candidate callable matches either using global_matches
920 # or attr_matches for dotted names
920 # or attr_matches for dotted names
921 if len(ids) == 1:
921 if len(ids) == 1:
922 callableMatches = self.global_matches(ids[0])
922 callableMatches = self.global_matches(ids[0])
923 else:
923 else:
924 callableMatches = self.attr_matches('.'.join(ids[::-1]))
924 callableMatches = self.attr_matches('.'.join(ids[::-1]))
925 argMatches = []
925 argMatches = []
926 for callableMatch in callableMatches:
926 for callableMatch in callableMatches:
927 try:
927 try:
928 namedArgs = self._default_arguments(eval(callableMatch,
928 namedArgs = self._default_arguments(eval(callableMatch,
929 self.namespace))
929 self.namespace))
930 except:
930 except:
931 continue
931 continue
932
932
933 # Remove used named arguments from the list, no need to show twice
933 # Remove used named arguments from the list, no need to show twice
934 for namedArg in set(namedArgs) - usedNamedArgs:
934 for namedArg in set(namedArgs) - usedNamedArgs:
935 if namedArg.startswith(text):
935 if namedArg.startswith(text):
936 argMatches.append(u"%s=" %namedArg)
936 argMatches.append(u"%s=" %namedArg)
937 return argMatches
937 return argMatches
938
938
939 def dict_key_matches(self, text):
939 def dict_key_matches(self, text):
940 "Match string keys in a dictionary, after e.g. 'foo[' "
940 "Match string keys in a dictionary, after e.g. 'foo[' "
941 def get_keys(obj):
941 def get_keys(obj):
942 # Objects can define their own completions by defining an
942 # Objects can define their own completions by defining an
943 # _ipy_key_completions_() method.
943 # _ipy_key_completions_() method.
944 method = get_real_method(obj, '_ipython_key_completions_')
944 method = get_real_method(obj, '_ipython_key_completions_')
945 if method is not None:
945 if method is not None:
946 return method()
946 return method()
947
947
948 # Special case some common in-memory dict-like types
948 # Special case some common in-memory dict-like types
949 if isinstance(obj, dict) or\
949 if isinstance(obj, dict) or\
950 _safe_isinstance(obj, 'pandas', 'DataFrame'):
950 _safe_isinstance(obj, 'pandas', 'DataFrame'):
951 try:
951 try:
952 return list(obj.keys())
952 return list(obj.keys())
953 except Exception:
953 except Exception:
954 return []
954 return []
955 elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
955 elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
956 _safe_isinstance(obj, 'numpy', 'void'):
956 _safe_isinstance(obj, 'numpy', 'void'):
957 return obj.dtype.names or []
957 return obj.dtype.names or []
958 return []
958 return []
959
959
960 try:
960 try:
961 regexps = self.__dict_key_regexps
961 regexps = self.__dict_key_regexps
962 except AttributeError:
962 except AttributeError:
963 dict_key_re_fmt = r'''(?x)
963 dict_key_re_fmt = r'''(?x)
964 ( # match dict-referring expression wrt greedy setting
964 ( # match dict-referring expression wrt greedy setting
965 %s
965 %s
966 )
966 )
967 \[ # open bracket
967 \[ # open bracket
968 \s* # and optional whitespace
968 \s* # and optional whitespace
969 ([uUbB]? # string prefix (r not handled)
969 ([uUbB]? # string prefix (r not handled)
970 (?: # unclosed string
970 (?: # unclosed string
971 '(?:[^']|(?<!\\)\\')*
971 '(?:[^']|(?<!\\)\\')*
972 |
972 |
973 "(?:[^"]|(?<!\\)\\")*
973 "(?:[^"]|(?<!\\)\\")*
974 )
974 )
975 )?
975 )?
976 $
976 $
977 '''
977 '''
978 regexps = self.__dict_key_regexps = {
978 regexps = self.__dict_key_regexps = {
979 False: re.compile(dict_key_re_fmt % '''
979 False: re.compile(dict_key_re_fmt % '''
980 # identifiers separated by .
980 # identifiers separated by .
981 (?!\d)\w+
981 (?!\d)\w+
982 (?:\.(?!\d)\w+)*
982 (?:\.(?!\d)\w+)*
983 '''),
983 '''),
984 True: re.compile(dict_key_re_fmt % '''
984 True: re.compile(dict_key_re_fmt % '''
985 .+
985 .+
986 ''')
986 ''')
987 }
987 }
988
988
989 match = regexps[self.greedy].search(self.text_until_cursor)
989 match = regexps[self.greedy].search(self.text_until_cursor)
990 if match is None:
990 if match is None:
991 return []
991 return []
992
992
993 expr, prefix = match.groups()
993 expr, prefix = match.groups()
994 try:
994 try:
995 obj = eval(expr, self.namespace)
995 obj = eval(expr, self.namespace)
996 except Exception:
996 except Exception:
997 try:
997 try:
998 obj = eval(expr, self.global_namespace)
998 obj = eval(expr, self.global_namespace)
999 except Exception:
999 except Exception:
1000 return []
1000 return []
1001
1001
1002 keys = get_keys(obj)
1002 keys = get_keys(obj)
1003 if not keys:
1003 if not keys:
1004 return keys
1004 return keys
1005 closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims)
1005 closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims)
1006 if not matches:
1006 if not matches:
1007 return matches
1007 return matches
1008
1008
1009 # get the cursor position of
1009 # get the cursor position of
1010 # - the text being completed
1010 # - the text being completed
1011 # - the start of the key text
1011 # - the start of the key text
1012 # - the start of the completion
1012 # - the start of the completion
1013 text_start = len(self.text_until_cursor) - len(text)
1013 text_start = len(self.text_until_cursor) - len(text)
1014 if prefix:
1014 if prefix:
1015 key_start = match.start(2)
1015 key_start = match.start(2)
1016 completion_start = key_start + token_offset
1016 completion_start = key_start + token_offset
1017 else:
1017 else:
1018 key_start = completion_start = match.end()
1018 key_start = completion_start = match.end()
1019
1019
1020 # grab the leading prefix, to make sure all completions start with `text`
1020 # grab the leading prefix, to make sure all completions start with `text`
1021 if text_start > key_start:
1021 if text_start > key_start:
1022 leading = ''
1022 leading = ''
1023 else:
1023 else:
1024 leading = text[text_start:completion_start]
1024 leading = text[text_start:completion_start]
1025
1025
1026 # the index of the `[` character
1026 # the index of the `[` character
1027 bracket_idx = match.end(1)
1027 bracket_idx = match.end(1)
1028
1028
1029 # append closing quote and bracket as appropriate
1029 # append closing quote and bracket as appropriate
1030 # this is *not* appropriate if the opening quote or bracket is outside
1030 # this is *not* appropriate if the opening quote or bracket is outside
1031 # the text given to this method
1031 # the text given to this method
1032 suf = ''
1032 suf = ''
1033 continuation = self.line_buffer[len(self.text_until_cursor):]
1033 continuation = self.line_buffer[len(self.text_until_cursor):]
1034 if key_start > text_start and closing_quote:
1034 if key_start > text_start and closing_quote:
1035 # quotes were opened inside text, maybe close them
1035 # quotes were opened inside text, maybe close them
1036 if continuation.startswith(closing_quote):
1036 if continuation.startswith(closing_quote):
1037 continuation = continuation[len(closing_quote):]
1037 continuation = continuation[len(closing_quote):]
1038 else:
1038 else:
1039 suf += closing_quote
1039 suf += closing_quote
1040 if bracket_idx > text_start:
1040 if bracket_idx > text_start:
1041 # brackets were opened inside text, maybe close them
1041 # brackets were opened inside text, maybe close them
1042 if not continuation.startswith(']'):
1042 if not continuation.startswith(']'):
1043 suf += ']'
1043 suf += ']'
1044
1044
1045 return [leading + k + suf for k in matches]
1045 return [leading + k + suf for k in matches]
1046
1046
1047 def unicode_name_matches(self, text):
1047 def unicode_name_matches(self, text):
1048 u"""Match Latex-like syntax for unicode characters base
1048 u"""Match Latex-like syntax for unicode characters base
1049 on the name of the character.
1049 on the name of the character.
1050
1050
1051 This does \\GREEK SMALL LETTER ETA -> η
1051 This does \\GREEK SMALL LETTER ETA -> η
1052
1052
1053 Works only on valid python 3 identifier, or on combining characters that
1053 Works only on valid python 3 identifier, or on combining characters that
1054 will combine to form a valid identifier.
1054 will combine to form a valid identifier.
1055
1055
1056 Used on Python 3 only.
1056 Used on Python 3 only.
1057 """
1057 """
1058 slashpos = text.rfind('\\')
1058 slashpos = text.rfind('\\')
1059 if slashpos > -1:
1059 if slashpos > -1:
1060 s = text[slashpos+1:]
1060 s = text[slashpos+1:]
1061 try :
1061 try :
1062 unic = unicodedata.lookup(s)
1062 unic = unicodedata.lookup(s)
1063 # allow combining chars
1063 # allow combining chars
1064 if ('a'+unic).isidentifier():
1064 if ('a'+unic).isidentifier():
1065 return '\\'+s,[unic]
1065 return '\\'+s,[unic]
1066 except KeyError:
1066 except KeyError:
1067 pass
1067 pass
1068 return u'', []
1068 return u'', []
1069
1069
1070
1070
1071
1071
1072
1072
1073 def latex_matches(self, text):
1073 def latex_matches(self, text):
1074 u"""Match Latex syntax for unicode characters.
1074 u"""Match Latex syntax for unicode characters.
1075
1075
1076 This does both \\alp -> \\alpha and \\alpha -> α
1076 This does both \\alp -> \\alpha and \\alpha -> α
1077
1077
1078 Used on Python 3 only.
1078 Used on Python 3 only.
1079 """
1079 """
1080 slashpos = text.rfind('\\')
1080 slashpos = text.rfind('\\')
1081 if slashpos > -1:
1081 if slashpos > -1:
1082 s = text[slashpos:]
1082 s = text[slashpos:]
1083 if s in latex_symbols:
1083 if s in latex_symbols:
1084 # Try to complete a full latex symbol to unicode
1084 # Try to complete a full latex symbol to unicode
1085 # \\alpha -> α
1085 # \\alpha -> α
1086 return s, [latex_symbols[s]]
1086 return s, [latex_symbols[s]]
1087 else:
1087 else:
1088 # If a user has partially typed a latex symbol, give them
1088 # If a user has partially typed a latex symbol, give them
1089 # a full list of options \al -> [\aleph, \alpha]
1089 # a full list of options \al -> [\aleph, \alpha]
1090 matches = [k for k in latex_symbols if k.startswith(s)]
1090 matches = [k for k in latex_symbols if k.startswith(s)]
1091 return s, matches
1091 return s, matches
1092 return u'', []
1092 return u'', []
1093
1093
1094 def dispatch_custom_completer(self, text):
1094 def dispatch_custom_completer(self, text):
1095 if not self.custom_completers:
1095 if not self.custom_completers:
1096 return
1096 return
1097
1097
1098 line = self.line_buffer
1098 line = self.line_buffer
1099 if not line.strip():
1099 if not line.strip():
1100 return None
1100 return None
1101
1101
1102 # Create a little structure to pass all the relevant information about
1102 # Create a little structure to pass all the relevant information about
1103 # the current completion to any custom completer.
1103 # the current completion to any custom completer.
1104 event = Bunch()
1104 event = Bunch()
1105 event.line = line
1105 event.line = line
1106 event.symbol = text
1106 event.symbol = text
1107 cmd = line.split(None,1)[0]
1107 cmd = line.split(None,1)[0]
1108 event.command = cmd
1108 event.command = cmd
1109 event.text_until_cursor = self.text_until_cursor
1109 event.text_until_cursor = self.text_until_cursor
1110
1110
1111 # for foo etc, try also to find completer for %foo
1111 # for foo etc, try also to find completer for %foo
1112 if not cmd.startswith(self.magic_escape):
1112 if not cmd.startswith(self.magic_escape):
1113 try_magic = self.custom_completers.s_matches(
1113 try_magic = self.custom_completers.s_matches(
1114 self.magic_escape + cmd)
1114 self.magic_escape + cmd)
1115 else:
1115 else:
1116 try_magic = []
1116 try_magic = []
1117
1117
1118 for c in itertools.chain(self.custom_completers.s_matches(cmd),
1118 for c in itertools.chain(self.custom_completers.s_matches(cmd),
1119 try_magic,
1119 try_magic,
1120 self.custom_completers.flat_matches(self.text_until_cursor)):
1120 self.custom_completers.flat_matches(self.text_until_cursor)):
1121 try:
1121 try:
1122 res = c(event)
1122 res = c(event)
1123 if res:
1123 if res:
1124 # first, try case sensitive match
1124 # first, try case sensitive match
1125 withcase = [cast_unicode_py2(r) for r in res if r.startswith(text)]
1125 withcase = [cast_unicode_py2(r) for r in res if r.startswith(text)]
1126 if withcase:
1126 if withcase:
1127 return withcase
1127 return withcase
1128 # if none, then case insensitive ones are ok too
1128 # if none, then case insensitive ones are ok too
1129 text_low = text.lower()
1129 text_low = text.lower()
1130 return [cast_unicode_py2(r) for r in res if r.lower().startswith(text_low)]
1130 return [cast_unicode_py2(r) for r in res if r.lower().startswith(text_low)]
1131 except TryNext:
1131 except TryNext:
1132 pass
1132 pass
1133
1133
1134 return None
1134 return None
1135
1135
1136 @_strip_single_trailing_space
1136 @_strip_single_trailing_space
1137 def complete(self, text=None, line_buffer=None, cursor_pos=None):
1137 def complete(self, text=None, line_buffer=None, cursor_pos=None):
1138 """Find completions for the given text and line context.
1138 """Find completions for the given text and line context.
1139
1139
1140 Note that both the text and the line_buffer are optional, but at least
1140 Note that both the text and the line_buffer are optional, but at least
1141 one of them must be given.
1141 one of them must be given.
1142
1142
1143 Parameters
1143 Parameters
1144 ----------
1144 ----------
1145 text : string, optional
1145 text : string, optional
1146 Text to perform the completion on. If not given, the line buffer
1146 Text to perform the completion on. If not given, the line buffer
1147 is split using the instance's CompletionSplitter object.
1147 is split using the instance's CompletionSplitter object.
1148
1148
1149 line_buffer : string, optional
1149 line_buffer : string, optional
1150 If not given, the completer attempts to obtain the current line
1150 If not given, the completer attempts to obtain the current line
1151 buffer via readline. This keyword allows clients which are
1151 buffer via readline. This keyword allows clients which are
1152 requesting for text completions in non-readline contexts to inform
1152 requesting for text completions in non-readline contexts to inform
1153 the completer of the entire text.
1153 the completer of the entire text.
1154
1154
1155 cursor_pos : int, optional
1155 cursor_pos : int, optional
1156 Index of the cursor in the full line buffer. Should be provided by
1156 Index of the cursor in the full line buffer. Should be provided by
1157 remote frontends where kernel has no access to frontend state.
1157 remote frontends where kernel has no access to frontend state.
1158
1158
1159 Returns
1159 Returns
1160 -------
1160 -------
1161 text : str
1161 text : str
1162 Text that was actually used in the completion.
1162 Text that was actually used in the completion.
1163
1163
1164 matches : list
1164 matches : list
1165 A list of completion matches.
1165 A list of completion matches.
1166 """
1166 """
1167 # if the cursor position isn't given, the only sane assumption we can
1167 # if the cursor position isn't given, the only sane assumption we can
1168 # make is that it's at the end of the line (the common case)
1168 # make is that it's at the end of the line (the common case)
1169 if cursor_pos is None:
1169 if cursor_pos is None:
1170 cursor_pos = len(line_buffer) if text is None else len(text)
1170 cursor_pos = len(line_buffer) if text is None else len(text)
1171
1171
1172 if self.use_main_ns:
1172 if self.use_main_ns:
1173 self.namespace = __main__.__dict__
1173 self.namespace = __main__.__dict__
1174
1174
1175 if PY3:
1175 if PY3:
1176
1176
1177 base_text = text if not line_buffer else line_buffer[:cursor_pos]
1177 base_text = text if not line_buffer else line_buffer[:cursor_pos]
1178 latex_text, latex_matches = self.latex_matches(base_text)
1178 latex_text, latex_matches = self.latex_matches(base_text)
1179 if latex_matches:
1179 if latex_matches:
1180 return latex_text, latex_matches
1180 return latex_text, latex_matches
1181 name_text = ''
1181 name_text = ''
1182 name_matches = []
1182 name_matches = []
1183 for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches):
1183 for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches):
1184 name_text, name_matches = meth(base_text)
1184 name_text, name_matches = meth(base_text)
1185 if name_text:
1185 if name_text:
1186 return name_text, name_matches
1186 return name_text, name_matches
1187
1187
1188 # if text is either None or an empty string, rely on the line buffer
1188 # if text is either None or an empty string, rely on the line buffer
1189 if not text:
1189 if not text:
1190 text = self.splitter.split_line(line_buffer, cursor_pos)
1190 text = self.splitter.split_line(line_buffer, cursor_pos)
1191
1191
1192 # If no line buffer is given, assume the input text is all there was
1192 # If no line buffer is given, assume the input text is all there was
1193 if line_buffer is None:
1193 if line_buffer is None:
1194 line_buffer = text
1194 line_buffer = text
1195
1195
1196 self.line_buffer = line_buffer
1196 self.line_buffer = line_buffer
1197 self.text_until_cursor = self.line_buffer[:cursor_pos]
1197 self.text_until_cursor = self.line_buffer[:cursor_pos]
1198
1198
1199 # Start with a clean slate of completions
1199 # Start with a clean slate of completions
1200 self.matches[:] = []
1200 self.matches[:] = []
1201 custom_res = self.dispatch_custom_completer(text)
1201 custom_res = self.dispatch_custom_completer(text)
1202 if custom_res is not None:
1202 if custom_res is not None:
1203 # did custom completers produce something?
1203 # did custom completers produce something?
1204 self.matches = custom_res
1204 self.matches = custom_res
1205 else:
1205 else:
1206 # Extend the list of completions with the results of each
1206 # Extend the list of completions with the results of each
1207 # matcher, so we return results to the user from all
1207 # matcher, so we return results to the user from all
1208 # namespaces.
1208 # namespaces.
1209 if self.merge_completions:
1209 if self.merge_completions:
1210 self.matches = []
1210 self.matches = []
1211 for matcher in self.matchers:
1211 for matcher in self.matchers:
1212 try:
1212 try:
1213 self.matches.extend(matcher(text))
1213 self.matches.extend(matcher(text))
1214 except:
1214 except:
1215 # Show the ugly traceback if the matcher causes an
1215 # Show the ugly traceback if the matcher causes an
1216 # exception, but do NOT crash the kernel!
1216 # exception, but do NOT crash the kernel!
1217 sys.excepthook(*sys.exc_info())
1217 sys.excepthook(*sys.exc_info())
1218 else:
1218 else:
1219 for matcher in self.matchers:
1219 for matcher in self.matchers:
1220 self.matches = matcher(text)
1220 self.matches = matcher(text)
1221 if self.matches:
1221 if self.matches:
1222 break
1222 break
1223 # FIXME: we should extend our api to return a dict with completions for
1223 # FIXME: we should extend our api to return a dict with completions for
1224 # different types of objects. The rlcomplete() method could then
1224 # different types of objects. The rlcomplete() method could then
1225 # simply collapse the dict into a list for readline, but we'd have
1225 # simply collapse the dict into a list for readline, but we'd have
1226 # richer completion semantics in other evironments.
1226 # richer completion semantics in other evironments.
1227 self.matches = sorted(set(self.matches), key=completions_sorting_key)
1227 self.matches = sorted(set(self.matches), key=completions_sorting_key)
1228
1228
1229 return text, self.matches
1229 return text, self.matches
@@ -1,343 +1,342 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Implementations for various useful completers.
2 """Implementations for various useful completers.
3
3
4 These are all loaded by default by IPython.
4 These are all loaded by default by IPython.
5 """
5 """
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2010-2011 The IPython Development Team.
7 # Copyright (C) 2010-2011 The IPython Development Team.
8 #
8 #
9 # Distributed under the terms of the BSD License.
9 # Distributed under the terms of the 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 imports
18 # Stdlib imports
19 import glob
19 import glob
20 import inspect
20 import inspect
21 import os
21 import os
22 import re
22 import re
23 import sys
23 import sys
24 from importlib import import_module
24 from importlib import import_module
25 from importlib.machinery import all_suffixes
25 from importlib.machinery import all_suffixes
26
26
27
27
28 # Third-party imports
28 # Third-party imports
29 from time import time
29 from time import time
30 from zipimport import zipimporter
30 from zipimport import zipimporter
31
31
32 # Our own imports
32 # Our own imports
33 from IPython.core.completer import expand_user, compress_user
33 from IPython.core.completer import expand_user, compress_user
34 from IPython.core.error import TryNext
34 from IPython.core.error import TryNext
35 from IPython.utils._process_common import arg_split
35 from IPython.utils._process_common import arg_split
36 from IPython.utils.py3compat import string_types
37
36
38 # FIXME: this should be pulled in with the right call via the component system
37 # FIXME: this should be pulled in with the right call via the component system
39 from IPython import get_ipython
38 from IPython import get_ipython
40
39
41 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
42 # Globals and constants
41 # Globals and constants
43 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
44 _suffixes = all_suffixes()
43 _suffixes = all_suffixes()
45
44
46 # Time in seconds after which the rootmodules will be stored permanently in the
45 # Time in seconds after which the rootmodules will be stored permanently in the
47 # ipython ip.db database (kept in the user's .ipython dir).
46 # ipython ip.db database (kept in the user's .ipython dir).
48 TIMEOUT_STORAGE = 2
47 TIMEOUT_STORAGE = 2
49
48
50 # Time in seconds after which we give up
49 # Time in seconds after which we give up
51 TIMEOUT_GIVEUP = 20
50 TIMEOUT_GIVEUP = 20
52
51
53 # Regular expression for the python import statement
52 # Regular expression for the python import statement
54 import_re = re.compile(r'(?P<name>[a-zA-Z_][a-zA-Z0-9_]*?)'
53 import_re = re.compile(r'(?P<name>[a-zA-Z_][a-zA-Z0-9_]*?)'
55 r'(?P<package>[/\\]__init__)?'
54 r'(?P<package>[/\\]__init__)?'
56 r'(?P<suffix>%s)$' %
55 r'(?P<suffix>%s)$' %
57 r'|'.join(re.escape(s) for s in _suffixes))
56 r'|'.join(re.escape(s) for s in _suffixes))
58
57
59 # RE for the ipython %run command (python + ipython scripts)
58 # RE for the ipython %run command (python + ipython scripts)
60 magic_run_re = re.compile(r'.*(\.ipy|\.ipynb|\.py[w]?)$')
59 magic_run_re = re.compile(r'.*(\.ipy|\.ipynb|\.py[w]?)$')
61
60
62 #-----------------------------------------------------------------------------
61 #-----------------------------------------------------------------------------
63 # Local utilities
62 # Local utilities
64 #-----------------------------------------------------------------------------
63 #-----------------------------------------------------------------------------
65
64
66 def module_list(path):
65 def module_list(path):
67 """
66 """
68 Return the list containing the names of the modules available in the given
67 Return the list containing the names of the modules available in the given
69 folder.
68 folder.
70 """
69 """
71 # sys.path has the cwd as an empty string, but isdir/listdir need it as '.'
70 # sys.path has the cwd as an empty string, but isdir/listdir need it as '.'
72 if path == '':
71 if path == '':
73 path = '.'
72 path = '.'
74
73
75 # A few local constants to be used in loops below
74 # A few local constants to be used in loops below
76 pjoin = os.path.join
75 pjoin = os.path.join
77
76
78 if os.path.isdir(path):
77 if os.path.isdir(path):
79 # Build a list of all files in the directory and all files
78 # Build a list of all files in the directory and all files
80 # in its subdirectories. For performance reasons, do not
79 # in its subdirectories. For performance reasons, do not
81 # recurse more than one level into subdirectories.
80 # recurse more than one level into subdirectories.
82 files = []
81 files = []
83 for root, dirs, nondirs in os.walk(path, followlinks=True):
82 for root, dirs, nondirs in os.walk(path, followlinks=True):
84 subdir = root[len(path)+1:]
83 subdir = root[len(path)+1:]
85 if subdir:
84 if subdir:
86 files.extend(pjoin(subdir, f) for f in nondirs)
85 files.extend(pjoin(subdir, f) for f in nondirs)
87 dirs[:] = [] # Do not recurse into additional subdirectories.
86 dirs[:] = [] # Do not recurse into additional subdirectories.
88 else:
87 else:
89 files.extend(nondirs)
88 files.extend(nondirs)
90
89
91 else:
90 else:
92 try:
91 try:
93 files = list(zipimporter(path)._files.keys())
92 files = list(zipimporter(path)._files.keys())
94 except:
93 except:
95 files = []
94 files = []
96
95
97 # Build a list of modules which match the import_re regex.
96 # Build a list of modules which match the import_re regex.
98 modules = []
97 modules = []
99 for f in files:
98 for f in files:
100 m = import_re.match(f)
99 m = import_re.match(f)
101 if m:
100 if m:
102 modules.append(m.group('name'))
101 modules.append(m.group('name'))
103 return list(set(modules))
102 return list(set(modules))
104
103
105
104
106 def get_root_modules():
105 def get_root_modules():
107 """
106 """
108 Returns a list containing the names of all the modules available in the
107 Returns a list containing the names of all the modules available in the
109 folders of the pythonpath.
108 folders of the pythonpath.
110
109
111 ip.db['rootmodules_cache'] maps sys.path entries to list of modules.
110 ip.db['rootmodules_cache'] maps sys.path entries to list of modules.
112 """
111 """
113 ip = get_ipython()
112 ip = get_ipython()
114 rootmodules_cache = ip.db.get('rootmodules_cache', {})
113 rootmodules_cache = ip.db.get('rootmodules_cache', {})
115 rootmodules = list(sys.builtin_module_names)
114 rootmodules = list(sys.builtin_module_names)
116 start_time = time()
115 start_time = time()
117 store = False
116 store = False
118 for path in sys.path:
117 for path in sys.path:
119 try:
118 try:
120 modules = rootmodules_cache[path]
119 modules = rootmodules_cache[path]
121 except KeyError:
120 except KeyError:
122 modules = module_list(path)
121 modules = module_list(path)
123 try:
122 try:
124 modules.remove('__init__')
123 modules.remove('__init__')
125 except ValueError:
124 except ValueError:
126 pass
125 pass
127 if path not in ('', '.'): # cwd modules should not be cached
126 if path not in ('', '.'): # cwd modules should not be cached
128 rootmodules_cache[path] = modules
127 rootmodules_cache[path] = modules
129 if time() - start_time > TIMEOUT_STORAGE and not store:
128 if time() - start_time > TIMEOUT_STORAGE and not store:
130 store = True
129 store = True
131 print("\nCaching the list of root modules, please wait!")
130 print("\nCaching the list of root modules, please wait!")
132 print("(This will only be done once - type '%rehashx' to "
131 print("(This will only be done once - type '%rehashx' to "
133 "reset cache!)\n")
132 "reset cache!)\n")
134 sys.stdout.flush()
133 sys.stdout.flush()
135 if time() - start_time > TIMEOUT_GIVEUP:
134 if time() - start_time > TIMEOUT_GIVEUP:
136 print("This is taking too long, we give up.\n")
135 print("This is taking too long, we give up.\n")
137 return []
136 return []
138 rootmodules.extend(modules)
137 rootmodules.extend(modules)
139 if store:
138 if store:
140 ip.db['rootmodules_cache'] = rootmodules_cache
139 ip.db['rootmodules_cache'] = rootmodules_cache
141 rootmodules = list(set(rootmodules))
140 rootmodules = list(set(rootmodules))
142 return rootmodules
141 return rootmodules
143
142
144
143
145 def is_importable(module, attr, only_modules):
144 def is_importable(module, attr, only_modules):
146 if only_modules:
145 if only_modules:
147 return inspect.ismodule(getattr(module, attr))
146 return inspect.ismodule(getattr(module, attr))
148 else:
147 else:
149 return not(attr[:2] == '__' and attr[-2:] == '__')
148 return not(attr[:2] == '__' and attr[-2:] == '__')
150
149
151 def try_import(mod, only_modules=False):
150 def try_import(mod, only_modules=False):
152 try:
151 try:
153 m = import_module(mod)
152 m = import_module(mod)
154 except:
153 except:
155 return []
154 return []
156
155
157 m_is_init = hasattr(m, '__file__') and '__init__' in m.__file__
156 m_is_init = hasattr(m, '__file__') and '__init__' in m.__file__
158
157
159 completions = []
158 completions = []
160 if (not hasattr(m, '__file__')) or (not only_modules) or m_is_init:
159 if (not hasattr(m, '__file__')) or (not only_modules) or m_is_init:
161 completions.extend( [attr for attr in dir(m) if
160 completions.extend( [attr for attr in dir(m) if
162 is_importable(m, attr, only_modules)])
161 is_importable(m, attr, only_modules)])
163
162
164 completions.extend(getattr(m, '__all__', []))
163 completions.extend(getattr(m, '__all__', []))
165 if m_is_init:
164 if m_is_init:
166 completions.extend(module_list(os.path.dirname(m.__file__)))
165 completions.extend(module_list(os.path.dirname(m.__file__)))
167 completions = {c for c in completions if isinstance(c, string_types)}
166 completions = {c for c in completions if isinstance(c, str)}
168 completions.discard('__init__')
167 completions.discard('__init__')
169 return list(completions)
168 return list(completions)
170
169
171
170
172 #-----------------------------------------------------------------------------
171 #-----------------------------------------------------------------------------
173 # Completion-related functions.
172 # Completion-related functions.
174 #-----------------------------------------------------------------------------
173 #-----------------------------------------------------------------------------
175
174
176 def quick_completer(cmd, completions):
175 def quick_completer(cmd, completions):
177 """ Easily create a trivial completer for a command.
176 """ Easily create a trivial completer for a command.
178
177
179 Takes either a list of completions, or all completions in string (that will
178 Takes either a list of completions, or all completions in string (that will
180 be split on whitespace).
179 be split on whitespace).
181
180
182 Example::
181 Example::
183
182
184 [d:\ipython]|1> import ipy_completers
183 [d:\ipython]|1> import ipy_completers
185 [d:\ipython]|2> ipy_completers.quick_completer('foo', ['bar','baz'])
184 [d:\ipython]|2> ipy_completers.quick_completer('foo', ['bar','baz'])
186 [d:\ipython]|3> foo b<TAB>
185 [d:\ipython]|3> foo b<TAB>
187 bar baz
186 bar baz
188 [d:\ipython]|3> foo ba
187 [d:\ipython]|3> foo ba
189 """
188 """
190
189
191 if isinstance(completions, string_types):
190 if isinstance(completions, str):
192 completions = completions.split()
191 completions = completions.split()
193
192
194 def do_complete(self, event):
193 def do_complete(self, event):
195 return completions
194 return completions
196
195
197 get_ipython().set_hook('complete_command',do_complete, str_key = cmd)
196 get_ipython().set_hook('complete_command',do_complete, str_key = cmd)
198
197
199 def module_completion(line):
198 def module_completion(line):
200 """
199 """
201 Returns a list containing the completion possibilities for an import line.
200 Returns a list containing the completion possibilities for an import line.
202
201
203 The line looks like this :
202 The line looks like this :
204 'import xml.d'
203 'import xml.d'
205 'from xml.dom import'
204 'from xml.dom import'
206 """
205 """
207
206
208 words = line.split(' ')
207 words = line.split(' ')
209 nwords = len(words)
208 nwords = len(words)
210
209
211 # from whatever <tab> -> 'import '
210 # from whatever <tab> -> 'import '
212 if nwords == 3 and words[0] == 'from':
211 if nwords == 3 and words[0] == 'from':
213 return ['import ']
212 return ['import ']
214
213
215 # 'from xy<tab>' or 'import xy<tab>'
214 # 'from xy<tab>' or 'import xy<tab>'
216 if nwords < 3 and (words[0] in {'%aimport', 'import', 'from'}) :
215 if nwords < 3 and (words[0] in {'%aimport', 'import', 'from'}) :
217 if nwords == 1:
216 if nwords == 1:
218 return get_root_modules()
217 return get_root_modules()
219 mod = words[1].split('.')
218 mod = words[1].split('.')
220 if len(mod) < 2:
219 if len(mod) < 2:
221 return get_root_modules()
220 return get_root_modules()
222 completion_list = try_import('.'.join(mod[:-1]), True)
221 completion_list = try_import('.'.join(mod[:-1]), True)
223 return ['.'.join(mod[:-1] + [el]) for el in completion_list]
222 return ['.'.join(mod[:-1] + [el]) for el in completion_list]
224
223
225 # 'from xyz import abc<tab>'
224 # 'from xyz import abc<tab>'
226 if nwords >= 3 and words[0] == 'from':
225 if nwords >= 3 and words[0] == 'from':
227 mod = words[1]
226 mod = words[1]
228 return try_import(mod)
227 return try_import(mod)
229
228
230 #-----------------------------------------------------------------------------
229 #-----------------------------------------------------------------------------
231 # Completers
230 # Completers
232 #-----------------------------------------------------------------------------
231 #-----------------------------------------------------------------------------
233 # These all have the func(self, event) signature to be used as custom
232 # These all have the func(self, event) signature to be used as custom
234 # completers
233 # completers
235
234
236 def module_completer(self,event):
235 def module_completer(self,event):
237 """Give completions after user has typed 'import ...' or 'from ...'"""
236 """Give completions after user has typed 'import ...' or 'from ...'"""
238
237
239 # This works in all versions of python. While 2.5 has
238 # This works in all versions of python. While 2.5 has
240 # pkgutil.walk_packages(), that particular routine is fairly dangerous,
239 # pkgutil.walk_packages(), that particular routine is fairly dangerous,
241 # since it imports *EVERYTHING* on sys.path. That is: a) very slow b) full
240 # since it imports *EVERYTHING* on sys.path. That is: a) very slow b) full
242 # of possibly problematic side effects.
241 # of possibly problematic side effects.
243 # This search the folders in the sys.path for available modules.
242 # This search the folders in the sys.path for available modules.
244
243
245 return module_completion(event.line)
244 return module_completion(event.line)
246
245
247 # FIXME: there's a lot of logic common to the run, cd and builtin file
246 # FIXME: there's a lot of logic common to the run, cd and builtin file
248 # completers, that is currently reimplemented in each.
247 # completers, that is currently reimplemented in each.
249
248
250 def magic_run_completer(self, event):
249 def magic_run_completer(self, event):
251 """Complete files that end in .py or .ipy or .ipynb for the %run command.
250 """Complete files that end in .py or .ipy or .ipynb for the %run command.
252 """
251 """
253 comps = arg_split(event.line, strict=False)
252 comps = arg_split(event.line, strict=False)
254 # relpath should be the current token that we need to complete.
253 # relpath should be the current token that we need to complete.
255 if (len(comps) > 1) and (not event.line.endswith(' ')):
254 if (len(comps) > 1) and (not event.line.endswith(' ')):
256 relpath = comps[-1].strip("'\"")
255 relpath = comps[-1].strip("'\"")
257 else:
256 else:
258 relpath = ''
257 relpath = ''
259
258
260 #print("\nev=", event) # dbg
259 #print("\nev=", event) # dbg
261 #print("rp=", relpath) # dbg
260 #print("rp=", relpath) # dbg
262 #print('comps=', comps) # dbg
261 #print('comps=', comps) # dbg
263
262
264 lglob = glob.glob
263 lglob = glob.glob
265 isdir = os.path.isdir
264 isdir = os.path.isdir
266 relpath, tilde_expand, tilde_val = expand_user(relpath)
265 relpath, tilde_expand, tilde_val = expand_user(relpath)
267
266
268 # Find if the user has already typed the first filename, after which we
267 # Find if the user has already typed the first filename, after which we
269 # should complete on all files, since after the first one other files may
268 # should complete on all files, since after the first one other files may
270 # be arguments to the input script.
269 # be arguments to the input script.
271
270
272 if any(magic_run_re.match(c) for c in comps):
271 if any(magic_run_re.match(c) for c in comps):
273 matches = [f.replace('\\','/') + ('/' if isdir(f) else '')
272 matches = [f.replace('\\','/') + ('/' if isdir(f) else '')
274 for f in lglob(relpath+'*')]
273 for f in lglob(relpath+'*')]
275 else:
274 else:
276 dirs = [f.replace('\\','/') + "/" for f in lglob(relpath+'*') if isdir(f)]
275 dirs = [f.replace('\\','/') + "/" for f in lglob(relpath+'*') if isdir(f)]
277 pys = [f.replace('\\','/')
276 pys = [f.replace('\\','/')
278 for f in lglob(relpath+'*.py') + lglob(relpath+'*.ipy') +
277 for f in lglob(relpath+'*.py') + lglob(relpath+'*.ipy') +
279 lglob(relpath+'*.ipynb') + lglob(relpath + '*.pyw')]
278 lglob(relpath+'*.ipynb') + lglob(relpath + '*.pyw')]
280
279
281 matches = dirs + pys
280 matches = dirs + pys
282
281
283 #print('run comp:', dirs+pys) # dbg
282 #print('run comp:', dirs+pys) # dbg
284 return [compress_user(p, tilde_expand, tilde_val) for p in matches]
283 return [compress_user(p, tilde_expand, tilde_val) for p in matches]
285
284
286
285
287 def cd_completer(self, event):
286 def cd_completer(self, event):
288 """Completer function for cd, which only returns directories."""
287 """Completer function for cd, which only returns directories."""
289 ip = get_ipython()
288 ip = get_ipython()
290 relpath = event.symbol
289 relpath = event.symbol
291
290
292 #print(event) # dbg
291 #print(event) # dbg
293 if event.line.endswith('-b') or ' -b ' in event.line:
292 if event.line.endswith('-b') or ' -b ' in event.line:
294 # return only bookmark completions
293 # return only bookmark completions
295 bkms = self.db.get('bookmarks', None)
294 bkms = self.db.get('bookmarks', None)
296 if bkms:
295 if bkms:
297 return bkms.keys()
296 return bkms.keys()
298 else:
297 else:
299 return []
298 return []
300
299
301 if event.symbol == '-':
300 if event.symbol == '-':
302 width_dh = str(len(str(len(ip.user_ns['_dh']) + 1)))
301 width_dh = str(len(str(len(ip.user_ns['_dh']) + 1)))
303 # jump in directory history by number
302 # jump in directory history by number
304 fmt = '-%0' + width_dh +'d [%s]'
303 fmt = '-%0' + width_dh +'d [%s]'
305 ents = [ fmt % (i,s) for i,s in enumerate(ip.user_ns['_dh'])]
304 ents = [ fmt % (i,s) for i,s in enumerate(ip.user_ns['_dh'])]
306 if len(ents) > 1:
305 if len(ents) > 1:
307 return ents
306 return ents
308 return []
307 return []
309
308
310 if event.symbol.startswith('--'):
309 if event.symbol.startswith('--'):
311 return ["--" + os.path.basename(d) for d in ip.user_ns['_dh']]
310 return ["--" + os.path.basename(d) for d in ip.user_ns['_dh']]
312
311
313 # Expand ~ in path and normalize directory separators.
312 # Expand ~ in path and normalize directory separators.
314 relpath, tilde_expand, tilde_val = expand_user(relpath)
313 relpath, tilde_expand, tilde_val = expand_user(relpath)
315 relpath = relpath.replace('\\','/')
314 relpath = relpath.replace('\\','/')
316
315
317 found = []
316 found = []
318 for d in [f.replace('\\','/') + '/' for f in glob.glob(relpath+'*')
317 for d in [f.replace('\\','/') + '/' for f in glob.glob(relpath+'*')
319 if os.path.isdir(f)]:
318 if os.path.isdir(f)]:
320 if ' ' in d:
319 if ' ' in d:
321 # we don't want to deal with any of that, complex code
320 # we don't want to deal with any of that, complex code
322 # for this is elsewhere
321 # for this is elsewhere
323 raise TryNext
322 raise TryNext
324
323
325 found.append(d)
324 found.append(d)
326
325
327 if not found:
326 if not found:
328 if os.path.isdir(relpath):
327 if os.path.isdir(relpath):
329 return [compress_user(relpath, tilde_expand, tilde_val)]
328 return [compress_user(relpath, tilde_expand, tilde_val)]
330
329
331 # if no completions so far, try bookmarks
330 # if no completions so far, try bookmarks
332 bks = self.db.get('bookmarks',{})
331 bks = self.db.get('bookmarks',{})
333 bkmatches = [s for s in bks if s.startswith(event.symbol)]
332 bkmatches = [s for s in bks if s.startswith(event.symbol)]
334 if bkmatches:
333 if bkmatches:
335 return bkmatches
334 return bkmatches
336
335
337 raise TryNext
336 raise TryNext
338
337
339 return [compress_user(p, tilde_expand, tilde_val) for p in found]
338 return [compress_user(p, tilde_expand, tilde_val) for p in found]
340
339
341 def reset_completer(self, event):
340 def reset_completer(self, event):
342 "A completer for %reset magic"
341 "A completer for %reset magic"
343 return '-f -s in out array dhist'.split()
342 return '-f -s in out array dhist'.split()
@@ -1,215 +1,215 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """sys.excepthook for IPython itself, leaves a detailed report on disk.
2 """sys.excepthook for IPython itself, leaves a detailed report on disk.
3
3
4 Authors:
4 Authors:
5
5
6 * Fernando Perez
6 * Fernando Perez
7 * Brian E. Granger
7 * Brian E. Granger
8 """
8 """
9
9
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
11 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
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. The full license is in
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
15 # the file COPYING, distributed as part of this software.
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19 # Imports
19 # Imports
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 import os
22 import os
23 import sys
23 import sys
24 import traceback
24 import traceback
25 from pprint import pformat
25 from pprint import pformat
26
26
27 from IPython.core import ultratb
27 from IPython.core import ultratb
28 from IPython.core.release import author_email
28 from IPython.core.release import author_email
29 from IPython.utils.sysinfo import sys_info
29 from IPython.utils.sysinfo import sys_info
30 from IPython.utils.py3compat import input, getcwd
30 from IPython.utils.py3compat import input
31
31
32 #-----------------------------------------------------------------------------
32 #-----------------------------------------------------------------------------
33 # Code
33 # Code
34 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
35
35
36 # Template for the user message.
36 # Template for the user message.
37 _default_message_template = """\
37 _default_message_template = """\
38 Oops, {app_name} crashed. We do our best to make it stable, but...
38 Oops, {app_name} crashed. We do our best to make it stable, but...
39
39
40 A crash report was automatically generated with the following information:
40 A crash report was automatically generated with the following information:
41 - A verbatim copy of the crash traceback.
41 - A verbatim copy of the crash traceback.
42 - A copy of your input history during this session.
42 - A copy of your input history during this session.
43 - Data on your current {app_name} configuration.
43 - Data on your current {app_name} configuration.
44
44
45 It was left in the file named:
45 It was left in the file named:
46 \t'{crash_report_fname}'
46 \t'{crash_report_fname}'
47 If you can email this file to the developers, the information in it will help
47 If you can email this file to the developers, the information in it will help
48 them in understanding and correcting the problem.
48 them in understanding and correcting the problem.
49
49
50 You can mail it to: {contact_name} at {contact_email}
50 You can mail it to: {contact_name} at {contact_email}
51 with the subject '{app_name} Crash Report'.
51 with the subject '{app_name} Crash Report'.
52
52
53 If you want to do it now, the following command will work (under Unix):
53 If you want to do it now, the following command will work (under Unix):
54 mail -s '{app_name} Crash Report' {contact_email} < {crash_report_fname}
54 mail -s '{app_name} Crash Report' {contact_email} < {crash_report_fname}
55
55
56 To ensure accurate tracking of this issue, please file a report about it at:
56 To ensure accurate tracking of this issue, please file a report about it at:
57 {bug_tracker}
57 {bug_tracker}
58 """
58 """
59
59
60 _lite_message_template = """
60 _lite_message_template = """
61 If you suspect this is an IPython bug, please report it at:
61 If you suspect this is an IPython bug, please report it at:
62 https://github.com/ipython/ipython/issues
62 https://github.com/ipython/ipython/issues
63 or send an email to the mailing list at {email}
63 or send an email to the mailing list at {email}
64
64
65 You can print a more detailed traceback right now with "%tb", or use "%debug"
65 You can print a more detailed traceback right now with "%tb", or use "%debug"
66 to interactively debug it.
66 to interactively debug it.
67
67
68 Extra-detailed tracebacks for bug-reporting purposes can be enabled via:
68 Extra-detailed tracebacks for bug-reporting purposes can be enabled via:
69 {config}Application.verbose_crash=True
69 {config}Application.verbose_crash=True
70 """
70 """
71
71
72
72
73 class CrashHandler(object):
73 class CrashHandler(object):
74 """Customizable crash handlers for IPython applications.
74 """Customizable crash handlers for IPython applications.
75
75
76 Instances of this class provide a :meth:`__call__` method which can be
76 Instances of this class provide a :meth:`__call__` method which can be
77 used as a ``sys.excepthook``. The :meth:`__call__` signature is::
77 used as a ``sys.excepthook``. The :meth:`__call__` signature is::
78
78
79 def __call__(self, etype, evalue, etb)
79 def __call__(self, etype, evalue, etb)
80 """
80 """
81
81
82 message_template = _default_message_template
82 message_template = _default_message_template
83 section_sep = '\n\n'+'*'*75+'\n\n'
83 section_sep = '\n\n'+'*'*75+'\n\n'
84
84
85 def __init__(self, app, contact_name=None, contact_email=None,
85 def __init__(self, app, contact_name=None, contact_email=None,
86 bug_tracker=None, show_crash_traceback=True, call_pdb=False):
86 bug_tracker=None, show_crash_traceback=True, call_pdb=False):
87 """Create a new crash handler
87 """Create a new crash handler
88
88
89 Parameters
89 Parameters
90 ----------
90 ----------
91 app : Application
91 app : Application
92 A running :class:`Application` instance, which will be queried at
92 A running :class:`Application` instance, which will be queried at
93 crash time for internal information.
93 crash time for internal information.
94
94
95 contact_name : str
95 contact_name : str
96 A string with the name of the person to contact.
96 A string with the name of the person to contact.
97
97
98 contact_email : str
98 contact_email : str
99 A string with the email address of the contact.
99 A string with the email address of the contact.
100
100
101 bug_tracker : str
101 bug_tracker : str
102 A string with the URL for your project's bug tracker.
102 A string with the URL for your project's bug tracker.
103
103
104 show_crash_traceback : bool
104 show_crash_traceback : bool
105 If false, don't print the crash traceback on stderr, only generate
105 If false, don't print the crash traceback on stderr, only generate
106 the on-disk report
106 the on-disk report
107
107
108 Non-argument instance attributes:
108 Non-argument instance attributes:
109
109
110 These instances contain some non-argument attributes which allow for
110 These instances contain some non-argument attributes which allow for
111 further customization of the crash handler's behavior. Please see the
111 further customization of the crash handler's behavior. Please see the
112 source for further details.
112 source for further details.
113 """
113 """
114 self.crash_report_fname = "Crash_report_%s.txt" % app.name
114 self.crash_report_fname = "Crash_report_%s.txt" % app.name
115 self.app = app
115 self.app = app
116 self.call_pdb = call_pdb
116 self.call_pdb = call_pdb
117 #self.call_pdb = True # dbg
117 #self.call_pdb = True # dbg
118 self.show_crash_traceback = show_crash_traceback
118 self.show_crash_traceback = show_crash_traceback
119 self.info = dict(app_name = app.name,
119 self.info = dict(app_name = app.name,
120 contact_name = contact_name,
120 contact_name = contact_name,
121 contact_email = contact_email,
121 contact_email = contact_email,
122 bug_tracker = bug_tracker,
122 bug_tracker = bug_tracker,
123 crash_report_fname = self.crash_report_fname)
123 crash_report_fname = self.crash_report_fname)
124
124
125
125
126 def __call__(self, etype, evalue, etb):
126 def __call__(self, etype, evalue, etb):
127 """Handle an exception, call for compatible with sys.excepthook"""
127 """Handle an exception, call for compatible with sys.excepthook"""
128
128
129 # do not allow the crash handler to be called twice without reinstalling it
129 # do not allow the crash handler to be called twice without reinstalling it
130 # this prevents unlikely errors in the crash handling from entering an
130 # this prevents unlikely errors in the crash handling from entering an
131 # infinite loop.
131 # infinite loop.
132 sys.excepthook = sys.__excepthook__
132 sys.excepthook = sys.__excepthook__
133
133
134 # Report tracebacks shouldn't use color in general (safer for users)
134 # Report tracebacks shouldn't use color in general (safer for users)
135 color_scheme = 'NoColor'
135 color_scheme = 'NoColor'
136
136
137 # Use this ONLY for developer debugging (keep commented out for release)
137 # Use this ONLY for developer debugging (keep commented out for release)
138 #color_scheme = 'Linux' # dbg
138 #color_scheme = 'Linux' # dbg
139 try:
139 try:
140 rptdir = self.app.ipython_dir
140 rptdir = self.app.ipython_dir
141 except:
141 except:
142 rptdir = getcwd()
142 rptdir = os.getcwd()
143 if rptdir is None or not os.path.isdir(rptdir):
143 if rptdir is None or not os.path.isdir(rptdir):
144 rptdir = getcwd()
144 rptdir = os.getcwd()
145 report_name = os.path.join(rptdir,self.crash_report_fname)
145 report_name = os.path.join(rptdir,self.crash_report_fname)
146 # write the report filename into the instance dict so it can get
146 # write the report filename into the instance dict so it can get
147 # properly expanded out in the user message template
147 # properly expanded out in the user message template
148 self.crash_report_fname = report_name
148 self.crash_report_fname = report_name
149 self.info['crash_report_fname'] = report_name
149 self.info['crash_report_fname'] = report_name
150 TBhandler = ultratb.VerboseTB(
150 TBhandler = ultratb.VerboseTB(
151 color_scheme=color_scheme,
151 color_scheme=color_scheme,
152 long_header=1,
152 long_header=1,
153 call_pdb=self.call_pdb,
153 call_pdb=self.call_pdb,
154 )
154 )
155 if self.call_pdb:
155 if self.call_pdb:
156 TBhandler(etype,evalue,etb)
156 TBhandler(etype,evalue,etb)
157 return
157 return
158 else:
158 else:
159 traceback = TBhandler.text(etype,evalue,etb,context=31)
159 traceback = TBhandler.text(etype,evalue,etb,context=31)
160
160
161 # print traceback to screen
161 # print traceback to screen
162 if self.show_crash_traceback:
162 if self.show_crash_traceback:
163 print(traceback, file=sys.stderr)
163 print(traceback, file=sys.stderr)
164
164
165 # and generate a complete report on disk
165 # and generate a complete report on disk
166 try:
166 try:
167 report = open(report_name,'w')
167 report = open(report_name,'w')
168 except:
168 except:
169 print('Could not create crash report on disk.', file=sys.stderr)
169 print('Could not create crash report on disk.', file=sys.stderr)
170 return
170 return
171
171
172 # Inform user on stderr of what happened
172 # Inform user on stderr of what happened
173 print('\n'+'*'*70+'\n', file=sys.stderr)
173 print('\n'+'*'*70+'\n', file=sys.stderr)
174 print(self.message_template.format(**self.info), file=sys.stderr)
174 print(self.message_template.format(**self.info), file=sys.stderr)
175
175
176 # Construct report on disk
176 # Construct report on disk
177 report.write(self.make_report(traceback))
177 report.write(self.make_report(traceback))
178 report.close()
178 report.close()
179 input("Hit <Enter> to quit (your terminal may close):")
179 input("Hit <Enter> to quit (your terminal may close):")
180
180
181 def make_report(self,traceback):
181 def make_report(self,traceback):
182 """Return a string containing a crash report."""
182 """Return a string containing a crash report."""
183
183
184 sec_sep = self.section_sep
184 sec_sep = self.section_sep
185
185
186 report = ['*'*75+'\n\n'+'IPython post-mortem report\n\n']
186 report = ['*'*75+'\n\n'+'IPython post-mortem report\n\n']
187 rpt_add = report.append
187 rpt_add = report.append
188 rpt_add(sys_info())
188 rpt_add(sys_info())
189
189
190 try:
190 try:
191 config = pformat(self.app.config)
191 config = pformat(self.app.config)
192 rpt_add(sec_sep)
192 rpt_add(sec_sep)
193 rpt_add('Application name: %s\n\n' % self.app_name)
193 rpt_add('Application name: %s\n\n' % self.app_name)
194 rpt_add('Current user configuration structure:\n\n')
194 rpt_add('Current user configuration structure:\n\n')
195 rpt_add(config)
195 rpt_add(config)
196 except:
196 except:
197 pass
197 pass
198 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
198 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
199
199
200 return ''.join(report)
200 return ''.join(report)
201
201
202
202
203 def crash_handler_lite(etype, evalue, tb):
203 def crash_handler_lite(etype, evalue, tb):
204 """a light excepthook, adding a small message to the usual traceback"""
204 """a light excepthook, adding a small message to the usual traceback"""
205 traceback.print_exception(etype, evalue, tb)
205 traceback.print_exception(etype, evalue, tb)
206
206
207 from IPython.core.interactiveshell import InteractiveShell
207 from IPython.core.interactiveshell import InteractiveShell
208 if InteractiveShell.initialized():
208 if InteractiveShell.initialized():
209 # we are in a Shell environment, give %magic example
209 # we are in a Shell environment, give %magic example
210 config = "%config "
210 config = "%config "
211 else:
211 else:
212 # we are not in a shell, show generic config
212 # we are not in a shell, show generic config
213 config = "c."
213 config = "c."
214 print(_lite_message_template.format(email=author_email, config=config), file=sys.stderr)
214 print(_lite_message_template.format(email=author_email, config=config), file=sys.stderr)
215
215
@@ -1,1136 +1,1135 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Top-level display functions for displaying object in different formats."""
2 """Top-level display functions for displaying object in different formats."""
3
3
4 # Copyright (c) IPython Development Team.
4 # Copyright (c) IPython Development Team.
5 # Distributed under the terms of the Modified BSD License.
5 # Distributed under the terms of the Modified BSD License.
6
6
7
7
8 try:
8 try:
9 from base64 import encodebytes as base64_encode
9 from base64 import encodebytes as base64_encode
10 except ImportError:
10 except ImportError:
11 from base64 import encodestring as base64_encode
11 from base64 import encodestring as base64_encode
12
12
13 from binascii import b2a_hex
13 from binascii import b2a_hex
14 import json
14 import json
15 import mimetypes
15 import mimetypes
16 import os
16 import os
17 import struct
17 import struct
18 import sys
18 import sys
19 import warnings
19 import warnings
20
20
21 from IPython.utils.py3compat import (string_types, cast_bytes_py2, cast_unicode,
21 from IPython.utils.py3compat import cast_bytes_py2, cast_unicode
22 unicode_type)
23 from IPython.testing.skipdoctest import skip_doctest
22 from IPython.testing.skipdoctest import skip_doctest
24
23
25 __all__ = ['display', 'display_pretty', 'display_html', 'display_markdown',
24 __all__ = ['display', 'display_pretty', 'display_html', 'display_markdown',
26 'display_svg', 'display_png', 'display_jpeg', 'display_latex', 'display_json',
25 'display_svg', 'display_png', 'display_jpeg', 'display_latex', 'display_json',
27 'display_javascript', 'display_pdf', 'DisplayObject', 'TextDisplayObject',
26 'display_javascript', 'display_pdf', 'DisplayObject', 'TextDisplayObject',
28 'Pretty', 'HTML', 'Markdown', 'Math', 'Latex', 'SVG', 'JSON', 'Javascript',
27 'Pretty', 'HTML', 'Markdown', 'Math', 'Latex', 'SVG', 'JSON', 'Javascript',
29 'Image', 'clear_output', 'set_matplotlib_formats', 'set_matplotlib_close',
28 'Image', 'clear_output', 'set_matplotlib_formats', 'set_matplotlib_close',
30 'publish_display_data', 'update_display', 'DisplayHandle']
29 'publish_display_data', 'update_display', 'DisplayHandle']
31
30
32 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
33 # utility functions
32 # utility functions
34 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
35
34
36 def _safe_exists(path):
35 def _safe_exists(path):
37 """Check path, but don't let exceptions raise"""
36 """Check path, but don't let exceptions raise"""
38 try:
37 try:
39 return os.path.exists(path)
38 return os.path.exists(path)
40 except Exception:
39 except Exception:
41 return False
40 return False
42
41
43 def _merge(d1, d2):
42 def _merge(d1, d2):
44 """Like update, but merges sub-dicts instead of clobbering at the top level.
43 """Like update, but merges sub-dicts instead of clobbering at the top level.
45
44
46 Updates d1 in-place
45 Updates d1 in-place
47 """
46 """
48
47
49 if not isinstance(d2, dict) or not isinstance(d1, dict):
48 if not isinstance(d2, dict) or not isinstance(d1, dict):
50 return d2
49 return d2
51 for key, value in d2.items():
50 for key, value in d2.items():
52 d1[key] = _merge(d1.get(key), value)
51 d1[key] = _merge(d1.get(key), value)
53 return d1
52 return d1
54
53
55 def _display_mimetype(mimetype, objs, raw=False, metadata=None):
54 def _display_mimetype(mimetype, objs, raw=False, metadata=None):
56 """internal implementation of all display_foo methods
55 """internal implementation of all display_foo methods
57
56
58 Parameters
57 Parameters
59 ----------
58 ----------
60 mimetype : str
59 mimetype : str
61 The mimetype to be published (e.g. 'image/png')
60 The mimetype to be published (e.g. 'image/png')
62 objs : tuple of objects
61 objs : tuple of objects
63 The Python objects to display, or if raw=True raw text data to
62 The Python objects to display, or if raw=True raw text data to
64 display.
63 display.
65 raw : bool
64 raw : bool
66 Are the data objects raw data or Python objects that need to be
65 Are the data objects raw data or Python objects that need to be
67 formatted before display? [default: False]
66 formatted before display? [default: False]
68 metadata : dict (optional)
67 metadata : dict (optional)
69 Metadata to be associated with the specific mimetype output.
68 Metadata to be associated with the specific mimetype output.
70 """
69 """
71 if metadata:
70 if metadata:
72 metadata = {mimetype: metadata}
71 metadata = {mimetype: metadata}
73 if raw:
72 if raw:
74 # turn list of pngdata into list of { 'image/png': pngdata }
73 # turn list of pngdata into list of { 'image/png': pngdata }
75 objs = [ {mimetype: obj} for obj in objs ]
74 objs = [ {mimetype: obj} for obj in objs ]
76 display(*objs, raw=raw, metadata=metadata, include=[mimetype])
75 display(*objs, raw=raw, metadata=metadata, include=[mimetype])
77
76
78 #-----------------------------------------------------------------------------
77 #-----------------------------------------------------------------------------
79 # Main functions
78 # Main functions
80 #-----------------------------------------------------------------------------
79 #-----------------------------------------------------------------------------
81
80
82 # use * to indicate transient is keyword-only
81 # use * to indicate transient is keyword-only
83 def publish_display_data(data, metadata=None, source=None, *, transient=None, **kwargs):
82 def publish_display_data(data, metadata=None, source=None, *, transient=None, **kwargs):
84 """Publish data and metadata to all frontends.
83 """Publish data and metadata to all frontends.
85
84
86 See the ``display_data`` message in the messaging documentation for
85 See the ``display_data`` message in the messaging documentation for
87 more details about this message type.
86 more details about this message type.
88
87
89 The following MIME types are currently implemented:
88 The following MIME types are currently implemented:
90
89
91 * text/plain
90 * text/plain
92 * text/html
91 * text/html
93 * text/markdown
92 * text/markdown
94 * text/latex
93 * text/latex
95 * application/json
94 * application/json
96 * application/javascript
95 * application/javascript
97 * image/png
96 * image/png
98 * image/jpeg
97 * image/jpeg
99 * image/svg+xml
98 * image/svg+xml
100
99
101 Parameters
100 Parameters
102 ----------
101 ----------
103 data : dict
102 data : dict
104 A dictionary having keys that are valid MIME types (like
103 A dictionary having keys that are valid MIME types (like
105 'text/plain' or 'image/svg+xml') and values that are the data for
104 'text/plain' or 'image/svg+xml') and values that are the data for
106 that MIME type. The data itself must be a JSON'able data
105 that MIME type. The data itself must be a JSON'able data
107 structure. Minimally all data should have the 'text/plain' data,
106 structure. Minimally all data should have the 'text/plain' data,
108 which can be displayed by all frontends. If more than the plain
107 which can be displayed by all frontends. If more than the plain
109 text is given, it is up to the frontend to decide which
108 text is given, it is up to the frontend to decide which
110 representation to use.
109 representation to use.
111 metadata : dict
110 metadata : dict
112 A dictionary for metadata related to the data. This can contain
111 A dictionary for metadata related to the data. This can contain
113 arbitrary key, value pairs that frontends can use to interpret
112 arbitrary key, value pairs that frontends can use to interpret
114 the data. mime-type keys matching those in data can be used
113 the data. mime-type keys matching those in data can be used
115 to specify metadata about particular representations.
114 to specify metadata about particular representations.
116 source : str, deprecated
115 source : str, deprecated
117 Unused.
116 Unused.
118 transient : dict, keyword-only
117 transient : dict, keyword-only
119 A dictionary of transient data, such as display_id.
118 A dictionary of transient data, such as display_id.
120 """
119 """
121 from IPython.core.interactiveshell import InteractiveShell
120 from IPython.core.interactiveshell import InteractiveShell
122
121
123 display_pub = InteractiveShell.instance().display_pub
122 display_pub = InteractiveShell.instance().display_pub
124
123
125 # only pass transient if supplied,
124 # only pass transient if supplied,
126 # to avoid errors with older ipykernel.
125 # to avoid errors with older ipykernel.
127 # TODO: We could check for ipykernel version and provide a detailed upgrade message.
126 # TODO: We could check for ipykernel version and provide a detailed upgrade message.
128 if transient:
127 if transient:
129 kwargs['transient'] = transient
128 kwargs['transient'] = transient
130
129
131 display_pub.publish(
130 display_pub.publish(
132 data=data,
131 data=data,
133 metadata=metadata,
132 metadata=metadata,
134 **kwargs
133 **kwargs
135 )
134 )
136
135
137
136
138 def _new_id():
137 def _new_id():
139 """Generate a new random text id with urandom"""
138 """Generate a new random text id with urandom"""
140 return b2a_hex(os.urandom(16)).decode('ascii')
139 return b2a_hex(os.urandom(16)).decode('ascii')
141
140
142
141
143 def display(*objs, include=None, exclude=None, metadata=None, transient=None, display_id=None, **kwargs):
142 def display(*objs, include=None, exclude=None, metadata=None, transient=None, display_id=None, **kwargs):
144 """Display a Python object in all frontends.
143 """Display a Python object in all frontends.
145
144
146 By default all representations will be computed and sent to the frontends.
145 By default all representations will be computed and sent to the frontends.
147 Frontends can decide which representation is used and how.
146 Frontends can decide which representation is used and how.
148
147
149 Parameters
148 Parameters
150 ----------
149 ----------
151 objs : tuple of objects
150 objs : tuple of objects
152 The Python objects to display.
151 The Python objects to display.
153 raw : bool, optional
152 raw : bool, optional
154 Are the objects to be displayed already mimetype-keyed dicts of raw display data,
153 Are the objects to be displayed already mimetype-keyed dicts of raw display data,
155 or Python objects that need to be formatted before display? [default: False]
154 or Python objects that need to be formatted before display? [default: False]
156 include : list or tuple, optional
155 include : list or tuple, optional
157 A list of format type strings (MIME types) to include in the
156 A list of format type strings (MIME types) to include in the
158 format data dict. If this is set *only* the format types included
157 format data dict. If this is set *only* the format types included
159 in this list will be computed.
158 in this list will be computed.
160 exclude : list or tuple, optional
159 exclude : list or tuple, optional
161 A list of format type strings (MIME types) to exclude in the format
160 A list of format type strings (MIME types) to exclude in the format
162 data dict. If this is set all format types will be computed,
161 data dict. If this is set all format types will be computed,
163 except for those included in this argument.
162 except for those included in this argument.
164 metadata : dict, optional
163 metadata : dict, optional
165 A dictionary of metadata to associate with the output.
164 A dictionary of metadata to associate with the output.
166 mime-type keys in this dictionary will be associated with the individual
165 mime-type keys in this dictionary will be associated with the individual
167 representation formats, if they exist.
166 representation formats, if they exist.
168 transient : dict, optional
167 transient : dict, optional
169 A dictionary of transient data to associate with the output.
168 A dictionary of transient data to associate with the output.
170 Data in this dict should not be persisted to files (e.g. notebooks).
169 Data in this dict should not be persisted to files (e.g. notebooks).
171 display_id : str, optional
170 display_id : str, optional
172 Set an id for the display.
171 Set an id for the display.
173 This id can be used for updating this display area later via update_display.
172 This id can be used for updating this display area later via update_display.
174 If given as True, generate a new display_id
173 If given as True, generate a new display_id
175 kwargs: additional keyword-args, optional
174 kwargs: additional keyword-args, optional
176 Additional keyword-arguments are passed through to the display publisher.
175 Additional keyword-arguments are passed through to the display publisher.
177
176
178 Returns
177 Returns
179 -------
178 -------
180
179
181 handle: DisplayHandle
180 handle: DisplayHandle
182 Returns a handle on updatable displays, if display_id is given.
181 Returns a handle on updatable displays, if display_id is given.
183 Returns None if no display_id is given (default).
182 Returns None if no display_id is given (default).
184 """
183 """
185 raw = kwargs.pop('raw', False)
184 raw = kwargs.pop('raw', False)
186 if transient is None:
185 if transient is None:
187 transient = {}
186 transient = {}
188 if display_id:
187 if display_id:
189 if display_id == True:
188 if display_id == True:
190 display_id = _new_id()
189 display_id = _new_id()
191 transient['display_id'] = display_id
190 transient['display_id'] = display_id
192 if kwargs.get('update') and 'display_id' not in transient:
191 if kwargs.get('update') and 'display_id' not in transient:
193 raise TypeError('display_id required for update_display')
192 raise TypeError('display_id required for update_display')
194 if transient:
193 if transient:
195 kwargs['transient'] = transient
194 kwargs['transient'] = transient
196
195
197 from IPython.core.interactiveshell import InteractiveShell
196 from IPython.core.interactiveshell import InteractiveShell
198
197
199 if not raw:
198 if not raw:
200 format = InteractiveShell.instance().display_formatter.format
199 format = InteractiveShell.instance().display_formatter.format
201
200
202 for obj in objs:
201 for obj in objs:
203 if raw:
202 if raw:
204 publish_display_data(data=obj, metadata=metadata, **kwargs)
203 publish_display_data(data=obj, metadata=metadata, **kwargs)
205 else:
204 else:
206 format_dict, md_dict = format(obj, include=include, exclude=exclude)
205 format_dict, md_dict = format(obj, include=include, exclude=exclude)
207 if not format_dict:
206 if not format_dict:
208 # nothing to display (e.g. _ipython_display_ took over)
207 # nothing to display (e.g. _ipython_display_ took over)
209 continue
208 continue
210 if metadata:
209 if metadata:
211 # kwarg-specified metadata gets precedence
210 # kwarg-specified metadata gets precedence
212 _merge(md_dict, metadata)
211 _merge(md_dict, metadata)
213 publish_display_data(data=format_dict, metadata=md_dict, **kwargs)
212 publish_display_data(data=format_dict, metadata=md_dict, **kwargs)
214 if display_id:
213 if display_id:
215 return DisplayHandle(display_id)
214 return DisplayHandle(display_id)
216
215
217
216
218 # use * for keyword-only display_id arg
217 # use * for keyword-only display_id arg
219 def update_display(obj, *, display_id, **kwargs):
218 def update_display(obj, *, display_id, **kwargs):
220 """Update an existing display by id
219 """Update an existing display by id
221
220
222 Parameters
221 Parameters
223 ----------
222 ----------
224
223
225 obj:
224 obj:
226 The object with which to update the display
225 The object with which to update the display
227 display_id: keyword-only
226 display_id: keyword-only
228 The id of the display to update
227 The id of the display to update
229 """
228 """
230 kwargs['update'] = True
229 kwargs['update'] = True
231 display(obj, display_id=display_id, **kwargs)
230 display(obj, display_id=display_id, **kwargs)
232
231
233
232
234 class DisplayHandle(object):
233 class DisplayHandle(object):
235 """A handle on an updatable display
234 """A handle on an updatable display
236
235
237 Call .update(obj) to display a new object.
236 Call .update(obj) to display a new object.
238
237
239 Call .display(obj) to add a new instance of this display,
238 Call .display(obj) to add a new instance of this display,
240 and update existing instances.
239 and update existing instances.
241 """
240 """
242
241
243 def __init__(self, display_id=None):
242 def __init__(self, display_id=None):
244 if display_id is None:
243 if display_id is None:
245 display_id = _new_id()
244 display_id = _new_id()
246 self.display_id = display_id
245 self.display_id = display_id
247
246
248 def __repr__(self):
247 def __repr__(self):
249 return "<%s display_id=%s>" % (self.__class__.__name__, self.display_id)
248 return "<%s display_id=%s>" % (self.__class__.__name__, self.display_id)
250
249
251 def display(self, obj, **kwargs):
250 def display(self, obj, **kwargs):
252 """Make a new display with my id, updating existing instances.
251 """Make a new display with my id, updating existing instances.
253
252
254 Parameters
253 Parameters
255 ----------
254 ----------
256
255
257 obj:
256 obj:
258 object to display
257 object to display
259 **kwargs:
258 **kwargs:
260 additional keyword arguments passed to display
259 additional keyword arguments passed to display
261 """
260 """
262 display(obj, display_id=self.display_id, **kwargs)
261 display(obj, display_id=self.display_id, **kwargs)
263
262
264 def update(self, obj, **kwargs):
263 def update(self, obj, **kwargs):
265 """Update existing displays with my id
264 """Update existing displays with my id
266
265
267 Parameters
266 Parameters
268 ----------
267 ----------
269
268
270 obj:
269 obj:
271 object to display
270 object to display
272 **kwargs:
271 **kwargs:
273 additional keyword arguments passed to update_display
272 additional keyword arguments passed to update_display
274 """
273 """
275 update_display(obj, display_id=self.display_id, **kwargs)
274 update_display(obj, display_id=self.display_id, **kwargs)
276
275
277
276
278 def display_pretty(*objs, **kwargs):
277 def display_pretty(*objs, **kwargs):
279 """Display the pretty (default) representation of an object.
278 """Display the pretty (default) representation of an object.
280
279
281 Parameters
280 Parameters
282 ----------
281 ----------
283 objs : tuple of objects
282 objs : tuple of objects
284 The Python objects to display, or if raw=True raw text data to
283 The Python objects to display, or if raw=True raw text data to
285 display.
284 display.
286 raw : bool
285 raw : bool
287 Are the data objects raw data or Python objects that need to be
286 Are the data objects raw data or Python objects that need to be
288 formatted before display? [default: False]
287 formatted before display? [default: False]
289 metadata : dict (optional)
288 metadata : dict (optional)
290 Metadata to be associated with the specific mimetype output.
289 Metadata to be associated with the specific mimetype output.
291 """
290 """
292 _display_mimetype('text/plain', objs, **kwargs)
291 _display_mimetype('text/plain', objs, **kwargs)
293
292
294
293
295 def display_html(*objs, **kwargs):
294 def display_html(*objs, **kwargs):
296 """Display the HTML representation of an object.
295 """Display the HTML representation of an object.
297
296
298 Note: If raw=False and the object does not have a HTML
297 Note: If raw=False and the object does not have a HTML
299 representation, no HTML will be shown.
298 representation, no HTML will be shown.
300
299
301 Parameters
300 Parameters
302 ----------
301 ----------
303 objs : tuple of objects
302 objs : tuple of objects
304 The Python objects to display, or if raw=True raw HTML data to
303 The Python objects to display, or if raw=True raw HTML data to
305 display.
304 display.
306 raw : bool
305 raw : bool
307 Are the data objects raw data or Python objects that need to be
306 Are the data objects raw data or Python objects that need to be
308 formatted before display? [default: False]
307 formatted before display? [default: False]
309 metadata : dict (optional)
308 metadata : dict (optional)
310 Metadata to be associated with the specific mimetype output.
309 Metadata to be associated with the specific mimetype output.
311 """
310 """
312 _display_mimetype('text/html', objs, **kwargs)
311 _display_mimetype('text/html', objs, **kwargs)
313
312
314
313
315 def display_markdown(*objs, **kwargs):
314 def display_markdown(*objs, **kwargs):
316 """Displays the Markdown representation of an object.
315 """Displays the Markdown representation of an object.
317
316
318 Parameters
317 Parameters
319 ----------
318 ----------
320 objs : tuple of objects
319 objs : tuple of objects
321 The Python objects to display, or if raw=True raw markdown data to
320 The Python objects to display, or if raw=True raw markdown data to
322 display.
321 display.
323 raw : bool
322 raw : bool
324 Are the data objects raw data or Python objects that need to be
323 Are the data objects raw data or Python objects that need to be
325 formatted before display? [default: False]
324 formatted before display? [default: False]
326 metadata : dict (optional)
325 metadata : dict (optional)
327 Metadata to be associated with the specific mimetype output.
326 Metadata to be associated with the specific mimetype output.
328 """
327 """
329
328
330 _display_mimetype('text/markdown', objs, **kwargs)
329 _display_mimetype('text/markdown', objs, **kwargs)
331
330
332
331
333 def display_svg(*objs, **kwargs):
332 def display_svg(*objs, **kwargs):
334 """Display the SVG representation of an object.
333 """Display the SVG representation of an object.
335
334
336 Parameters
335 Parameters
337 ----------
336 ----------
338 objs : tuple of objects
337 objs : tuple of objects
339 The Python objects to display, or if raw=True raw svg data to
338 The Python objects to display, or if raw=True raw svg data to
340 display.
339 display.
341 raw : bool
340 raw : bool
342 Are the data objects raw data or Python objects that need to be
341 Are the data objects raw data or Python objects that need to be
343 formatted before display? [default: False]
342 formatted before display? [default: False]
344 metadata : dict (optional)
343 metadata : dict (optional)
345 Metadata to be associated with the specific mimetype output.
344 Metadata to be associated with the specific mimetype output.
346 """
345 """
347 _display_mimetype('image/svg+xml', objs, **kwargs)
346 _display_mimetype('image/svg+xml', objs, **kwargs)
348
347
349
348
350 def display_png(*objs, **kwargs):
349 def display_png(*objs, **kwargs):
351 """Display the PNG representation of an object.
350 """Display the PNG representation of an object.
352
351
353 Parameters
352 Parameters
354 ----------
353 ----------
355 objs : tuple of objects
354 objs : tuple of objects
356 The Python objects to display, or if raw=True raw png data to
355 The Python objects to display, or if raw=True raw png data to
357 display.
356 display.
358 raw : bool
357 raw : bool
359 Are the data objects raw data or Python objects that need to be
358 Are the data objects raw data or Python objects that need to be
360 formatted before display? [default: False]
359 formatted before display? [default: False]
361 metadata : dict (optional)
360 metadata : dict (optional)
362 Metadata to be associated with the specific mimetype output.
361 Metadata to be associated with the specific mimetype output.
363 """
362 """
364 _display_mimetype('image/png', objs, **kwargs)
363 _display_mimetype('image/png', objs, **kwargs)
365
364
366
365
367 def display_jpeg(*objs, **kwargs):
366 def display_jpeg(*objs, **kwargs):
368 """Display the JPEG representation of an object.
367 """Display the JPEG representation of an object.
369
368
370 Parameters
369 Parameters
371 ----------
370 ----------
372 objs : tuple of objects
371 objs : tuple of objects
373 The Python objects to display, or if raw=True raw JPEG data to
372 The Python objects to display, or if raw=True raw JPEG data to
374 display.
373 display.
375 raw : bool
374 raw : bool
376 Are the data objects raw data or Python objects that need to be
375 Are the data objects raw data or Python objects that need to be
377 formatted before display? [default: False]
376 formatted before display? [default: False]
378 metadata : dict (optional)
377 metadata : dict (optional)
379 Metadata to be associated with the specific mimetype output.
378 Metadata to be associated with the specific mimetype output.
380 """
379 """
381 _display_mimetype('image/jpeg', objs, **kwargs)
380 _display_mimetype('image/jpeg', objs, **kwargs)
382
381
383
382
384 def display_latex(*objs, **kwargs):
383 def display_latex(*objs, **kwargs):
385 """Display the LaTeX representation of an object.
384 """Display the LaTeX representation of an object.
386
385
387 Parameters
386 Parameters
388 ----------
387 ----------
389 objs : tuple of objects
388 objs : tuple of objects
390 The Python objects to display, or if raw=True raw latex data to
389 The Python objects to display, or if raw=True raw latex data to
391 display.
390 display.
392 raw : bool
391 raw : bool
393 Are the data objects raw data or Python objects that need to be
392 Are the data objects raw data or Python objects that need to be
394 formatted before display? [default: False]
393 formatted before display? [default: False]
395 metadata : dict (optional)
394 metadata : dict (optional)
396 Metadata to be associated with the specific mimetype output.
395 Metadata to be associated with the specific mimetype output.
397 """
396 """
398 _display_mimetype('text/latex', objs, **kwargs)
397 _display_mimetype('text/latex', objs, **kwargs)
399
398
400
399
401 def display_json(*objs, **kwargs):
400 def display_json(*objs, **kwargs):
402 """Display the JSON representation of an object.
401 """Display the JSON representation of an object.
403
402
404 Note that not many frontends support displaying JSON.
403 Note that not many frontends support displaying JSON.
405
404
406 Parameters
405 Parameters
407 ----------
406 ----------
408 objs : tuple of objects
407 objs : tuple of objects
409 The Python objects to display, or if raw=True raw json data to
408 The Python objects to display, or if raw=True raw json data to
410 display.
409 display.
411 raw : bool
410 raw : bool
412 Are the data objects raw data or Python objects that need to be
411 Are the data objects raw data or Python objects that need to be
413 formatted before display? [default: False]
412 formatted before display? [default: False]
414 metadata : dict (optional)
413 metadata : dict (optional)
415 Metadata to be associated with the specific mimetype output.
414 Metadata to be associated with the specific mimetype output.
416 """
415 """
417 _display_mimetype('application/json', objs, **kwargs)
416 _display_mimetype('application/json', objs, **kwargs)
418
417
419
418
420 def display_javascript(*objs, **kwargs):
419 def display_javascript(*objs, **kwargs):
421 """Display the Javascript representation of an object.
420 """Display the Javascript representation of an object.
422
421
423 Parameters
422 Parameters
424 ----------
423 ----------
425 objs : tuple of objects
424 objs : tuple of objects
426 The Python objects to display, or if raw=True raw javascript data to
425 The Python objects to display, or if raw=True raw javascript data to
427 display.
426 display.
428 raw : bool
427 raw : bool
429 Are the data objects raw data or Python objects that need to be
428 Are the data objects raw data or Python objects that need to be
430 formatted before display? [default: False]
429 formatted before display? [default: False]
431 metadata : dict (optional)
430 metadata : dict (optional)
432 Metadata to be associated with the specific mimetype output.
431 Metadata to be associated with the specific mimetype output.
433 """
432 """
434 _display_mimetype('application/javascript', objs, **kwargs)
433 _display_mimetype('application/javascript', objs, **kwargs)
435
434
436
435
437 def display_pdf(*objs, **kwargs):
436 def display_pdf(*objs, **kwargs):
438 """Display the PDF representation of an object.
437 """Display the PDF representation of an object.
439
438
440 Parameters
439 Parameters
441 ----------
440 ----------
442 objs : tuple of objects
441 objs : tuple of objects
443 The Python objects to display, or if raw=True raw javascript data to
442 The Python objects to display, or if raw=True raw javascript data to
444 display.
443 display.
445 raw : bool
444 raw : bool
446 Are the data objects raw data or Python objects that need to be
445 Are the data objects raw data or Python objects that need to be
447 formatted before display? [default: False]
446 formatted before display? [default: False]
448 metadata : dict (optional)
447 metadata : dict (optional)
449 Metadata to be associated with the specific mimetype output.
448 Metadata to be associated with the specific mimetype output.
450 """
449 """
451 _display_mimetype('application/pdf', objs, **kwargs)
450 _display_mimetype('application/pdf', objs, **kwargs)
452
451
453
452
454 #-----------------------------------------------------------------------------
453 #-----------------------------------------------------------------------------
455 # Smart classes
454 # Smart classes
456 #-----------------------------------------------------------------------------
455 #-----------------------------------------------------------------------------
457
456
458
457
459 class DisplayObject(object):
458 class DisplayObject(object):
460 """An object that wraps data to be displayed."""
459 """An object that wraps data to be displayed."""
461
460
462 _read_flags = 'r'
461 _read_flags = 'r'
463 _show_mem_addr = False
462 _show_mem_addr = False
464
463
465 def __init__(self, data=None, url=None, filename=None):
464 def __init__(self, data=None, url=None, filename=None):
466 """Create a display object given raw data.
465 """Create a display object given raw data.
467
466
468 When this object is returned by an expression or passed to the
467 When this object is returned by an expression or passed to the
469 display function, it will result in the data being displayed
468 display function, it will result in the data being displayed
470 in the frontend. The MIME type of the data should match the
469 in the frontend. The MIME type of the data should match the
471 subclasses used, so the Png subclass should be used for 'image/png'
470 subclasses used, so the Png subclass should be used for 'image/png'
472 data. If the data is a URL, the data will first be downloaded
471 data. If the data is a URL, the data will first be downloaded
473 and then displayed. If
472 and then displayed. If
474
473
475 Parameters
474 Parameters
476 ----------
475 ----------
477 data : unicode, str or bytes
476 data : unicode, str or bytes
478 The raw data or a URL or file to load the data from
477 The raw data or a URL or file to load the data from
479 url : unicode
478 url : unicode
480 A URL to download the data from.
479 A URL to download the data from.
481 filename : unicode
480 filename : unicode
482 Path to a local file to load the data from.
481 Path to a local file to load the data from.
483 """
482 """
484 if data is not None and isinstance(data, string_types):
483 if data is not None and isinstance(data, str):
485 if data.startswith('http') and url is None:
484 if data.startswith('http') and url is None:
486 url = data
485 url = data
487 filename = None
486 filename = None
488 data = None
487 data = None
489 elif _safe_exists(data) and filename is None:
488 elif _safe_exists(data) and filename is None:
490 url = None
489 url = None
491 filename = data
490 filename = data
492 data = None
491 data = None
493
492
494 self.data = data
493 self.data = data
495 self.url = url
494 self.url = url
496 self.filename = None if filename is None else unicode_type(filename)
495 self.filename = filename
497
496
498 self.reload()
497 self.reload()
499 self._check_data()
498 self._check_data()
500
499
501 def __repr__(self):
500 def __repr__(self):
502 if not self._show_mem_addr:
501 if not self._show_mem_addr:
503 cls = self.__class__
502 cls = self.__class__
504 r = "<%s.%s object>" % (cls.__module__, cls.__name__)
503 r = "<%s.%s object>" % (cls.__module__, cls.__name__)
505 else:
504 else:
506 r = super(DisplayObject, self).__repr__()
505 r = super(DisplayObject, self).__repr__()
507 return r
506 return r
508
507
509 def _check_data(self):
508 def _check_data(self):
510 """Override in subclasses if there's something to check."""
509 """Override in subclasses if there's something to check."""
511 pass
510 pass
512
511
513 def reload(self):
512 def reload(self):
514 """Reload the raw data from file or URL."""
513 """Reload the raw data from file or URL."""
515 if self.filename is not None:
514 if self.filename is not None:
516 with open(self.filename, self._read_flags) as f:
515 with open(self.filename, self._read_flags) as f:
517 self.data = f.read()
516 self.data = f.read()
518 elif self.url is not None:
517 elif self.url is not None:
519 try:
518 try:
520 try:
519 try:
521 from urllib.request import urlopen # Py3
520 from urllib.request import urlopen # Py3
522 except ImportError:
521 except ImportError:
523 from urllib2 import urlopen
522 from urllib2 import urlopen
524 response = urlopen(self.url)
523 response = urlopen(self.url)
525 self.data = response.read()
524 self.data = response.read()
526 # extract encoding from header, if there is one:
525 # extract encoding from header, if there is one:
527 encoding = None
526 encoding = None
528 for sub in response.headers['content-type'].split(';'):
527 for sub in response.headers['content-type'].split(';'):
529 sub = sub.strip()
528 sub = sub.strip()
530 if sub.startswith('charset'):
529 if sub.startswith('charset'):
531 encoding = sub.split('=')[-1].strip()
530 encoding = sub.split('=')[-1].strip()
532 break
531 break
533 # decode data, if an encoding was specified
532 # decode data, if an encoding was specified
534 if encoding:
533 if encoding:
535 self.data = self.data.decode(encoding, 'replace')
534 self.data = self.data.decode(encoding, 'replace')
536 except:
535 except:
537 self.data = None
536 self.data = None
538
537
539 class TextDisplayObject(DisplayObject):
538 class TextDisplayObject(DisplayObject):
540 """Validate that display data is text"""
539 """Validate that display data is text"""
541 def _check_data(self):
540 def _check_data(self):
542 if self.data is not None and not isinstance(self.data, string_types):
541 if self.data is not None and not isinstance(self.data, str):
543 raise TypeError("%s expects text, not %r" % (self.__class__.__name__, self.data))
542 raise TypeError("%s expects text, not %r" % (self.__class__.__name__, self.data))
544
543
545 class Pretty(TextDisplayObject):
544 class Pretty(TextDisplayObject):
546
545
547 def _repr_pretty_(self):
546 def _repr_pretty_(self):
548 return self.data
547 return self.data
549
548
550
549
551 class HTML(TextDisplayObject):
550 class HTML(TextDisplayObject):
552
551
553 def _repr_html_(self):
552 def _repr_html_(self):
554 return self.data
553 return self.data
555
554
556 def __html__(self):
555 def __html__(self):
557 """
556 """
558 This method exists to inform other HTML-using modules (e.g. Markupsafe,
557 This method exists to inform other HTML-using modules (e.g. Markupsafe,
559 htmltag, etc) that this object is HTML and does not need things like
558 htmltag, etc) that this object is HTML and does not need things like
560 special characters (<>&) escaped.
559 special characters (<>&) escaped.
561 """
560 """
562 return self._repr_html_()
561 return self._repr_html_()
563
562
564
563
565 class Markdown(TextDisplayObject):
564 class Markdown(TextDisplayObject):
566
565
567 def _repr_markdown_(self):
566 def _repr_markdown_(self):
568 return self.data
567 return self.data
569
568
570
569
571 class Math(TextDisplayObject):
570 class Math(TextDisplayObject):
572
571
573 def _repr_latex_(self):
572 def _repr_latex_(self):
574 s = self.data.strip('$')
573 s = self.data.strip('$')
575 return "$$%s$$" % s
574 return "$$%s$$" % s
576
575
577
576
578 class Latex(TextDisplayObject):
577 class Latex(TextDisplayObject):
579
578
580 def _repr_latex_(self):
579 def _repr_latex_(self):
581 return self.data
580 return self.data
582
581
583
582
584 class SVG(DisplayObject):
583 class SVG(DisplayObject):
585
584
586 _read_flags = 'rb'
585 _read_flags = 'rb'
587 # wrap data in a property, which extracts the <svg> tag, discarding
586 # wrap data in a property, which extracts the <svg> tag, discarding
588 # document headers
587 # document headers
589 _data = None
588 _data = None
590
589
591 @property
590 @property
592 def data(self):
591 def data(self):
593 return self._data
592 return self._data
594
593
595 @data.setter
594 @data.setter
596 def data(self, svg):
595 def data(self, svg):
597 if svg is None:
596 if svg is None:
598 self._data = None
597 self._data = None
599 return
598 return
600 # parse into dom object
599 # parse into dom object
601 from xml.dom import minidom
600 from xml.dom import minidom
602 svg = cast_bytes_py2(svg)
601 svg = cast_bytes_py2(svg)
603 x = minidom.parseString(svg)
602 x = minidom.parseString(svg)
604 # get svg tag (should be 1)
603 # get svg tag (should be 1)
605 found_svg = x.getElementsByTagName('svg')
604 found_svg = x.getElementsByTagName('svg')
606 if found_svg:
605 if found_svg:
607 svg = found_svg[0].toxml()
606 svg = found_svg[0].toxml()
608 else:
607 else:
609 # fallback on the input, trust the user
608 # fallback on the input, trust the user
610 # but this is probably an error.
609 # but this is probably an error.
611 pass
610 pass
612 svg = cast_unicode(svg)
611 svg = cast_unicode(svg)
613 self._data = svg
612 self._data = svg
614
613
615 def _repr_svg_(self):
614 def _repr_svg_(self):
616 return self.data
615 return self.data
617
616
618
617
619 class JSON(DisplayObject):
618 class JSON(DisplayObject):
620 """JSON expects a JSON-able dict or list
619 """JSON expects a JSON-able dict or list
621
620
622 not an already-serialized JSON string.
621 not an already-serialized JSON string.
623
622
624 Scalar types (None, number, string) are not allowed, only dict or list containers.
623 Scalar types (None, number, string) are not allowed, only dict or list containers.
625 """
624 """
626 # wrap data in a property, which warns about passing already-serialized JSON
625 # wrap data in a property, which warns about passing already-serialized JSON
627 _data = None
626 _data = None
628 def __init__(self, data=None, url=None, filename=None, expanded=False, metadata=None):
627 def __init__(self, data=None, url=None, filename=None, expanded=False, metadata=None):
629 """Create a JSON display object given raw data.
628 """Create a JSON display object given raw data.
630
629
631 Parameters
630 Parameters
632 ----------
631 ----------
633 data : dict or list
632 data : dict or list
634 JSON data to display. Not an already-serialized JSON string.
633 JSON data to display. Not an already-serialized JSON string.
635 Scalar types (None, number, string) are not allowed, only dict
634 Scalar types (None, number, string) are not allowed, only dict
636 or list containers.
635 or list containers.
637 url : unicode
636 url : unicode
638 A URL to download the data from.
637 A URL to download the data from.
639 filename : unicode
638 filename : unicode
640 Path to a local file to load the data from.
639 Path to a local file to load the data from.
641 expanded : boolean
640 expanded : boolean
642 Metadata to control whether a JSON display component is expanded.
641 Metadata to control whether a JSON display component is expanded.
643 metadata: dict
642 metadata: dict
644 Specify extra metadata to attach to the json display object.
643 Specify extra metadata to attach to the json display object.
645 """
644 """
646 self.expanded = expanded
645 self.expanded = expanded
647 self.metadata = metadata
646 self.metadata = metadata
648 super(JSON, self).__init__(data=data, url=url, filename=filename)
647 super(JSON, self).__init__(data=data, url=url, filename=filename)
649
648
650 def _check_data(self):
649 def _check_data(self):
651 if self.data is not None and not isinstance(self.data, (dict, list)):
650 if self.data is not None and not isinstance(self.data, (dict, list)):
652 raise TypeError("%s expects JSONable dict or list, not %r" % (self.__class__.__name__, self.data))
651 raise TypeError("%s expects JSONable dict or list, not %r" % (self.__class__.__name__, self.data))
653
652
654 @property
653 @property
655 def data(self):
654 def data(self):
656 return self._data
655 return self._data
657
656
658 @data.setter
657 @data.setter
659 def data(self, data):
658 def data(self, data):
660 if isinstance(data, string_types):
659 if isinstance(data, str):
661 warnings.warn("JSON expects JSONable dict or list, not JSON strings")
660 warnings.warn("JSON expects JSONable dict or list, not JSON strings")
662 data = json.loads(data)
661 data = json.loads(data)
663 self._data = data
662 self._data = data
664
663
665 def _data_and_metadata(self):
664 def _data_and_metadata(self):
666 md = {'expanded': self.expanded}
665 md = {'expanded': self.expanded}
667 if self.metadata:
666 if self.metadata:
668 md.update(self.metadata)
667 md.update(self.metadata)
669 return self.data, md
668 return self.data, md
670
669
671 def _repr_json_(self):
670 def _repr_json_(self):
672 return self._data_and_metadata()
671 return self._data_and_metadata()
673
672
674 css_t = """$("head").append($("<link/>").attr({
673 css_t = """$("head").append($("<link/>").attr({
675 rel: "stylesheet",
674 rel: "stylesheet",
676 type: "text/css",
675 type: "text/css",
677 href: "%s"
676 href: "%s"
678 }));
677 }));
679 """
678 """
680
679
681 lib_t1 = """$.getScript("%s", function () {
680 lib_t1 = """$.getScript("%s", function () {
682 """
681 """
683 lib_t2 = """});
682 lib_t2 = """});
684 """
683 """
685
684
686 class Javascript(TextDisplayObject):
685 class Javascript(TextDisplayObject):
687
686
688 def __init__(self, data=None, url=None, filename=None, lib=None, css=None):
687 def __init__(self, data=None, url=None, filename=None, lib=None, css=None):
689 """Create a Javascript display object given raw data.
688 """Create a Javascript display object given raw data.
690
689
691 When this object is returned by an expression or passed to the
690 When this object is returned by an expression or passed to the
692 display function, it will result in the data being displayed
691 display function, it will result in the data being displayed
693 in the frontend. If the data is a URL, the data will first be
692 in the frontend. If the data is a URL, the data will first be
694 downloaded and then displayed.
693 downloaded and then displayed.
695
694
696 In the Notebook, the containing element will be available as `element`,
695 In the Notebook, the containing element will be available as `element`,
697 and jQuery will be available. Content appended to `element` will be
696 and jQuery will be available. Content appended to `element` will be
698 visible in the output area.
697 visible in the output area.
699
698
700 Parameters
699 Parameters
701 ----------
700 ----------
702 data : unicode, str or bytes
701 data : unicode, str or bytes
703 The Javascript source code or a URL to download it from.
702 The Javascript source code or a URL to download it from.
704 url : unicode
703 url : unicode
705 A URL to download the data from.
704 A URL to download the data from.
706 filename : unicode
705 filename : unicode
707 Path to a local file to load the data from.
706 Path to a local file to load the data from.
708 lib : list or str
707 lib : list or str
709 A sequence of Javascript library URLs to load asynchronously before
708 A sequence of Javascript library URLs to load asynchronously before
710 running the source code. The full URLs of the libraries should
709 running the source code. The full URLs of the libraries should
711 be given. A single Javascript library URL can also be given as a
710 be given. A single Javascript library URL can also be given as a
712 string.
711 string.
713 css: : list or str
712 css: : list or str
714 A sequence of css files to load before running the source code.
713 A sequence of css files to load before running the source code.
715 The full URLs of the css files should be given. A single css URL
714 The full URLs of the css files should be given. A single css URL
716 can also be given as a string.
715 can also be given as a string.
717 """
716 """
718 if isinstance(lib, string_types):
717 if isinstance(lib, str):
719 lib = [lib]
718 lib = [lib]
720 elif lib is None:
719 elif lib is None:
721 lib = []
720 lib = []
722 if isinstance(css, string_types):
721 if isinstance(css, str):
723 css = [css]
722 css = [css]
724 elif css is None:
723 elif css is None:
725 css = []
724 css = []
726 if not isinstance(lib, (list,tuple)):
725 if not isinstance(lib, (list,tuple)):
727 raise TypeError('expected sequence, got: %r' % lib)
726 raise TypeError('expected sequence, got: %r' % lib)
728 if not isinstance(css, (list,tuple)):
727 if not isinstance(css, (list,tuple)):
729 raise TypeError('expected sequence, got: %r' % css)
728 raise TypeError('expected sequence, got: %r' % css)
730 self.lib = lib
729 self.lib = lib
731 self.css = css
730 self.css = css
732 super(Javascript, self).__init__(data=data, url=url, filename=filename)
731 super(Javascript, self).__init__(data=data, url=url, filename=filename)
733
732
734 def _repr_javascript_(self):
733 def _repr_javascript_(self):
735 r = ''
734 r = ''
736 for c in self.css:
735 for c in self.css:
737 r += css_t % c
736 r += css_t % c
738 for l in self.lib:
737 for l in self.lib:
739 r += lib_t1 % l
738 r += lib_t1 % l
740 r += self.data
739 r += self.data
741 r += lib_t2*len(self.lib)
740 r += lib_t2*len(self.lib)
742 return r
741 return r
743
742
744 # constants for identifying png/jpeg data
743 # constants for identifying png/jpeg data
745 _PNG = b'\x89PNG\r\n\x1a\n'
744 _PNG = b'\x89PNG\r\n\x1a\n'
746 _JPEG = b'\xff\xd8'
745 _JPEG = b'\xff\xd8'
747
746
748 def _pngxy(data):
747 def _pngxy(data):
749 """read the (width, height) from a PNG header"""
748 """read the (width, height) from a PNG header"""
750 ihdr = data.index(b'IHDR')
749 ihdr = data.index(b'IHDR')
751 # next 8 bytes are width/height
750 # next 8 bytes are width/height
752 w4h4 = data[ihdr+4:ihdr+12]
751 w4h4 = data[ihdr+4:ihdr+12]
753 return struct.unpack('>ii', w4h4)
752 return struct.unpack('>ii', w4h4)
754
753
755 def _jpegxy(data):
754 def _jpegxy(data):
756 """read the (width, height) from a JPEG header"""
755 """read the (width, height) from a JPEG header"""
757 # adapted from http://www.64lines.com/jpeg-width-height
756 # adapted from http://www.64lines.com/jpeg-width-height
758
757
759 idx = 4
758 idx = 4
760 while True:
759 while True:
761 block_size = struct.unpack('>H', data[idx:idx+2])[0]
760 block_size = struct.unpack('>H', data[idx:idx+2])[0]
762 idx = idx + block_size
761 idx = idx + block_size
763 if data[idx:idx+2] == b'\xFF\xC0':
762 if data[idx:idx+2] == b'\xFF\xC0':
764 # found Start of Frame
763 # found Start of Frame
765 iSOF = idx
764 iSOF = idx
766 break
765 break
767 else:
766 else:
768 # read another block
767 # read another block
769 idx += 2
768 idx += 2
770
769
771 h, w = struct.unpack('>HH', data[iSOF+5:iSOF+9])
770 h, w = struct.unpack('>HH', data[iSOF+5:iSOF+9])
772 return w, h
771 return w, h
773
772
774 class Image(DisplayObject):
773 class Image(DisplayObject):
775
774
776 _read_flags = 'rb'
775 _read_flags = 'rb'
777 _FMT_JPEG = u'jpeg'
776 _FMT_JPEG = u'jpeg'
778 _FMT_PNG = u'png'
777 _FMT_PNG = u'png'
779 _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG]
778 _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG]
780
779
781 def __init__(self, data=None, url=None, filename=None, format=None,
780 def __init__(self, data=None, url=None, filename=None, format=None,
782 embed=None, width=None, height=None, retina=False,
781 embed=None, width=None, height=None, retina=False,
783 unconfined=False, metadata=None):
782 unconfined=False, metadata=None):
784 """Create a PNG/JPEG image object given raw data.
783 """Create a PNG/JPEG image object given raw data.
785
784
786 When this object is returned by an input cell or passed to the
785 When this object is returned by an input cell or passed to the
787 display function, it will result in the image being displayed
786 display function, it will result in the image being displayed
788 in the frontend.
787 in the frontend.
789
788
790 Parameters
789 Parameters
791 ----------
790 ----------
792 data : unicode, str or bytes
791 data : unicode, str or bytes
793 The raw image data or a URL or filename to load the data from.
792 The raw image data or a URL or filename to load the data from.
794 This always results in embedded image data.
793 This always results in embedded image data.
795 url : unicode
794 url : unicode
796 A URL to download the data from. If you specify `url=`,
795 A URL to download the data from. If you specify `url=`,
797 the image data will not be embedded unless you also specify `embed=True`.
796 the image data will not be embedded unless you also specify `embed=True`.
798 filename : unicode
797 filename : unicode
799 Path to a local file to load the data from.
798 Path to a local file to load the data from.
800 Images from a file are always embedded.
799 Images from a file are always embedded.
801 format : unicode
800 format : unicode
802 The format of the image data (png/jpeg/jpg). If a filename or URL is given
801 The format of the image data (png/jpeg/jpg). If a filename or URL is given
803 for format will be inferred from the filename extension.
802 for format will be inferred from the filename extension.
804 embed : bool
803 embed : bool
805 Should the image data be embedded using a data URI (True) or be
804 Should the image data be embedded using a data URI (True) or be
806 loaded using an <img> tag. Set this to True if you want the image
805 loaded using an <img> tag. Set this to True if you want the image
807 to be viewable later with no internet connection in the notebook.
806 to be viewable later with no internet connection in the notebook.
808
807
809 Default is `True`, unless the keyword argument `url` is set, then
808 Default is `True`, unless the keyword argument `url` is set, then
810 default value is `False`.
809 default value is `False`.
811
810
812 Note that QtConsole is not able to display images if `embed` is set to `False`
811 Note that QtConsole is not able to display images if `embed` is set to `False`
813 width : int
812 width : int
814 Width in pixels to which to constrain the image in html
813 Width in pixels to which to constrain the image in html
815 height : int
814 height : int
816 Height in pixels to which to constrain the image in html
815 Height in pixels to which to constrain the image in html
817 retina : bool
816 retina : bool
818 Automatically set the width and height to half of the measured
817 Automatically set the width and height to half of the measured
819 width and height.
818 width and height.
820 This only works for embedded images because it reads the width/height
819 This only works for embedded images because it reads the width/height
821 from image data.
820 from image data.
822 For non-embedded images, you can just set the desired display width
821 For non-embedded images, you can just set the desired display width
823 and height directly.
822 and height directly.
824 unconfined: bool
823 unconfined: bool
825 Set unconfined=True to disable max-width confinement of the image.
824 Set unconfined=True to disable max-width confinement of the image.
826 metadata: dict
825 metadata: dict
827 Specify extra metadata to attach to the image.
826 Specify extra metadata to attach to the image.
828
827
829 Examples
828 Examples
830 --------
829 --------
831 # embedded image data, works in qtconsole and notebook
830 # embedded image data, works in qtconsole and notebook
832 # when passed positionally, the first arg can be any of raw image data,
831 # when passed positionally, the first arg can be any of raw image data,
833 # a URL, or a filename from which to load image data.
832 # a URL, or a filename from which to load image data.
834 # The result is always embedding image data for inline images.
833 # The result is always embedding image data for inline images.
835 Image('http://www.google.fr/images/srpr/logo3w.png')
834 Image('http://www.google.fr/images/srpr/logo3w.png')
836 Image('/path/to/image.jpg')
835 Image('/path/to/image.jpg')
837 Image(b'RAW_PNG_DATA...')
836 Image(b'RAW_PNG_DATA...')
838
837
839 # Specifying Image(url=...) does not embed the image data,
838 # Specifying Image(url=...) does not embed the image data,
840 # it only generates `<img>` tag with a link to the source.
839 # it only generates `<img>` tag with a link to the source.
841 # This will not work in the qtconsole or offline.
840 # This will not work in the qtconsole or offline.
842 Image(url='http://www.google.fr/images/srpr/logo3w.png')
841 Image(url='http://www.google.fr/images/srpr/logo3w.png')
843
842
844 """
843 """
845 if filename is not None:
844 if filename is not None:
846 ext = self._find_ext(filename)
845 ext = self._find_ext(filename)
847 elif url is not None:
846 elif url is not None:
848 ext = self._find_ext(url)
847 ext = self._find_ext(url)
849 elif data is None:
848 elif data is None:
850 raise ValueError("No image data found. Expecting filename, url, or data.")
849 raise ValueError("No image data found. Expecting filename, url, or data.")
851 elif isinstance(data, string_types) and (
850 elif isinstance(data, str) and (
852 data.startswith('http') or _safe_exists(data)
851 data.startswith('http') or _safe_exists(data)
853 ):
852 ):
854 ext = self._find_ext(data)
853 ext = self._find_ext(data)
855 else:
854 else:
856 ext = None
855 ext = None
857
856
858 if format is None:
857 if format is None:
859 if ext is not None:
858 if ext is not None:
860 if ext == u'jpg' or ext == u'jpeg':
859 if ext == u'jpg' or ext == u'jpeg':
861 format = self._FMT_JPEG
860 format = self._FMT_JPEG
862 if ext == u'png':
861 if ext == u'png':
863 format = self._FMT_PNG
862 format = self._FMT_PNG
864 else:
863 else:
865 format = ext.lower()
864 format = ext.lower()
866 elif isinstance(data, bytes):
865 elif isinstance(data, bytes):
867 # infer image type from image data header,
866 # infer image type from image data header,
868 # only if format has not been specified.
867 # only if format has not been specified.
869 if data[:2] == _JPEG:
868 if data[:2] == _JPEG:
870 format = self._FMT_JPEG
869 format = self._FMT_JPEG
871
870
872 # failed to detect format, default png
871 # failed to detect format, default png
873 if format is None:
872 if format is None:
874 format = 'png'
873 format = 'png'
875
874
876 if format.lower() == 'jpg':
875 if format.lower() == 'jpg':
877 # jpg->jpeg
876 # jpg->jpeg
878 format = self._FMT_JPEG
877 format = self._FMT_JPEG
879
878
880 self.format = unicode_type(format).lower()
879 self.format = format.lower()
881 self.embed = embed if embed is not None else (url is None)
880 self.embed = embed if embed is not None else (url is None)
882
881
883 if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS:
882 if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS:
884 raise ValueError("Cannot embed the '%s' image format" % (self.format))
883 raise ValueError("Cannot embed the '%s' image format" % (self.format))
885 self.width = width
884 self.width = width
886 self.height = height
885 self.height = height
887 self.retina = retina
886 self.retina = retina
888 self.unconfined = unconfined
887 self.unconfined = unconfined
889 self.metadata = metadata
888 self.metadata = metadata
890 super(Image, self).__init__(data=data, url=url, filename=filename)
889 super(Image, self).__init__(data=data, url=url, filename=filename)
891
890
892 if retina:
891 if retina:
893 self._retina_shape()
892 self._retina_shape()
894
893
895 def _retina_shape(self):
894 def _retina_shape(self):
896 """load pixel-doubled width and height from image data"""
895 """load pixel-doubled width and height from image data"""
897 if not self.embed:
896 if not self.embed:
898 return
897 return
899 if self.format == 'png':
898 if self.format == 'png':
900 w, h = _pngxy(self.data)
899 w, h = _pngxy(self.data)
901 elif self.format == 'jpeg':
900 elif self.format == 'jpeg':
902 w, h = _jpegxy(self.data)
901 w, h = _jpegxy(self.data)
903 else:
902 else:
904 # retina only supports png
903 # retina only supports png
905 return
904 return
906 self.width = w // 2
905 self.width = w // 2
907 self.height = h // 2
906 self.height = h // 2
908
907
909 def reload(self):
908 def reload(self):
910 """Reload the raw data from file or URL."""
909 """Reload the raw data from file or URL."""
911 if self.embed:
910 if self.embed:
912 super(Image,self).reload()
911 super(Image,self).reload()
913 if self.retina:
912 if self.retina:
914 self._retina_shape()
913 self._retina_shape()
915
914
916 def _repr_html_(self):
915 def _repr_html_(self):
917 if not self.embed:
916 if not self.embed:
918 width = height = klass = ''
917 width = height = klass = ''
919 if self.width:
918 if self.width:
920 width = ' width="%d"' % self.width
919 width = ' width="%d"' % self.width
921 if self.height:
920 if self.height:
922 height = ' height="%d"' % self.height
921 height = ' height="%d"' % self.height
923 if self.unconfined:
922 if self.unconfined:
924 klass = ' class="unconfined"'
923 klass = ' class="unconfined"'
925 return u'<img src="{url}"{width}{height}{klass}/>'.format(
924 return u'<img src="{url}"{width}{height}{klass}/>'.format(
926 url=self.url,
925 url=self.url,
927 width=width,
926 width=width,
928 height=height,
927 height=height,
929 klass=klass,
928 klass=klass,
930 )
929 )
931
930
932 def _data_and_metadata(self):
931 def _data_and_metadata(self):
933 """shortcut for returning metadata with shape information, if defined"""
932 """shortcut for returning metadata with shape information, if defined"""
934 md = {}
933 md = {}
935 if self.width:
934 if self.width:
936 md['width'] = self.width
935 md['width'] = self.width
937 if self.height:
936 if self.height:
938 md['height'] = self.height
937 md['height'] = self.height
939 if self.unconfined:
938 if self.unconfined:
940 md['unconfined'] = self.unconfined
939 md['unconfined'] = self.unconfined
941 if self.metadata:
940 if self.metadata:
942 md.update(self.metadata)
941 md.update(self.metadata)
943 if md:
942 if md:
944 return self.data, md
943 return self.data, md
945 else:
944 else:
946 return self.data
945 return self.data
947
946
948 def _repr_png_(self):
947 def _repr_png_(self):
949 if self.embed and self.format == u'png':
948 if self.embed and self.format == u'png':
950 return self._data_and_metadata()
949 return self._data_and_metadata()
951
950
952 def _repr_jpeg_(self):
951 def _repr_jpeg_(self):
953 if self.embed and (self.format == u'jpeg' or self.format == u'jpg'):
952 if self.embed and (self.format == u'jpeg' or self.format == u'jpg'):
954 return self._data_and_metadata()
953 return self._data_and_metadata()
955
954
956 def _find_ext(self, s):
955 def _find_ext(self, s):
957 return unicode_type(s.split('.')[-1].lower())
956 return s.split('.')[-1].lower()
958
957
959 class Video(DisplayObject):
958 class Video(DisplayObject):
960
959
961 def __init__(self, data=None, url=None, filename=None, embed=False, mimetype=None):
960 def __init__(self, data=None, url=None, filename=None, embed=False, mimetype=None):
962 """Create a video object given raw data or an URL.
961 """Create a video object given raw data or an URL.
963
962
964 When this object is returned by an input cell or passed to the
963 When this object is returned by an input cell or passed to the
965 display function, it will result in the video being displayed
964 display function, it will result in the video being displayed
966 in the frontend.
965 in the frontend.
967
966
968 Parameters
967 Parameters
969 ----------
968 ----------
970 data : unicode, str or bytes
969 data : unicode, str or bytes
971 The raw video data or a URL or filename to load the data from.
970 The raw video data or a URL or filename to load the data from.
972 Raw data will require passing `embed=True`.
971 Raw data will require passing `embed=True`.
973 url : unicode
972 url : unicode
974 A URL for the video. If you specify `url=`,
973 A URL for the video. If you specify `url=`,
975 the image data will not be embedded.
974 the image data will not be embedded.
976 filename : unicode
975 filename : unicode
977 Path to a local file containing the video.
976 Path to a local file containing the video.
978 Will be interpreted as a local URL unless `embed=True`.
977 Will be interpreted as a local URL unless `embed=True`.
979 embed : bool
978 embed : bool
980 Should the video be embedded using a data URI (True) or be
979 Should the video be embedded using a data URI (True) or be
981 loaded using a <video> tag (False).
980 loaded using a <video> tag (False).
982
981
983 Since videos are large, embedding them should be avoided, if possible.
982 Since videos are large, embedding them should be avoided, if possible.
984 You must confirm embedding as your intention by passing `embed=True`.
983 You must confirm embedding as your intention by passing `embed=True`.
985
984
986 Local files can be displayed with URLs without embedding the content, via::
985 Local files can be displayed with URLs without embedding the content, via::
987
986
988 Video('./video.mp4')
987 Video('./video.mp4')
989
988
990 mimetype: unicode
989 mimetype: unicode
991 Specify the mimetype for embedded videos.
990 Specify the mimetype for embedded videos.
992 Default will be guessed from file extension, if available.
991 Default will be guessed from file extension, if available.
993
992
994 Examples
993 Examples
995 --------
994 --------
996
995
997 Video('https://archive.org/download/Sita_Sings_the_Blues/Sita_Sings_the_Blues_small.mp4')
996 Video('https://archive.org/download/Sita_Sings_the_Blues/Sita_Sings_the_Blues_small.mp4')
998 Video('path/to/video.mp4')
997 Video('path/to/video.mp4')
999 Video('path/to/video.mp4', embed=True)
998 Video('path/to/video.mp4', embed=True)
1000 Video(b'raw-videodata', embed=True)
999 Video(b'raw-videodata', embed=True)
1001 """
1000 """
1002 if url is None and isinstance(data, string_types) and data.startswith(('http:', 'https:')):
1001 if url is None and isinstance(data, str) and data.startswith(('http:', 'https:')):
1003 url = data
1002 url = data
1004 data = None
1003 data = None
1005 elif os.path.exists(data):
1004 elif os.path.exists(data):
1006 filename = data
1005 filename = data
1007 data = None
1006 data = None
1008
1007
1009 if data and not embed:
1008 if data and not embed:
1010 msg = ''.join([
1009 msg = ''.join([
1011 "To embed videos, you must pass embed=True ",
1010 "To embed videos, you must pass embed=True ",
1012 "(this may make your notebook files huge)\n",
1011 "(this may make your notebook files huge)\n",
1013 "Consider passing Video(url='...')",
1012 "Consider passing Video(url='...')",
1014 ])
1013 ])
1015 raise ValueError(msg)
1014 raise ValueError(msg)
1016
1015
1017 self.mimetype = mimetype
1016 self.mimetype = mimetype
1018 self.embed = embed
1017 self.embed = embed
1019 super(Video, self).__init__(data=data, url=url, filename=filename)
1018 super(Video, self).__init__(data=data, url=url, filename=filename)
1020
1019
1021 def _repr_html_(self):
1020 def _repr_html_(self):
1022 # External URLs and potentially local files are not embedded into the
1021 # External URLs and potentially local files are not embedded into the
1023 # notebook output.
1022 # notebook output.
1024 if not self.embed:
1023 if not self.embed:
1025 url = self.url if self.url is not None else self.filename
1024 url = self.url if self.url is not None else self.filename
1026 output = """<video src="{0}" controls>
1025 output = """<video src="{0}" controls>
1027 Your browser does not support the <code>video</code> element.
1026 Your browser does not support the <code>video</code> element.
1028 </video>""".format(url)
1027 </video>""".format(url)
1029 return output
1028 return output
1030
1029
1031 # Embedded videos are base64-encoded.
1030 # Embedded videos are base64-encoded.
1032 mimetype = self.mimetype
1031 mimetype = self.mimetype
1033 if self.filename is not None:
1032 if self.filename is not None:
1034 if not mimetype:
1033 if not mimetype:
1035 mimetype, _ = mimetypes.guess_type(self.filename)
1034 mimetype, _ = mimetypes.guess_type(self.filename)
1036
1035
1037 with open(self.filename, 'rb') as f:
1036 with open(self.filename, 'rb') as f:
1038 video = f.read()
1037 video = f.read()
1039 else:
1038 else:
1040 video = self.data
1039 video = self.data
1041 if isinstance(video, unicode_type):
1040 if isinstance(video, str):
1042 # unicode input is already b64-encoded
1041 # unicode input is already b64-encoded
1043 b64_video = video
1042 b64_video = video
1044 else:
1043 else:
1045 b64_video = base64_encode(video).decode('ascii').rstrip()
1044 b64_video = base64_encode(video).decode('ascii').rstrip()
1046
1045
1047 output = """<video controls>
1046 output = """<video controls>
1048 <source src="data:{0};base64,{1}" type="{0}">
1047 <source src="data:{0};base64,{1}" type="{0}">
1049 Your browser does not support the video tag.
1048 Your browser does not support the video tag.
1050 </video>""".format(mimetype, b64_video)
1049 </video>""".format(mimetype, b64_video)
1051 return output
1050 return output
1052
1051
1053 def reload(self):
1052 def reload(self):
1054 # TODO
1053 # TODO
1055 pass
1054 pass
1056
1055
1057 def _repr_png_(self):
1056 def _repr_png_(self):
1058 # TODO
1057 # TODO
1059 pass
1058 pass
1060 def _repr_jpeg_(self):
1059 def _repr_jpeg_(self):
1061 # TODO
1060 # TODO
1062 pass
1061 pass
1063
1062
1064 def clear_output(wait=False):
1063 def clear_output(wait=False):
1065 """Clear the output of the current cell receiving output.
1064 """Clear the output of the current cell receiving output.
1066
1065
1067 Parameters
1066 Parameters
1068 ----------
1067 ----------
1069 wait : bool [default: false]
1068 wait : bool [default: false]
1070 Wait to clear the output until new output is available to replace it."""
1069 Wait to clear the output until new output is available to replace it."""
1071 from IPython.core.interactiveshell import InteractiveShell
1070 from IPython.core.interactiveshell import InteractiveShell
1072 if InteractiveShell.initialized():
1071 if InteractiveShell.initialized():
1073 InteractiveShell.instance().display_pub.clear_output(wait)
1072 InteractiveShell.instance().display_pub.clear_output(wait)
1074 else:
1073 else:
1075 print('\033[2K\r', end='')
1074 print('\033[2K\r', end='')
1076 sys.stdout.flush()
1075 sys.stdout.flush()
1077 print('\033[2K\r', end='')
1076 print('\033[2K\r', end='')
1078 sys.stderr.flush()
1077 sys.stderr.flush()
1079
1078
1080
1079
1081 @skip_doctest
1080 @skip_doctest
1082 def set_matplotlib_formats(*formats, **kwargs):
1081 def set_matplotlib_formats(*formats, **kwargs):
1083 """Select figure formats for the inline backend. Optionally pass quality for JPEG.
1082 """Select figure formats for the inline backend. Optionally pass quality for JPEG.
1084
1083
1085 For example, this enables PNG and JPEG output with a JPEG quality of 90%::
1084 For example, this enables PNG and JPEG output with a JPEG quality of 90%::
1086
1085
1087 In [1]: set_matplotlib_formats('png', 'jpeg', quality=90)
1086 In [1]: set_matplotlib_formats('png', 'jpeg', quality=90)
1088
1087
1089 To set this in your config files use the following::
1088 To set this in your config files use the following::
1090
1089
1091 c.InlineBackend.figure_formats = {'png', 'jpeg'}
1090 c.InlineBackend.figure_formats = {'png', 'jpeg'}
1092 c.InlineBackend.print_figure_kwargs.update({'quality' : 90})
1091 c.InlineBackend.print_figure_kwargs.update({'quality' : 90})
1093
1092
1094 Parameters
1093 Parameters
1095 ----------
1094 ----------
1096 *formats : strs
1095 *formats : strs
1097 One or more figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'.
1096 One or more figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'.
1098 **kwargs :
1097 **kwargs :
1099 Keyword args will be relayed to ``figure.canvas.print_figure``.
1098 Keyword args will be relayed to ``figure.canvas.print_figure``.
1100 """
1099 """
1101 from IPython.core.interactiveshell import InteractiveShell
1100 from IPython.core.interactiveshell import InteractiveShell
1102 from IPython.core.pylabtools import select_figure_formats
1101 from IPython.core.pylabtools import select_figure_formats
1103 # build kwargs, starting with InlineBackend config
1102 # build kwargs, starting with InlineBackend config
1104 kw = {}
1103 kw = {}
1105 from ipykernel.pylab.config import InlineBackend
1104 from ipykernel.pylab.config import InlineBackend
1106 cfg = InlineBackend.instance()
1105 cfg = InlineBackend.instance()
1107 kw.update(cfg.print_figure_kwargs)
1106 kw.update(cfg.print_figure_kwargs)
1108 kw.update(**kwargs)
1107 kw.update(**kwargs)
1109 shell = InteractiveShell.instance()
1108 shell = InteractiveShell.instance()
1110 select_figure_formats(shell, formats, **kw)
1109 select_figure_formats(shell, formats, **kw)
1111
1110
1112 @skip_doctest
1111 @skip_doctest
1113 def set_matplotlib_close(close=True):
1112 def set_matplotlib_close(close=True):
1114 """Set whether the inline backend closes all figures automatically or not.
1113 """Set whether the inline backend closes all figures automatically or not.
1115
1114
1116 By default, the inline backend used in the IPython Notebook will close all
1115 By default, the inline backend used in the IPython Notebook will close all
1117 matplotlib figures automatically after each cell is run. This means that
1116 matplotlib figures automatically after each cell is run. This means that
1118 plots in different cells won't interfere. Sometimes, you may want to make
1117 plots in different cells won't interfere. Sometimes, you may want to make
1119 a plot in one cell and then refine it in later cells. This can be accomplished
1118 a plot in one cell and then refine it in later cells. This can be accomplished
1120 by::
1119 by::
1121
1120
1122 In [1]: set_matplotlib_close(False)
1121 In [1]: set_matplotlib_close(False)
1123
1122
1124 To set this in your config files use the following::
1123 To set this in your config files use the following::
1125
1124
1126 c.InlineBackend.close_figures = False
1125 c.InlineBackend.close_figures = False
1127
1126
1128 Parameters
1127 Parameters
1129 ----------
1128 ----------
1130 close : bool
1129 close : bool
1131 Should all matplotlib figures be automatically closed after each cell is
1130 Should all matplotlib figures be automatically closed after each cell is
1132 run?
1131 run?
1133 """
1132 """
1134 from ipykernel.pylab.config import InlineBackend
1133 from ipykernel.pylab.config import InlineBackend
1135 cfg = InlineBackend.instance()
1134 cfg = InlineBackend.instance()
1136 cfg.close_figures = close
1135 cfg.close_figures = close
@@ -1,947 +1,947 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Display formatters.
2 """Display formatters.
3
3
4 Inheritance diagram:
4 Inheritance diagram:
5
5
6 .. inheritance-diagram:: IPython.core.formatters
6 .. inheritance-diagram:: IPython.core.formatters
7 :parts: 3
7 :parts: 3
8 """
8 """
9
9
10 # Copyright (c) IPython Development Team.
10 # Copyright (c) IPython Development Team.
11 # Distributed under the terms of the Modified BSD License.
11 # Distributed under the terms of the Modified BSD License.
12
12
13 import abc
13 import abc
14 import json
14 import json
15 import sys
15 import sys
16 import traceback
16 import traceback
17 import warnings
17 import warnings
18
18
19 from decorator import decorator
19 from decorator import decorator
20
20
21 from traitlets.config.configurable import Configurable
21 from traitlets.config.configurable import Configurable
22 from IPython.core.getipython import get_ipython
22 from IPython.core.getipython import get_ipython
23 from IPython.utils.sentinel import Sentinel
23 from IPython.utils.sentinel import Sentinel
24 from IPython.utils.dir2 import get_real_method
24 from IPython.utils.dir2 import get_real_method
25 from IPython.lib import pretty
25 from IPython.lib import pretty
26 from traitlets import (
26 from traitlets import (
27 Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List,
27 Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List,
28 ForwardDeclaredInstance,
28 ForwardDeclaredInstance,
29 default, observe,
29 default, observe,
30 )
30 )
31 from IPython.utils.py3compat import (
31 from IPython.utils.py3compat import (
32 with_metaclass, string_types, unicode_type,
32 with_metaclass
33 )
33 )
34
34
35
35
36 class DisplayFormatter(Configurable):
36 class DisplayFormatter(Configurable):
37
37
38 active_types = List(Unicode(),
38 active_types = List(Unicode(),
39 help="""List of currently active mime-types to display.
39 help="""List of currently active mime-types to display.
40 You can use this to set a white-list for formats to display.
40 You can use this to set a white-list for formats to display.
41
41
42 Most users will not need to change this value.
42 Most users will not need to change this value.
43 """).tag(config=True)
43 """).tag(config=True)
44
44
45 @default('active_types')
45 @default('active_types')
46 def _active_types_default(self):
46 def _active_types_default(self):
47 return self.format_types
47 return self.format_types
48
48
49 @observe('active_types')
49 @observe('active_types')
50 def _active_types_changed(self, change):
50 def _active_types_changed(self, change):
51 for key, formatter in self.formatters.items():
51 for key, formatter in self.formatters.items():
52 if key in change['new']:
52 if key in change['new']:
53 formatter.enabled = True
53 formatter.enabled = True
54 else:
54 else:
55 formatter.enabled = False
55 formatter.enabled = False
56
56
57 ipython_display_formatter = ForwardDeclaredInstance('FormatterABC')
57 ipython_display_formatter = ForwardDeclaredInstance('FormatterABC')
58 @default('ipython_display_formatter')
58 @default('ipython_display_formatter')
59 def _default_formatter(self):
59 def _default_formatter(self):
60 return IPythonDisplayFormatter(parent=self)
60 return IPythonDisplayFormatter(parent=self)
61
61
62 # A dict of formatter whose keys are format types (MIME types) and whose
62 # A dict of formatter whose keys are format types (MIME types) and whose
63 # values are subclasses of BaseFormatter.
63 # values are subclasses of BaseFormatter.
64 formatters = Dict()
64 formatters = Dict()
65 @default('formatters')
65 @default('formatters')
66 def _formatters_default(self):
66 def _formatters_default(self):
67 """Activate the default formatters."""
67 """Activate the default formatters."""
68 formatter_classes = [
68 formatter_classes = [
69 PlainTextFormatter,
69 PlainTextFormatter,
70 HTMLFormatter,
70 HTMLFormatter,
71 MarkdownFormatter,
71 MarkdownFormatter,
72 SVGFormatter,
72 SVGFormatter,
73 PNGFormatter,
73 PNGFormatter,
74 PDFFormatter,
74 PDFFormatter,
75 JPEGFormatter,
75 JPEGFormatter,
76 LatexFormatter,
76 LatexFormatter,
77 JSONFormatter,
77 JSONFormatter,
78 JavascriptFormatter
78 JavascriptFormatter
79 ]
79 ]
80 d = {}
80 d = {}
81 for cls in formatter_classes:
81 for cls in formatter_classes:
82 f = cls(parent=self)
82 f = cls(parent=self)
83 d[f.format_type] = f
83 d[f.format_type] = f
84 return d
84 return d
85
85
86 def format(self, obj, include=None, exclude=None):
86 def format(self, obj, include=None, exclude=None):
87 """Return a format data dict for an object.
87 """Return a format data dict for an object.
88
88
89 By default all format types will be computed.
89 By default all format types will be computed.
90
90
91 The following MIME types are currently implemented:
91 The following MIME types are currently implemented:
92
92
93 * text/plain
93 * text/plain
94 * text/html
94 * text/html
95 * text/markdown
95 * text/markdown
96 * text/latex
96 * text/latex
97 * application/json
97 * application/json
98 * application/javascript
98 * application/javascript
99 * application/pdf
99 * application/pdf
100 * image/png
100 * image/png
101 * image/jpeg
101 * image/jpeg
102 * image/svg+xml
102 * image/svg+xml
103
103
104 Parameters
104 Parameters
105 ----------
105 ----------
106 obj : object
106 obj : object
107 The Python object whose format data will be computed.
107 The Python object whose format data will be computed.
108 include : list or tuple, optional
108 include : list or tuple, optional
109 A list of format type strings (MIME types) to include in the
109 A list of format type strings (MIME types) to include in the
110 format data dict. If this is set *only* the format types included
110 format data dict. If this is set *only* the format types included
111 in this list will be computed.
111 in this list will be computed.
112 exclude : list or tuple, optional
112 exclude : list or tuple, optional
113 A list of format type string (MIME types) to exclude in the format
113 A list of format type string (MIME types) to exclude in the format
114 data dict. If this is set all format types will be computed,
114 data dict. If this is set all format types will be computed,
115 except for those included in this argument.
115 except for those included in this argument.
116
116
117 Returns
117 Returns
118 -------
118 -------
119 (format_dict, metadata_dict) : tuple of two dicts
119 (format_dict, metadata_dict) : tuple of two dicts
120
120
121 format_dict is a dictionary of key/value pairs, one of each format that was
121 format_dict is a dictionary of key/value pairs, one of each format that was
122 generated for the object. The keys are the format types, which
122 generated for the object. The keys are the format types, which
123 will usually be MIME type strings and the values and JSON'able
123 will usually be MIME type strings and the values and JSON'able
124 data structure containing the raw data for the representation in
124 data structure containing the raw data for the representation in
125 that format.
125 that format.
126
126
127 metadata_dict is a dictionary of metadata about each mime-type output.
127 metadata_dict is a dictionary of metadata about each mime-type output.
128 Its keys will be a strict subset of the keys in format_dict.
128 Its keys will be a strict subset of the keys in format_dict.
129 """
129 """
130 format_dict = {}
130 format_dict = {}
131 md_dict = {}
131 md_dict = {}
132
132
133 if self.ipython_display_formatter(obj):
133 if self.ipython_display_formatter(obj):
134 # object handled itself, don't proceed
134 # object handled itself, don't proceed
135 return {}, {}
135 return {}, {}
136
136
137 for format_type, formatter in self.formatters.items():
137 for format_type, formatter in self.formatters.items():
138 if include and format_type not in include:
138 if include and format_type not in include:
139 continue
139 continue
140 if exclude and format_type in exclude:
140 if exclude and format_type in exclude:
141 continue
141 continue
142
142
143 md = None
143 md = None
144 try:
144 try:
145 data = formatter(obj)
145 data = formatter(obj)
146 except:
146 except:
147 # FIXME: log the exception
147 # FIXME: log the exception
148 raise
148 raise
149
149
150 # formatters can return raw data or (data, metadata)
150 # formatters can return raw data or (data, metadata)
151 if isinstance(data, tuple) and len(data) == 2:
151 if isinstance(data, tuple) and len(data) == 2:
152 data, md = data
152 data, md = data
153
153
154 if data is not None:
154 if data is not None:
155 format_dict[format_type] = data
155 format_dict[format_type] = data
156 if md is not None:
156 if md is not None:
157 md_dict[format_type] = md
157 md_dict[format_type] = md
158
158
159 return format_dict, md_dict
159 return format_dict, md_dict
160
160
161 @property
161 @property
162 def format_types(self):
162 def format_types(self):
163 """Return the format types (MIME types) of the active formatters."""
163 """Return the format types (MIME types) of the active formatters."""
164 return list(self.formatters.keys())
164 return list(self.formatters.keys())
165
165
166
166
167 #-----------------------------------------------------------------------------
167 #-----------------------------------------------------------------------------
168 # Formatters for specific format types (text, html, svg, etc.)
168 # Formatters for specific format types (text, html, svg, etc.)
169 #-----------------------------------------------------------------------------
169 #-----------------------------------------------------------------------------
170
170
171
171
172 def _safe_repr(obj):
172 def _safe_repr(obj):
173 """Try to return a repr of an object
173 """Try to return a repr of an object
174
174
175 always returns a string, at least.
175 always returns a string, at least.
176 """
176 """
177 try:
177 try:
178 return repr(obj)
178 return repr(obj)
179 except Exception as e:
179 except Exception as e:
180 return "un-repr-able object (%r)" % e
180 return "un-repr-able object (%r)" % e
181
181
182
182
183 class FormatterWarning(UserWarning):
183 class FormatterWarning(UserWarning):
184 """Warning class for errors in formatters"""
184 """Warning class for errors in formatters"""
185
185
186 @decorator
186 @decorator
187 def catch_format_error(method, self, *args, **kwargs):
187 def catch_format_error(method, self, *args, **kwargs):
188 """show traceback on failed format call"""
188 """show traceback on failed format call"""
189 try:
189 try:
190 r = method(self, *args, **kwargs)
190 r = method(self, *args, **kwargs)
191 except NotImplementedError:
191 except NotImplementedError:
192 # don't warn on NotImplementedErrors
192 # don't warn on NotImplementedErrors
193 return None
193 return None
194 except Exception:
194 except Exception:
195 exc_info = sys.exc_info()
195 exc_info = sys.exc_info()
196 ip = get_ipython()
196 ip = get_ipython()
197 if ip is not None:
197 if ip is not None:
198 ip.showtraceback(exc_info)
198 ip.showtraceback(exc_info)
199 else:
199 else:
200 traceback.print_exception(*exc_info)
200 traceback.print_exception(*exc_info)
201 return None
201 return None
202 return self._check_return(r, args[0])
202 return self._check_return(r, args[0])
203
203
204
204
205 class FormatterABC(with_metaclass(abc.ABCMeta, object)):
205 class FormatterABC(with_metaclass(abc.ABCMeta, object)):
206 """ Abstract base class for Formatters.
206 """ Abstract base class for Formatters.
207
207
208 A formatter is a callable class that is responsible for computing the
208 A formatter is a callable class that is responsible for computing the
209 raw format data for a particular format type (MIME type). For example,
209 raw format data for a particular format type (MIME type). For example,
210 an HTML formatter would have a format type of `text/html` and would return
210 an HTML formatter would have a format type of `text/html` and would return
211 the HTML representation of the object when called.
211 the HTML representation of the object when called.
212 """
212 """
213
213
214 # The format type of the data returned, usually a MIME type.
214 # The format type of the data returned, usually a MIME type.
215 format_type = 'text/plain'
215 format_type = 'text/plain'
216
216
217 # Is the formatter enabled...
217 # Is the formatter enabled...
218 enabled = True
218 enabled = True
219
219
220 @abc.abstractmethod
220 @abc.abstractmethod
221 def __call__(self, obj):
221 def __call__(self, obj):
222 """Return a JSON'able representation of the object.
222 """Return a JSON'able representation of the object.
223
223
224 If the object cannot be formatted by this formatter,
224 If the object cannot be formatted by this formatter,
225 warn and return None.
225 warn and return None.
226 """
226 """
227 return repr(obj)
227 return repr(obj)
228
228
229
229
230 def _mod_name_key(typ):
230 def _mod_name_key(typ):
231 """Return a (__module__, __name__) tuple for a type.
231 """Return a (__module__, __name__) tuple for a type.
232
232
233 Used as key in Formatter.deferred_printers.
233 Used as key in Formatter.deferred_printers.
234 """
234 """
235 module = getattr(typ, '__module__', None)
235 module = getattr(typ, '__module__', None)
236 name = getattr(typ, '__name__', None)
236 name = getattr(typ, '__name__', None)
237 return (module, name)
237 return (module, name)
238
238
239
239
240 def _get_type(obj):
240 def _get_type(obj):
241 """Return the type of an instance (old and new-style)"""
241 """Return the type of an instance (old and new-style)"""
242 return getattr(obj, '__class__', None) or type(obj)
242 return getattr(obj, '__class__', None) or type(obj)
243
243
244
244
245 _raise_key_error = Sentinel('_raise_key_error', __name__,
245 _raise_key_error = Sentinel('_raise_key_error', __name__,
246 """
246 """
247 Special value to raise a KeyError
247 Special value to raise a KeyError
248
248
249 Raise KeyError in `BaseFormatter.pop` if passed as the default value to `pop`
249 Raise KeyError in `BaseFormatter.pop` if passed as the default value to `pop`
250 """)
250 """)
251
251
252
252
253 class BaseFormatter(Configurable):
253 class BaseFormatter(Configurable):
254 """A base formatter class that is configurable.
254 """A base formatter class that is configurable.
255
255
256 This formatter should usually be used as the base class of all formatters.
256 This formatter should usually be used as the base class of all formatters.
257 It is a traited :class:`Configurable` class and includes an extensible
257 It is a traited :class:`Configurable` class and includes an extensible
258 API for users to determine how their objects are formatted. The following
258 API for users to determine how their objects are formatted. The following
259 logic is used to find a function to format an given object.
259 logic is used to find a function to format an given object.
260
260
261 1. The object is introspected to see if it has a method with the name
261 1. The object is introspected to see if it has a method with the name
262 :attr:`print_method`. If is does, that object is passed to that method
262 :attr:`print_method`. If is does, that object is passed to that method
263 for formatting.
263 for formatting.
264 2. If no print method is found, three internal dictionaries are consulted
264 2. If no print method is found, three internal dictionaries are consulted
265 to find print method: :attr:`singleton_printers`, :attr:`type_printers`
265 to find print method: :attr:`singleton_printers`, :attr:`type_printers`
266 and :attr:`deferred_printers`.
266 and :attr:`deferred_printers`.
267
267
268 Users should use these dictionaries to register functions that will be
268 Users should use these dictionaries to register functions that will be
269 used to compute the format data for their objects (if those objects don't
269 used to compute the format data for their objects (if those objects don't
270 have the special print methods). The easiest way of using these
270 have the special print methods). The easiest way of using these
271 dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
271 dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
272 methods.
272 methods.
273
273
274 If no function/callable is found to compute the format data, ``None`` is
274 If no function/callable is found to compute the format data, ``None`` is
275 returned and this format type is not used.
275 returned and this format type is not used.
276 """
276 """
277
277
278 format_type = Unicode('text/plain')
278 format_type = Unicode('text/plain')
279 _return_type = string_types
279 _return_type = str
280
280
281 enabled = Bool(True).tag(config=True)
281 enabled = Bool(True).tag(config=True)
282
282
283 print_method = ObjectName('__repr__')
283 print_method = ObjectName('__repr__')
284
284
285 # The singleton printers.
285 # The singleton printers.
286 # Maps the IDs of the builtin singleton objects to the format functions.
286 # Maps the IDs of the builtin singleton objects to the format functions.
287 singleton_printers = Dict().tag(config=True)
287 singleton_printers = Dict().tag(config=True)
288
288
289 # The type-specific printers.
289 # The type-specific printers.
290 # Map type objects to the format functions.
290 # Map type objects to the format functions.
291 type_printers = Dict().tag(config=True)
291 type_printers = Dict().tag(config=True)
292
292
293 # The deferred-import type-specific printers.
293 # The deferred-import type-specific printers.
294 # Map (modulename, classname) pairs to the format functions.
294 # Map (modulename, classname) pairs to the format functions.
295 deferred_printers = Dict().tag(config=True)
295 deferred_printers = Dict().tag(config=True)
296
296
297 @catch_format_error
297 @catch_format_error
298 def __call__(self, obj):
298 def __call__(self, obj):
299 """Compute the format for an object."""
299 """Compute the format for an object."""
300 if self.enabled:
300 if self.enabled:
301 # lookup registered printer
301 # lookup registered printer
302 try:
302 try:
303 printer = self.lookup(obj)
303 printer = self.lookup(obj)
304 except KeyError:
304 except KeyError:
305 pass
305 pass
306 else:
306 else:
307 return printer(obj)
307 return printer(obj)
308 # Finally look for special method names
308 # Finally look for special method names
309 method = get_real_method(obj, self.print_method)
309 method = get_real_method(obj, self.print_method)
310 if method is not None:
310 if method is not None:
311 return method()
311 return method()
312 return None
312 return None
313 else:
313 else:
314 return None
314 return None
315
315
316 def __contains__(self, typ):
316 def __contains__(self, typ):
317 """map in to lookup_by_type"""
317 """map in to lookup_by_type"""
318 try:
318 try:
319 self.lookup_by_type(typ)
319 self.lookup_by_type(typ)
320 except KeyError:
320 except KeyError:
321 return False
321 return False
322 else:
322 else:
323 return True
323 return True
324
324
325 def _check_return(self, r, obj):
325 def _check_return(self, r, obj):
326 """Check that a return value is appropriate
326 """Check that a return value is appropriate
327
327
328 Return the value if so, None otherwise, warning if invalid.
328 Return the value if so, None otherwise, warning if invalid.
329 """
329 """
330 if r is None or isinstance(r, self._return_type) or \
330 if r is None or isinstance(r, self._return_type) or \
331 (isinstance(r, tuple) and r and isinstance(r[0], self._return_type)):
331 (isinstance(r, tuple) and r and isinstance(r[0], self._return_type)):
332 return r
332 return r
333 else:
333 else:
334 warnings.warn(
334 warnings.warn(
335 "%s formatter returned invalid type %s (expected %s) for object: %s" % \
335 "%s formatter returned invalid type %s (expected %s) for object: %s" % \
336 (self.format_type, type(r), self._return_type, _safe_repr(obj)),
336 (self.format_type, type(r), self._return_type, _safe_repr(obj)),
337 FormatterWarning
337 FormatterWarning
338 )
338 )
339
339
340 def lookup(self, obj):
340 def lookup(self, obj):
341 """Look up the formatter for a given instance.
341 """Look up the formatter for a given instance.
342
342
343 Parameters
343 Parameters
344 ----------
344 ----------
345 obj : object instance
345 obj : object instance
346
346
347 Returns
347 Returns
348 -------
348 -------
349 f : callable
349 f : callable
350 The registered formatting callable for the type.
350 The registered formatting callable for the type.
351
351
352 Raises
352 Raises
353 ------
353 ------
354 KeyError if the type has not been registered.
354 KeyError if the type has not been registered.
355 """
355 """
356 # look for singleton first
356 # look for singleton first
357 obj_id = id(obj)
357 obj_id = id(obj)
358 if obj_id in self.singleton_printers:
358 if obj_id in self.singleton_printers:
359 return self.singleton_printers[obj_id]
359 return self.singleton_printers[obj_id]
360 # then lookup by type
360 # then lookup by type
361 return self.lookup_by_type(_get_type(obj))
361 return self.lookup_by_type(_get_type(obj))
362
362
363 def lookup_by_type(self, typ):
363 def lookup_by_type(self, typ):
364 """Look up the registered formatter for a type.
364 """Look up the registered formatter for a type.
365
365
366 Parameters
366 Parameters
367 ----------
367 ----------
368 typ : type or '__module__.__name__' string for a type
368 typ : type or '__module__.__name__' string for a type
369
369
370 Returns
370 Returns
371 -------
371 -------
372 f : callable
372 f : callable
373 The registered formatting callable for the type.
373 The registered formatting callable for the type.
374
374
375 Raises
375 Raises
376 ------
376 ------
377 KeyError if the type has not been registered.
377 KeyError if the type has not been registered.
378 """
378 """
379 if isinstance(typ, string_types):
379 if isinstance(typ, str):
380 typ_key = tuple(typ.rsplit('.',1))
380 typ_key = tuple(typ.rsplit('.',1))
381 if typ_key not in self.deferred_printers:
381 if typ_key not in self.deferred_printers:
382 # We may have it cached in the type map. We will have to
382 # We may have it cached in the type map. We will have to
383 # iterate over all of the types to check.
383 # iterate over all of the types to check.
384 for cls in self.type_printers:
384 for cls in self.type_printers:
385 if _mod_name_key(cls) == typ_key:
385 if _mod_name_key(cls) == typ_key:
386 return self.type_printers[cls]
386 return self.type_printers[cls]
387 else:
387 else:
388 return self.deferred_printers[typ_key]
388 return self.deferred_printers[typ_key]
389 else:
389 else:
390 for cls in pretty._get_mro(typ):
390 for cls in pretty._get_mro(typ):
391 if cls in self.type_printers or self._in_deferred_types(cls):
391 if cls in self.type_printers or self._in_deferred_types(cls):
392 return self.type_printers[cls]
392 return self.type_printers[cls]
393
393
394 # If we have reached here, the lookup failed.
394 # If we have reached here, the lookup failed.
395 raise KeyError("No registered printer for {0!r}".format(typ))
395 raise KeyError("No registered printer for {0!r}".format(typ))
396
396
397 def for_type(self, typ, func=None):
397 def for_type(self, typ, func=None):
398 """Add a format function for a given type.
398 """Add a format function for a given type.
399
399
400 Parameters
400 Parameters
401 -----------
401 -----------
402 typ : type or '__module__.__name__' string for a type
402 typ : type or '__module__.__name__' string for a type
403 The class of the object that will be formatted using `func`.
403 The class of the object that will be formatted using `func`.
404 func : callable
404 func : callable
405 A callable for computing the format data.
405 A callable for computing the format data.
406 `func` will be called with the object to be formatted,
406 `func` will be called with the object to be formatted,
407 and will return the raw data in this formatter's format.
407 and will return the raw data in this formatter's format.
408 Subclasses may use a different call signature for the
408 Subclasses may use a different call signature for the
409 `func` argument.
409 `func` argument.
410
410
411 If `func` is None or not specified, there will be no change,
411 If `func` is None or not specified, there will be no change,
412 only returning the current value.
412 only returning the current value.
413
413
414 Returns
414 Returns
415 -------
415 -------
416 oldfunc : callable
416 oldfunc : callable
417 The currently registered callable.
417 The currently registered callable.
418 If you are registering a new formatter,
418 If you are registering a new formatter,
419 this will be the previous value (to enable restoring later).
419 this will be the previous value (to enable restoring later).
420 """
420 """
421 # if string given, interpret as 'pkg.module.class_name'
421 # if string given, interpret as 'pkg.module.class_name'
422 if isinstance(typ, string_types):
422 if isinstance(typ, str):
423 type_module, type_name = typ.rsplit('.', 1)
423 type_module, type_name = typ.rsplit('.', 1)
424 return self.for_type_by_name(type_module, type_name, func)
424 return self.for_type_by_name(type_module, type_name, func)
425
425
426 try:
426 try:
427 oldfunc = self.lookup_by_type(typ)
427 oldfunc = self.lookup_by_type(typ)
428 except KeyError:
428 except KeyError:
429 oldfunc = None
429 oldfunc = None
430
430
431 if func is not None:
431 if func is not None:
432 self.type_printers[typ] = func
432 self.type_printers[typ] = func
433
433
434 return oldfunc
434 return oldfunc
435
435
436 def for_type_by_name(self, type_module, type_name, func=None):
436 def for_type_by_name(self, type_module, type_name, func=None):
437 """Add a format function for a type specified by the full dotted
437 """Add a format function for a type specified by the full dotted
438 module and name of the type, rather than the type of the object.
438 module and name of the type, rather than the type of the object.
439
439
440 Parameters
440 Parameters
441 ----------
441 ----------
442 type_module : str
442 type_module : str
443 The full dotted name of the module the type is defined in, like
443 The full dotted name of the module the type is defined in, like
444 ``numpy``.
444 ``numpy``.
445 type_name : str
445 type_name : str
446 The name of the type (the class name), like ``dtype``
446 The name of the type (the class name), like ``dtype``
447 func : callable
447 func : callable
448 A callable for computing the format data.
448 A callable for computing the format data.
449 `func` will be called with the object to be formatted,
449 `func` will be called with the object to be formatted,
450 and will return the raw data in this formatter's format.
450 and will return the raw data in this formatter's format.
451 Subclasses may use a different call signature for the
451 Subclasses may use a different call signature for the
452 `func` argument.
452 `func` argument.
453
453
454 If `func` is None or unspecified, there will be no change,
454 If `func` is None or unspecified, there will be no change,
455 only returning the current value.
455 only returning the current value.
456
456
457 Returns
457 Returns
458 -------
458 -------
459 oldfunc : callable
459 oldfunc : callable
460 The currently registered callable.
460 The currently registered callable.
461 If you are registering a new formatter,
461 If you are registering a new formatter,
462 this will be the previous value (to enable restoring later).
462 this will be the previous value (to enable restoring later).
463 """
463 """
464 key = (type_module, type_name)
464 key = (type_module, type_name)
465
465
466 try:
466 try:
467 oldfunc = self.lookup_by_type("%s.%s" % key)
467 oldfunc = self.lookup_by_type("%s.%s" % key)
468 except KeyError:
468 except KeyError:
469 oldfunc = None
469 oldfunc = None
470
470
471 if func is not None:
471 if func is not None:
472 self.deferred_printers[key] = func
472 self.deferred_printers[key] = func
473 return oldfunc
473 return oldfunc
474
474
475 def pop(self, typ, default=_raise_key_error):
475 def pop(self, typ, default=_raise_key_error):
476 """Pop a formatter for the given type.
476 """Pop a formatter for the given type.
477
477
478 Parameters
478 Parameters
479 ----------
479 ----------
480 typ : type or '__module__.__name__' string for a type
480 typ : type or '__module__.__name__' string for a type
481 default : object
481 default : object
482 value to be returned if no formatter is registered for typ.
482 value to be returned if no formatter is registered for typ.
483
483
484 Returns
484 Returns
485 -------
485 -------
486 obj : object
486 obj : object
487 The last registered object for the type.
487 The last registered object for the type.
488
488
489 Raises
489 Raises
490 ------
490 ------
491 KeyError if the type is not registered and default is not specified.
491 KeyError if the type is not registered and default is not specified.
492 """
492 """
493
493
494 if isinstance(typ, string_types):
494 if isinstance(typ, str):
495 typ_key = tuple(typ.rsplit('.',1))
495 typ_key = tuple(typ.rsplit('.',1))
496 if typ_key not in self.deferred_printers:
496 if typ_key not in self.deferred_printers:
497 # We may have it cached in the type map. We will have to
497 # We may have it cached in the type map. We will have to
498 # iterate over all of the types to check.
498 # iterate over all of the types to check.
499 for cls in self.type_printers:
499 for cls in self.type_printers:
500 if _mod_name_key(cls) == typ_key:
500 if _mod_name_key(cls) == typ_key:
501 old = self.type_printers.pop(cls)
501 old = self.type_printers.pop(cls)
502 break
502 break
503 else:
503 else:
504 old = default
504 old = default
505 else:
505 else:
506 old = self.deferred_printers.pop(typ_key)
506 old = self.deferred_printers.pop(typ_key)
507 else:
507 else:
508 if typ in self.type_printers:
508 if typ in self.type_printers:
509 old = self.type_printers.pop(typ)
509 old = self.type_printers.pop(typ)
510 else:
510 else:
511 old = self.deferred_printers.pop(_mod_name_key(typ), default)
511 old = self.deferred_printers.pop(_mod_name_key(typ), default)
512 if old is _raise_key_error:
512 if old is _raise_key_error:
513 raise KeyError("No registered value for {0!r}".format(typ))
513 raise KeyError("No registered value for {0!r}".format(typ))
514 return old
514 return old
515
515
516 def _in_deferred_types(self, cls):
516 def _in_deferred_types(self, cls):
517 """
517 """
518 Check if the given class is specified in the deferred type registry.
518 Check if the given class is specified in the deferred type registry.
519
519
520 Successful matches will be moved to the regular type registry for future use.
520 Successful matches will be moved to the regular type registry for future use.
521 """
521 """
522 mod = getattr(cls, '__module__', None)
522 mod = getattr(cls, '__module__', None)
523 name = getattr(cls, '__name__', None)
523 name = getattr(cls, '__name__', None)
524 key = (mod, name)
524 key = (mod, name)
525 if key in self.deferred_printers:
525 if key in self.deferred_printers:
526 # Move the printer over to the regular registry.
526 # Move the printer over to the regular registry.
527 printer = self.deferred_printers.pop(key)
527 printer = self.deferred_printers.pop(key)
528 self.type_printers[cls] = printer
528 self.type_printers[cls] = printer
529 return True
529 return True
530 return False
530 return False
531
531
532
532
533 class PlainTextFormatter(BaseFormatter):
533 class PlainTextFormatter(BaseFormatter):
534 """The default pretty-printer.
534 """The default pretty-printer.
535
535
536 This uses :mod:`IPython.lib.pretty` to compute the format data of
536 This uses :mod:`IPython.lib.pretty` to compute the format data of
537 the object. If the object cannot be pretty printed, :func:`repr` is used.
537 the object. If the object cannot be pretty printed, :func:`repr` is used.
538 See the documentation of :mod:`IPython.lib.pretty` for details on
538 See the documentation of :mod:`IPython.lib.pretty` for details on
539 how to write pretty printers. Here is a simple example::
539 how to write pretty printers. Here is a simple example::
540
540
541 def dtype_pprinter(obj, p, cycle):
541 def dtype_pprinter(obj, p, cycle):
542 if cycle:
542 if cycle:
543 return p.text('dtype(...)')
543 return p.text('dtype(...)')
544 if hasattr(obj, 'fields'):
544 if hasattr(obj, 'fields'):
545 if obj.fields is None:
545 if obj.fields is None:
546 p.text(repr(obj))
546 p.text(repr(obj))
547 else:
547 else:
548 p.begin_group(7, 'dtype([')
548 p.begin_group(7, 'dtype([')
549 for i, field in enumerate(obj.descr):
549 for i, field in enumerate(obj.descr):
550 if i > 0:
550 if i > 0:
551 p.text(',')
551 p.text(',')
552 p.breakable()
552 p.breakable()
553 p.pretty(field)
553 p.pretty(field)
554 p.end_group(7, '])')
554 p.end_group(7, '])')
555 """
555 """
556
556
557 # The format type of data returned.
557 # The format type of data returned.
558 format_type = Unicode('text/plain')
558 format_type = Unicode('text/plain')
559
559
560 # This subclass ignores this attribute as it always need to return
560 # This subclass ignores this attribute as it always need to return
561 # something.
561 # something.
562 enabled = Bool(True).tag(config=False)
562 enabled = Bool(True).tag(config=False)
563
563
564 max_seq_length = Integer(pretty.MAX_SEQ_LENGTH,
564 max_seq_length = Integer(pretty.MAX_SEQ_LENGTH,
565 help="""Truncate large collections (lists, dicts, tuples, sets) to this size.
565 help="""Truncate large collections (lists, dicts, tuples, sets) to this size.
566
566
567 Set to 0 to disable truncation.
567 Set to 0 to disable truncation.
568 """
568 """
569 ).tag(config=True)
569 ).tag(config=True)
570
570
571 # Look for a _repr_pretty_ methods to use for pretty printing.
571 # Look for a _repr_pretty_ methods to use for pretty printing.
572 print_method = ObjectName('_repr_pretty_')
572 print_method = ObjectName('_repr_pretty_')
573
573
574 # Whether to pretty-print or not.
574 # Whether to pretty-print or not.
575 pprint = Bool(True).tag(config=True)
575 pprint = Bool(True).tag(config=True)
576
576
577 # Whether to be verbose or not.
577 # Whether to be verbose or not.
578 verbose = Bool(False).tag(config=True)
578 verbose = Bool(False).tag(config=True)
579
579
580 # The maximum width.
580 # The maximum width.
581 max_width = Integer(79).tag(config=True)
581 max_width = Integer(79).tag(config=True)
582
582
583 # The newline character.
583 # The newline character.
584 newline = Unicode('\n').tag(config=True)
584 newline = Unicode('\n').tag(config=True)
585
585
586 # format-string for pprinting floats
586 # format-string for pprinting floats
587 float_format = Unicode('%r')
587 float_format = Unicode('%r')
588 # setter for float precision, either int or direct format-string
588 # setter for float precision, either int or direct format-string
589 float_precision = CUnicode('').tag(config=True)
589 float_precision = CUnicode('').tag(config=True)
590
590
591 @observe('float_precision')
591 @observe('float_precision')
592 def _float_precision_changed(self, change):
592 def _float_precision_changed(self, change):
593 """float_precision changed, set float_format accordingly.
593 """float_precision changed, set float_format accordingly.
594
594
595 float_precision can be set by int or str.
595 float_precision can be set by int or str.
596 This will set float_format, after interpreting input.
596 This will set float_format, after interpreting input.
597 If numpy has been imported, numpy print precision will also be set.
597 If numpy has been imported, numpy print precision will also be set.
598
598
599 integer `n` sets format to '%.nf', otherwise, format set directly.
599 integer `n` sets format to '%.nf', otherwise, format set directly.
600
600
601 An empty string returns to defaults (repr for float, 8 for numpy).
601 An empty string returns to defaults (repr for float, 8 for numpy).
602
602
603 This parameter can be set via the '%precision' magic.
603 This parameter can be set via the '%precision' magic.
604 """
604 """
605
605
606 new = change['new']
606 new = change['new']
607 if '%' in new:
607 if '%' in new:
608 # got explicit format string
608 # got explicit format string
609 fmt = new
609 fmt = new
610 try:
610 try:
611 fmt%3.14159
611 fmt%3.14159
612 except Exception:
612 except Exception:
613 raise ValueError("Precision must be int or format string, not %r"%new)
613 raise ValueError("Precision must be int or format string, not %r"%new)
614 elif new:
614 elif new:
615 # otherwise, should be an int
615 # otherwise, should be an int
616 try:
616 try:
617 i = int(new)
617 i = int(new)
618 assert i >= 0
618 assert i >= 0
619 except ValueError:
619 except ValueError:
620 raise ValueError("Precision must be int or format string, not %r"%new)
620 raise ValueError("Precision must be int or format string, not %r"%new)
621 except AssertionError:
621 except AssertionError:
622 raise ValueError("int precision must be non-negative, not %r"%i)
622 raise ValueError("int precision must be non-negative, not %r"%i)
623
623
624 fmt = '%%.%if'%i
624 fmt = '%%.%if'%i
625 if 'numpy' in sys.modules:
625 if 'numpy' in sys.modules:
626 # set numpy precision if it has been imported
626 # set numpy precision if it has been imported
627 import numpy
627 import numpy
628 numpy.set_printoptions(precision=i)
628 numpy.set_printoptions(precision=i)
629 else:
629 else:
630 # default back to repr
630 # default back to repr
631 fmt = '%r'
631 fmt = '%r'
632 if 'numpy' in sys.modules:
632 if 'numpy' in sys.modules:
633 import numpy
633 import numpy
634 # numpy default is 8
634 # numpy default is 8
635 numpy.set_printoptions(precision=8)
635 numpy.set_printoptions(precision=8)
636 self.float_format = fmt
636 self.float_format = fmt
637
637
638 # Use the default pretty printers from IPython.lib.pretty.
638 # Use the default pretty printers from IPython.lib.pretty.
639 @default('singleton_printers')
639 @default('singleton_printers')
640 def _singleton_printers_default(self):
640 def _singleton_printers_default(self):
641 return pretty._singleton_pprinters.copy()
641 return pretty._singleton_pprinters.copy()
642
642
643 @default('type_printers')
643 @default('type_printers')
644 def _type_printers_default(self):
644 def _type_printers_default(self):
645 d = pretty._type_pprinters.copy()
645 d = pretty._type_pprinters.copy()
646 d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
646 d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
647 return d
647 return d
648
648
649 @default('deferred_printers')
649 @default('deferred_printers')
650 def _deferred_printers_default(self):
650 def _deferred_printers_default(self):
651 return pretty._deferred_type_pprinters.copy()
651 return pretty._deferred_type_pprinters.copy()
652
652
653 #### FormatterABC interface ####
653 #### FormatterABC interface ####
654
654
655 @catch_format_error
655 @catch_format_error
656 def __call__(self, obj):
656 def __call__(self, obj):
657 """Compute the pretty representation of the object."""
657 """Compute the pretty representation of the object."""
658 if not self.pprint:
658 if not self.pprint:
659 return repr(obj)
659 return repr(obj)
660 else:
660 else:
661 # handle str and unicode on Python 2
661 # handle str and unicode on Python 2
662 # io.StringIO only accepts unicode,
662 # io.StringIO only accepts unicode,
663 # cStringIO doesn't handle unicode on py2,
663 # cStringIO doesn't handle unicode on py2,
664 # StringIO allows str, unicode but only ascii str
664 # StringIO allows str, unicode but only ascii str
665 stream = pretty.CUnicodeIO()
665 stream = pretty.CUnicodeIO()
666 printer = pretty.RepresentationPrinter(stream, self.verbose,
666 printer = pretty.RepresentationPrinter(stream, self.verbose,
667 self.max_width, self.newline,
667 self.max_width, self.newline,
668 max_seq_length=self.max_seq_length,
668 max_seq_length=self.max_seq_length,
669 singleton_pprinters=self.singleton_printers,
669 singleton_pprinters=self.singleton_printers,
670 type_pprinters=self.type_printers,
670 type_pprinters=self.type_printers,
671 deferred_pprinters=self.deferred_printers)
671 deferred_pprinters=self.deferred_printers)
672 printer.pretty(obj)
672 printer.pretty(obj)
673 printer.flush()
673 printer.flush()
674 return stream.getvalue()
674 return stream.getvalue()
675
675
676
676
677 class HTMLFormatter(BaseFormatter):
677 class HTMLFormatter(BaseFormatter):
678 """An HTML formatter.
678 """An HTML formatter.
679
679
680 To define the callables that compute the HTML representation of your
680 To define the callables that compute the HTML representation of your
681 objects, define a :meth:`_repr_html_` method or use the :meth:`for_type`
681 objects, define a :meth:`_repr_html_` method or use the :meth:`for_type`
682 or :meth:`for_type_by_name` methods to register functions that handle
682 or :meth:`for_type_by_name` methods to register functions that handle
683 this.
683 this.
684
684
685 The return value of this formatter should be a valid HTML snippet that
685 The return value of this formatter should be a valid HTML snippet that
686 could be injected into an existing DOM. It should *not* include the
686 could be injected into an existing DOM. It should *not* include the
687 ```<html>`` or ```<body>`` tags.
687 ```<html>`` or ```<body>`` tags.
688 """
688 """
689 format_type = Unicode('text/html')
689 format_type = Unicode('text/html')
690
690
691 print_method = ObjectName('_repr_html_')
691 print_method = ObjectName('_repr_html_')
692
692
693
693
694 class MarkdownFormatter(BaseFormatter):
694 class MarkdownFormatter(BaseFormatter):
695 """A Markdown formatter.
695 """A Markdown formatter.
696
696
697 To define the callables that compute the Markdown representation of your
697 To define the callables that compute the Markdown representation of your
698 objects, define a :meth:`_repr_markdown_` method or use the :meth:`for_type`
698 objects, define a :meth:`_repr_markdown_` method or use the :meth:`for_type`
699 or :meth:`for_type_by_name` methods to register functions that handle
699 or :meth:`for_type_by_name` methods to register functions that handle
700 this.
700 this.
701
701
702 The return value of this formatter should be a valid Markdown.
702 The return value of this formatter should be a valid Markdown.
703 """
703 """
704 format_type = Unicode('text/markdown')
704 format_type = Unicode('text/markdown')
705
705
706 print_method = ObjectName('_repr_markdown_')
706 print_method = ObjectName('_repr_markdown_')
707
707
708 class SVGFormatter(BaseFormatter):
708 class SVGFormatter(BaseFormatter):
709 """An SVG formatter.
709 """An SVG formatter.
710
710
711 To define the callables that compute the SVG representation of your
711 To define the callables that compute the SVG representation of your
712 objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type`
712 objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type`
713 or :meth:`for_type_by_name` methods to register functions that handle
713 or :meth:`for_type_by_name` methods to register functions that handle
714 this.
714 this.
715
715
716 The return value of this formatter should be valid SVG enclosed in
716 The return value of this formatter should be valid SVG enclosed in
717 ```<svg>``` tags, that could be injected into an existing DOM. It should
717 ```<svg>``` tags, that could be injected into an existing DOM. It should
718 *not* include the ```<html>`` or ```<body>`` tags.
718 *not* include the ```<html>`` or ```<body>`` tags.
719 """
719 """
720 format_type = Unicode('image/svg+xml')
720 format_type = Unicode('image/svg+xml')
721
721
722 print_method = ObjectName('_repr_svg_')
722 print_method = ObjectName('_repr_svg_')
723
723
724
724
725 class PNGFormatter(BaseFormatter):
725 class PNGFormatter(BaseFormatter):
726 """A PNG formatter.
726 """A PNG formatter.
727
727
728 To define the callables that compute the PNG representation of your
728 To define the callables that compute the PNG representation of your
729 objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
729 objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
730 or :meth:`for_type_by_name` methods to register functions that handle
730 or :meth:`for_type_by_name` methods to register functions that handle
731 this.
731 this.
732
732
733 The return value of this formatter should be raw PNG data, *not*
733 The return value of this formatter should be raw PNG data, *not*
734 base64 encoded.
734 base64 encoded.
735 """
735 """
736 format_type = Unicode('image/png')
736 format_type = Unicode('image/png')
737
737
738 print_method = ObjectName('_repr_png_')
738 print_method = ObjectName('_repr_png_')
739
739
740 _return_type = (bytes, unicode_type)
740 _return_type = (bytes, str)
741
741
742
742
743 class JPEGFormatter(BaseFormatter):
743 class JPEGFormatter(BaseFormatter):
744 """A JPEG formatter.
744 """A JPEG formatter.
745
745
746 To define the callables that compute the JPEG representation of your
746 To define the callables that compute the JPEG representation of your
747 objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type`
747 objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type`
748 or :meth:`for_type_by_name` methods to register functions that handle
748 or :meth:`for_type_by_name` methods to register functions that handle
749 this.
749 this.
750
750
751 The return value of this formatter should be raw JPEG data, *not*
751 The return value of this formatter should be raw JPEG data, *not*
752 base64 encoded.
752 base64 encoded.
753 """
753 """
754 format_type = Unicode('image/jpeg')
754 format_type = Unicode('image/jpeg')
755
755
756 print_method = ObjectName('_repr_jpeg_')
756 print_method = ObjectName('_repr_jpeg_')
757
757
758 _return_type = (bytes, unicode_type)
758 _return_type = (bytes, str)
759
759
760
760
761 class LatexFormatter(BaseFormatter):
761 class LatexFormatter(BaseFormatter):
762 """A LaTeX formatter.
762 """A LaTeX formatter.
763
763
764 To define the callables that compute the LaTeX representation of your
764 To define the callables that compute the LaTeX representation of your
765 objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type`
765 objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type`
766 or :meth:`for_type_by_name` methods to register functions that handle
766 or :meth:`for_type_by_name` methods to register functions that handle
767 this.
767 this.
768
768
769 The return value of this formatter should be a valid LaTeX equation,
769 The return value of this formatter should be a valid LaTeX equation,
770 enclosed in either ```$```, ```$$``` or another LaTeX equation
770 enclosed in either ```$```, ```$$``` or another LaTeX equation
771 environment.
771 environment.
772 """
772 """
773 format_type = Unicode('text/latex')
773 format_type = Unicode('text/latex')
774
774
775 print_method = ObjectName('_repr_latex_')
775 print_method = ObjectName('_repr_latex_')
776
776
777
777
778 class JSONFormatter(BaseFormatter):
778 class JSONFormatter(BaseFormatter):
779 """A JSON string formatter.
779 """A JSON string formatter.
780
780
781 To define the callables that compute the JSONable representation of
781 To define the callables that compute the JSONable representation of
782 your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type`
782 your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type`
783 or :meth:`for_type_by_name` methods to register functions that handle
783 or :meth:`for_type_by_name` methods to register functions that handle
784 this.
784 this.
785
785
786 The return value of this formatter should be a JSONable list or dict.
786 The return value of this formatter should be a JSONable list or dict.
787 JSON scalars (None, number, string) are not allowed, only dict or list containers.
787 JSON scalars (None, number, string) are not allowed, only dict or list containers.
788 """
788 """
789 format_type = Unicode('application/json')
789 format_type = Unicode('application/json')
790 _return_type = (list, dict)
790 _return_type = (list, dict)
791
791
792 print_method = ObjectName('_repr_json_')
792 print_method = ObjectName('_repr_json_')
793
793
794 def _check_return(self, r, obj):
794 def _check_return(self, r, obj):
795 """Check that a return value is appropriate
795 """Check that a return value is appropriate
796
796
797 Return the value if so, None otherwise, warning if invalid.
797 Return the value if so, None otherwise, warning if invalid.
798 """
798 """
799 if r is None:
799 if r is None:
800 return
800 return
801 md = None
801 md = None
802 if isinstance(r, tuple):
802 if isinstance(r, tuple):
803 # unpack data, metadata tuple for type checking on first element
803 # unpack data, metadata tuple for type checking on first element
804 r, md = r
804 r, md = r
805
805
806 # handle deprecated JSON-as-string form from IPython < 3
806 # handle deprecated JSON-as-string form from IPython < 3
807 if isinstance(r, string_types):
807 if isinstance(r, str):
808 warnings.warn("JSON expects JSONable list/dict containers, not JSON strings",
808 warnings.warn("JSON expects JSONable list/dict containers, not JSON strings",
809 FormatterWarning)
809 FormatterWarning)
810 r = json.loads(r)
810 r = json.loads(r)
811
811
812 if md is not None:
812 if md is not None:
813 # put the tuple back together
813 # put the tuple back together
814 r = (r, md)
814 r = (r, md)
815 return super(JSONFormatter, self)._check_return(r, obj)
815 return super(JSONFormatter, self)._check_return(r, obj)
816
816
817
817
818 class JavascriptFormatter(BaseFormatter):
818 class JavascriptFormatter(BaseFormatter):
819 """A Javascript formatter.
819 """A Javascript formatter.
820
820
821 To define the callables that compute the Javascript representation of
821 To define the callables that compute the Javascript representation of
822 your objects, define a :meth:`_repr_javascript_` method or use the
822 your objects, define a :meth:`_repr_javascript_` method or use the
823 :meth:`for_type` or :meth:`for_type_by_name` methods to register functions
823 :meth:`for_type` or :meth:`for_type_by_name` methods to register functions
824 that handle this.
824 that handle this.
825
825
826 The return value of this formatter should be valid Javascript code and
826 The return value of this formatter should be valid Javascript code and
827 should *not* be enclosed in ```<script>``` tags.
827 should *not* be enclosed in ```<script>``` tags.
828 """
828 """
829 format_type = Unicode('application/javascript')
829 format_type = Unicode('application/javascript')
830
830
831 print_method = ObjectName('_repr_javascript_')
831 print_method = ObjectName('_repr_javascript_')
832
832
833
833
834 class PDFFormatter(BaseFormatter):
834 class PDFFormatter(BaseFormatter):
835 """A PDF formatter.
835 """A PDF formatter.
836
836
837 To define the callables that compute the PDF representation of your
837 To define the callables that compute the PDF representation of your
838 objects, define a :meth:`_repr_pdf_` method or use the :meth:`for_type`
838 objects, define a :meth:`_repr_pdf_` method or use the :meth:`for_type`
839 or :meth:`for_type_by_name` methods to register functions that handle
839 or :meth:`for_type_by_name` methods to register functions that handle
840 this.
840 this.
841
841
842 The return value of this formatter should be raw PDF data, *not*
842 The return value of this formatter should be raw PDF data, *not*
843 base64 encoded.
843 base64 encoded.
844 """
844 """
845 format_type = Unicode('application/pdf')
845 format_type = Unicode('application/pdf')
846
846
847 print_method = ObjectName('_repr_pdf_')
847 print_method = ObjectName('_repr_pdf_')
848
848
849 _return_type = (bytes, unicode_type)
849 _return_type = (bytes, str)
850
850
851 class IPythonDisplayFormatter(BaseFormatter):
851 class IPythonDisplayFormatter(BaseFormatter):
852 """A Formatter for objects that know how to display themselves.
852 """A Formatter for objects that know how to display themselves.
853
853
854 To define the callables that compute the representation of your
854 To define the callables that compute the representation of your
855 objects, define a :meth:`_ipython_display_` method or use the :meth:`for_type`
855 objects, define a :meth:`_ipython_display_` method or use the :meth:`for_type`
856 or :meth:`for_type_by_name` methods to register functions that handle
856 or :meth:`for_type_by_name` methods to register functions that handle
857 this. Unlike mime-type displays, this method should not return anything,
857 this. Unlike mime-type displays, this method should not return anything,
858 instead calling any appropriate display methods itself.
858 instead calling any appropriate display methods itself.
859
859
860 This display formatter has highest priority.
860 This display formatter has highest priority.
861 If it fires, no other display formatter will be called.
861 If it fires, no other display formatter will be called.
862 """
862 """
863 print_method = ObjectName('_ipython_display_')
863 print_method = ObjectName('_ipython_display_')
864 _return_type = (type(None), bool)
864 _return_type = (type(None), bool)
865
865
866
866
867 @catch_format_error
867 @catch_format_error
868 def __call__(self, obj):
868 def __call__(self, obj):
869 """Compute the format for an object."""
869 """Compute the format for an object."""
870 if self.enabled:
870 if self.enabled:
871 # lookup registered printer
871 # lookup registered printer
872 try:
872 try:
873 printer = self.lookup(obj)
873 printer = self.lookup(obj)
874 except KeyError:
874 except KeyError:
875 pass
875 pass
876 else:
876 else:
877 printer(obj)
877 printer(obj)
878 return True
878 return True
879 # Finally look for special method names
879 # Finally look for special method names
880 method = get_real_method(obj, self.print_method)
880 method = get_real_method(obj, self.print_method)
881 if method is not None:
881 if method is not None:
882 method()
882 method()
883 return True
883 return True
884
884
885
885
886 FormatterABC.register(BaseFormatter)
886 FormatterABC.register(BaseFormatter)
887 FormatterABC.register(PlainTextFormatter)
887 FormatterABC.register(PlainTextFormatter)
888 FormatterABC.register(HTMLFormatter)
888 FormatterABC.register(HTMLFormatter)
889 FormatterABC.register(MarkdownFormatter)
889 FormatterABC.register(MarkdownFormatter)
890 FormatterABC.register(SVGFormatter)
890 FormatterABC.register(SVGFormatter)
891 FormatterABC.register(PNGFormatter)
891 FormatterABC.register(PNGFormatter)
892 FormatterABC.register(PDFFormatter)
892 FormatterABC.register(PDFFormatter)
893 FormatterABC.register(JPEGFormatter)
893 FormatterABC.register(JPEGFormatter)
894 FormatterABC.register(LatexFormatter)
894 FormatterABC.register(LatexFormatter)
895 FormatterABC.register(JSONFormatter)
895 FormatterABC.register(JSONFormatter)
896 FormatterABC.register(JavascriptFormatter)
896 FormatterABC.register(JavascriptFormatter)
897 FormatterABC.register(IPythonDisplayFormatter)
897 FormatterABC.register(IPythonDisplayFormatter)
898
898
899
899
900 def format_display_data(obj, include=None, exclude=None):
900 def format_display_data(obj, include=None, exclude=None):
901 """Return a format data dict for an object.
901 """Return a format data dict for an object.
902
902
903 By default all format types will be computed.
903 By default all format types will be computed.
904
904
905 The following MIME types are currently implemented:
905 The following MIME types are currently implemented:
906
906
907 * text/plain
907 * text/plain
908 * text/html
908 * text/html
909 * text/markdown
909 * text/markdown
910 * text/latex
910 * text/latex
911 * application/json
911 * application/json
912 * application/javascript
912 * application/javascript
913 * application/pdf
913 * application/pdf
914 * image/png
914 * image/png
915 * image/jpeg
915 * image/jpeg
916 * image/svg+xml
916 * image/svg+xml
917
917
918 Parameters
918 Parameters
919 ----------
919 ----------
920 obj : object
920 obj : object
921 The Python object whose format data will be computed.
921 The Python object whose format data will be computed.
922
922
923 Returns
923 Returns
924 -------
924 -------
925 format_dict : dict
925 format_dict : dict
926 A dictionary of key/value pairs, one or each format that was
926 A dictionary of key/value pairs, one or each format that was
927 generated for the object. The keys are the format types, which
927 generated for the object. The keys are the format types, which
928 will usually be MIME type strings and the values and JSON'able
928 will usually be MIME type strings and the values and JSON'able
929 data structure containing the raw data for the representation in
929 data structure containing the raw data for the representation in
930 that format.
930 that format.
931 include : list or tuple, optional
931 include : list or tuple, optional
932 A list of format type strings (MIME types) to include in the
932 A list of format type strings (MIME types) to include in the
933 format data dict. If this is set *only* the format types included
933 format data dict. If this is set *only* the format types included
934 in this list will be computed.
934 in this list will be computed.
935 exclude : list or tuple, optional
935 exclude : list or tuple, optional
936 A list of format type string (MIME types) to exclue in the format
936 A list of format type string (MIME types) to exclue in the format
937 data dict. If this is set all format types will be computed,
937 data dict. If this is set all format types will be computed,
938 except for those included in this argument.
938 except for those included in this argument.
939 """
939 """
940 from IPython.core.interactiveshell import InteractiveShell
940 from IPython.core.interactiveshell import InteractiveShell
941
941
942 return InteractiveShell.instance().display_formatter.format(
942 return InteractiveShell.instance().display_formatter.format(
943 obj,
943 obj,
944 include,
944 include,
945 exclude
945 exclude
946 )
946 )
947
947
@@ -1,910 +1,910 b''
1 """ History related magics and functionality """
1 """ History related magics and functionality """
2
2
3 # Copyright (c) IPython Development Team.
3 # Copyright (c) IPython Development Team.
4 # Distributed under the terms of the Modified BSD License.
4 # Distributed under the terms of the Modified BSD License.
5
5
6
6
7 import atexit
7 import atexit
8 import datetime
8 import datetime
9 import os
9 import os
10 import re
10 import re
11 try:
11 try:
12 import sqlite3
12 import sqlite3
13 except ImportError:
13 except ImportError:
14 try:
14 try:
15 from pysqlite2 import dbapi2 as sqlite3
15 from pysqlite2 import dbapi2 as sqlite3
16 except ImportError:
16 except ImportError:
17 sqlite3 = None
17 sqlite3 = None
18 import threading
18 import threading
19
19
20 from traitlets.config.configurable import LoggingConfigurable
20 from traitlets.config.configurable import LoggingConfigurable
21 from decorator import decorator
21 from decorator import decorator
22 from IPython.utils.decorators import undoc
22 from IPython.utils.decorators import undoc
23 from IPython.utils.path import locate_profile
23 from IPython.utils.path import locate_profile
24 from IPython.utils import py3compat
24 from IPython.utils import py3compat
25 from traitlets import (
25 from traitlets import (
26 Any, Bool, Dict, Instance, Integer, List, Unicode, TraitError,
26 Any, Bool, Dict, Instance, Integer, List, Unicode, TraitError,
27 default, observe,
27 default, observe,
28 )
28 )
29 from warnings import warn
29 from warnings import warn
30
30
31 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
32 # Classes and functions
32 # Classes and functions
33 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
34
34
35 @undoc
35 @undoc
36 class DummyDB(object):
36 class DummyDB(object):
37 """Dummy DB that will act as a black hole for history.
37 """Dummy DB that will act as a black hole for history.
38
38
39 Only used in the absence of sqlite"""
39 Only used in the absence of sqlite"""
40 def execute(*args, **kwargs):
40 def execute(*args, **kwargs):
41 return []
41 return []
42
42
43 def commit(self, *args, **kwargs):
43 def commit(self, *args, **kwargs):
44 pass
44 pass
45
45
46 def __enter__(self, *args, **kwargs):
46 def __enter__(self, *args, **kwargs):
47 pass
47 pass
48
48
49 def __exit__(self, *args, **kwargs):
49 def __exit__(self, *args, **kwargs):
50 pass
50 pass
51
51
52
52
53 @decorator
53 @decorator
54 def needs_sqlite(f, self, *a, **kw):
54 def needs_sqlite(f, self, *a, **kw):
55 """Decorator: return an empty list in the absence of sqlite."""
55 """Decorator: return an empty list in the absence of sqlite."""
56 if sqlite3 is None or not self.enabled:
56 if sqlite3 is None or not self.enabled:
57 return []
57 return []
58 else:
58 else:
59 return f(self, *a, **kw)
59 return f(self, *a, **kw)
60
60
61
61
62 if sqlite3 is not None:
62 if sqlite3 is not None:
63 DatabaseError = sqlite3.DatabaseError
63 DatabaseError = sqlite3.DatabaseError
64 OperationalError = sqlite3.OperationalError
64 OperationalError = sqlite3.OperationalError
65 else:
65 else:
66 @undoc
66 @undoc
67 class DatabaseError(Exception):
67 class DatabaseError(Exception):
68 "Dummy exception when sqlite could not be imported. Should never occur."
68 "Dummy exception when sqlite could not be imported. Should never occur."
69
69
70 @undoc
70 @undoc
71 class OperationalError(Exception):
71 class OperationalError(Exception):
72 "Dummy exception when sqlite could not be imported. Should never occur."
72 "Dummy exception when sqlite could not be imported. Should never occur."
73
73
74 # use 16kB as threshold for whether a corrupt history db should be saved
74 # use 16kB as threshold for whether a corrupt history db should be saved
75 # that should be at least 100 entries or so
75 # that should be at least 100 entries or so
76 _SAVE_DB_SIZE = 16384
76 _SAVE_DB_SIZE = 16384
77
77
78 @decorator
78 @decorator
79 def catch_corrupt_db(f, self, *a, **kw):
79 def catch_corrupt_db(f, self, *a, **kw):
80 """A decorator which wraps HistoryAccessor method calls to catch errors from
80 """A decorator which wraps HistoryAccessor method calls to catch errors from
81 a corrupt SQLite database, move the old database out of the way, and create
81 a corrupt SQLite database, move the old database out of the way, and create
82 a new one.
82 a new one.
83
83
84 We avoid clobbering larger databases because this may be triggered due to filesystem issues,
84 We avoid clobbering larger databases because this may be triggered due to filesystem issues,
85 not just a corrupt file.
85 not just a corrupt file.
86 """
86 """
87 try:
87 try:
88 return f(self, *a, **kw)
88 return f(self, *a, **kw)
89 except (DatabaseError, OperationalError) as e:
89 except (DatabaseError, OperationalError) as e:
90 self._corrupt_db_counter += 1
90 self._corrupt_db_counter += 1
91 self.log.error("Failed to open SQLite history %s (%s).", self.hist_file, e)
91 self.log.error("Failed to open SQLite history %s (%s).", self.hist_file, e)
92 if self.hist_file != ':memory:':
92 if self.hist_file != ':memory:':
93 if self._corrupt_db_counter > self._corrupt_db_limit:
93 if self._corrupt_db_counter > self._corrupt_db_limit:
94 self.hist_file = ':memory:'
94 self.hist_file = ':memory:'
95 self.log.error("Failed to load history too many times, history will not be saved.")
95 self.log.error("Failed to load history too many times, history will not be saved.")
96 elif os.path.isfile(self.hist_file):
96 elif os.path.isfile(self.hist_file):
97 # move the file out of the way
97 # move the file out of the way
98 base, ext = os.path.splitext(self.hist_file)
98 base, ext = os.path.splitext(self.hist_file)
99 size = os.stat(self.hist_file).st_size
99 size = os.stat(self.hist_file).st_size
100 if size >= _SAVE_DB_SIZE:
100 if size >= _SAVE_DB_SIZE:
101 # if there's significant content, avoid clobbering
101 # if there's significant content, avoid clobbering
102 now = datetime.datetime.now().isoformat().replace(':', '.')
102 now = datetime.datetime.now().isoformat().replace(':', '.')
103 newpath = base + '-corrupt-' + now + ext
103 newpath = base + '-corrupt-' + now + ext
104 # don't clobber previous corrupt backups
104 # don't clobber previous corrupt backups
105 for i in range(100):
105 for i in range(100):
106 if not os.path.isfile(newpath):
106 if not os.path.isfile(newpath):
107 break
107 break
108 else:
108 else:
109 newpath = base + '-corrupt-' + now + (u'-%i' % i) + ext
109 newpath = base + '-corrupt-' + now + (u'-%i' % i) + ext
110 else:
110 else:
111 # not much content, possibly empty; don't worry about clobbering
111 # not much content, possibly empty; don't worry about clobbering
112 # maybe we should just delete it?
112 # maybe we should just delete it?
113 newpath = base + '-corrupt' + ext
113 newpath = base + '-corrupt' + ext
114 os.rename(self.hist_file, newpath)
114 os.rename(self.hist_file, newpath)
115 self.log.error("History file was moved to %s and a new file created.", newpath)
115 self.log.error("History file was moved to %s and a new file created.", newpath)
116 self.init_db()
116 self.init_db()
117 return []
117 return []
118 else:
118 else:
119 # Failed with :memory:, something serious is wrong
119 # Failed with :memory:, something serious is wrong
120 raise
120 raise
121
121
122 class HistoryAccessorBase(LoggingConfigurable):
122 class HistoryAccessorBase(LoggingConfigurable):
123 """An abstract class for History Accessors """
123 """An abstract class for History Accessors """
124
124
125 def get_tail(self, n=10, raw=True, output=False, include_latest=False):
125 def get_tail(self, n=10, raw=True, output=False, include_latest=False):
126 raise NotImplementedError
126 raise NotImplementedError
127
127
128 def search(self, pattern="*", raw=True, search_raw=True,
128 def search(self, pattern="*", raw=True, search_raw=True,
129 output=False, n=None, unique=False):
129 output=False, n=None, unique=False):
130 raise NotImplementedError
130 raise NotImplementedError
131
131
132 def get_range(self, session, start=1, stop=None, raw=True,output=False):
132 def get_range(self, session, start=1, stop=None, raw=True,output=False):
133 raise NotImplementedError
133 raise NotImplementedError
134
134
135 def get_range_by_str(self, rangestr, raw=True, output=False):
135 def get_range_by_str(self, rangestr, raw=True, output=False):
136 raise NotImplementedError
136 raise NotImplementedError
137
137
138
138
139 class HistoryAccessor(HistoryAccessorBase):
139 class HistoryAccessor(HistoryAccessorBase):
140 """Access the history database without adding to it.
140 """Access the history database without adding to it.
141
141
142 This is intended for use by standalone history tools. IPython shells use
142 This is intended for use by standalone history tools. IPython shells use
143 HistoryManager, below, which is a subclass of this."""
143 HistoryManager, below, which is a subclass of this."""
144
144
145 # counter for init_db retries, so we don't keep trying over and over
145 # counter for init_db retries, so we don't keep trying over and over
146 _corrupt_db_counter = 0
146 _corrupt_db_counter = 0
147 # after two failures, fallback on :memory:
147 # after two failures, fallback on :memory:
148 _corrupt_db_limit = 2
148 _corrupt_db_limit = 2
149
149
150 # String holding the path to the history file
150 # String holding the path to the history file
151 hist_file = Unicode(
151 hist_file = Unicode(
152 help="""Path to file to use for SQLite history database.
152 help="""Path to file to use for SQLite history database.
153
153
154 By default, IPython will put the history database in the IPython
154 By default, IPython will put the history database in the IPython
155 profile directory. If you would rather share one history among
155 profile directory. If you would rather share one history among
156 profiles, you can set this value in each, so that they are consistent.
156 profiles, you can set this value in each, so that they are consistent.
157
157
158 Due to an issue with fcntl, SQLite is known to misbehave on some NFS
158 Due to an issue with fcntl, SQLite is known to misbehave on some NFS
159 mounts. If you see IPython hanging, try setting this to something on a
159 mounts. If you see IPython hanging, try setting this to something on a
160 local disk, e.g::
160 local disk, e.g::
161
161
162 ipython --HistoryManager.hist_file=/tmp/ipython_hist.sqlite
162 ipython --HistoryManager.hist_file=/tmp/ipython_hist.sqlite
163
163
164 you can also use the specific value `:memory:` (including the colon
164 you can also use the specific value `:memory:` (including the colon
165 at both end but not the back ticks), to avoid creating an history file.
165 at both end but not the back ticks), to avoid creating an history file.
166
166
167 """).tag(config=True)
167 """).tag(config=True)
168
168
169 enabled = Bool(True,
169 enabled = Bool(True,
170 help="""enable the SQLite history
170 help="""enable the SQLite history
171
171
172 set enabled=False to disable the SQLite history,
172 set enabled=False to disable the SQLite history,
173 in which case there will be no stored history, no SQLite connection,
173 in which case there will be no stored history, no SQLite connection,
174 and no background saving thread. This may be necessary in some
174 and no background saving thread. This may be necessary in some
175 threaded environments where IPython is embedded.
175 threaded environments where IPython is embedded.
176 """
176 """
177 ).tag(config=True)
177 ).tag(config=True)
178
178
179 connection_options = Dict(
179 connection_options = Dict(
180 help="""Options for configuring the SQLite connection
180 help="""Options for configuring the SQLite connection
181
181
182 These options are passed as keyword args to sqlite3.connect
182 These options are passed as keyword args to sqlite3.connect
183 when establishing database conenctions.
183 when establishing database conenctions.
184 """
184 """
185 ).tag(config=True)
185 ).tag(config=True)
186
186
187 # The SQLite database
187 # The SQLite database
188 db = Any()
188 db = Any()
189 @observe('db')
189 @observe('db')
190 def _db_changed(self, change):
190 def _db_changed(self, change):
191 """validate the db, since it can be an Instance of two different types"""
191 """validate the db, since it can be an Instance of two different types"""
192 new = change['new']
192 new = change['new']
193 connection_types = (DummyDB,)
193 connection_types = (DummyDB,)
194 if sqlite3 is not None:
194 if sqlite3 is not None:
195 connection_types = (DummyDB, sqlite3.Connection)
195 connection_types = (DummyDB, sqlite3.Connection)
196 if not isinstance(new, connection_types):
196 if not isinstance(new, connection_types):
197 msg = "%s.db must be sqlite3 Connection or DummyDB, not %r" % \
197 msg = "%s.db must be sqlite3 Connection or DummyDB, not %r" % \
198 (self.__class__.__name__, new)
198 (self.__class__.__name__, new)
199 raise TraitError(msg)
199 raise TraitError(msg)
200
200
201 def __init__(self, profile='default', hist_file=u'', **traits):
201 def __init__(self, profile='default', hist_file=u'', **traits):
202 """Create a new history accessor.
202 """Create a new history accessor.
203
203
204 Parameters
204 Parameters
205 ----------
205 ----------
206 profile : str
206 profile : str
207 The name of the profile from which to open history.
207 The name of the profile from which to open history.
208 hist_file : str
208 hist_file : str
209 Path to an SQLite history database stored by IPython. If specified,
209 Path to an SQLite history database stored by IPython. If specified,
210 hist_file overrides profile.
210 hist_file overrides profile.
211 config : :class:`~traitlets.config.loader.Config`
211 config : :class:`~traitlets.config.loader.Config`
212 Config object. hist_file can also be set through this.
212 Config object. hist_file can also be set through this.
213 """
213 """
214 # We need a pointer back to the shell for various tasks.
214 # We need a pointer back to the shell for various tasks.
215 super(HistoryAccessor, self).__init__(**traits)
215 super(HistoryAccessor, self).__init__(**traits)
216 # defer setting hist_file from kwarg until after init,
216 # defer setting hist_file from kwarg until after init,
217 # otherwise the default kwarg value would clobber any value
217 # otherwise the default kwarg value would clobber any value
218 # set by config
218 # set by config
219 if hist_file:
219 if hist_file:
220 self.hist_file = hist_file
220 self.hist_file = hist_file
221
221
222 if self.hist_file == u'':
222 if self.hist_file == u'':
223 # No one has set the hist_file, yet.
223 # No one has set the hist_file, yet.
224 self.hist_file = self._get_hist_file_name(profile)
224 self.hist_file = self._get_hist_file_name(profile)
225
225
226 if sqlite3 is None and self.enabled:
226 if sqlite3 is None and self.enabled:
227 warn("IPython History requires SQLite, your history will not be saved")
227 warn("IPython History requires SQLite, your history will not be saved")
228 self.enabled = False
228 self.enabled = False
229
229
230 self.init_db()
230 self.init_db()
231
231
232 def _get_hist_file_name(self, profile='default'):
232 def _get_hist_file_name(self, profile='default'):
233 """Find the history file for the given profile name.
233 """Find the history file for the given profile name.
234
234
235 This is overridden by the HistoryManager subclass, to use the shell's
235 This is overridden by the HistoryManager subclass, to use the shell's
236 active profile.
236 active profile.
237
237
238 Parameters
238 Parameters
239 ----------
239 ----------
240 profile : str
240 profile : str
241 The name of a profile which has a history file.
241 The name of a profile which has a history file.
242 """
242 """
243 return os.path.join(locate_profile(profile), 'history.sqlite')
243 return os.path.join(locate_profile(profile), 'history.sqlite')
244
244
245 @catch_corrupt_db
245 @catch_corrupt_db
246 def init_db(self):
246 def init_db(self):
247 """Connect to the database, and create tables if necessary."""
247 """Connect to the database, and create tables if necessary."""
248 if not self.enabled:
248 if not self.enabled:
249 self.db = DummyDB()
249 self.db = DummyDB()
250 return
250 return
251
251
252 # use detect_types so that timestamps return datetime objects
252 # use detect_types so that timestamps return datetime objects
253 kwargs = dict(detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
253 kwargs = dict(detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
254 kwargs.update(self.connection_options)
254 kwargs.update(self.connection_options)
255 self.db = sqlite3.connect(self.hist_file, **kwargs)
255 self.db = sqlite3.connect(self.hist_file, **kwargs)
256 self.db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer
256 self.db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer
257 primary key autoincrement, start timestamp,
257 primary key autoincrement, start timestamp,
258 end timestamp, num_cmds integer, remark text)""")
258 end timestamp, num_cmds integer, remark text)""")
259 self.db.execute("""CREATE TABLE IF NOT EXISTS history
259 self.db.execute("""CREATE TABLE IF NOT EXISTS history
260 (session integer, line integer, source text, source_raw text,
260 (session integer, line integer, source text, source_raw text,
261 PRIMARY KEY (session, line))""")
261 PRIMARY KEY (session, line))""")
262 # Output history is optional, but ensure the table's there so it can be
262 # Output history is optional, but ensure the table's there so it can be
263 # enabled later.
263 # enabled later.
264 self.db.execute("""CREATE TABLE IF NOT EXISTS output_history
264 self.db.execute("""CREATE TABLE IF NOT EXISTS output_history
265 (session integer, line integer, output text,
265 (session integer, line integer, output text,
266 PRIMARY KEY (session, line))""")
266 PRIMARY KEY (session, line))""")
267 self.db.commit()
267 self.db.commit()
268 # success! reset corrupt db count
268 # success! reset corrupt db count
269 self._corrupt_db_counter = 0
269 self._corrupt_db_counter = 0
270
270
271 def writeout_cache(self):
271 def writeout_cache(self):
272 """Overridden by HistoryManager to dump the cache before certain
272 """Overridden by HistoryManager to dump the cache before certain
273 database lookups."""
273 database lookups."""
274 pass
274 pass
275
275
276 ## -------------------------------
276 ## -------------------------------
277 ## Methods for retrieving history:
277 ## Methods for retrieving history:
278 ## -------------------------------
278 ## -------------------------------
279 def _run_sql(self, sql, params, raw=True, output=False):
279 def _run_sql(self, sql, params, raw=True, output=False):
280 """Prepares and runs an SQL query for the history database.
280 """Prepares and runs an SQL query for the history database.
281
281
282 Parameters
282 Parameters
283 ----------
283 ----------
284 sql : str
284 sql : str
285 Any filtering expressions to go after SELECT ... FROM ...
285 Any filtering expressions to go after SELECT ... FROM ...
286 params : tuple
286 params : tuple
287 Parameters passed to the SQL query (to replace "?")
287 Parameters passed to the SQL query (to replace "?")
288 raw, output : bool
288 raw, output : bool
289 See :meth:`get_range`
289 See :meth:`get_range`
290
290
291 Returns
291 Returns
292 -------
292 -------
293 Tuples as :meth:`get_range`
293 Tuples as :meth:`get_range`
294 """
294 """
295 toget = 'source_raw' if raw else 'source'
295 toget = 'source_raw' if raw else 'source'
296 sqlfrom = "history"
296 sqlfrom = "history"
297 if output:
297 if output:
298 sqlfrom = "history LEFT JOIN output_history USING (session, line)"
298 sqlfrom = "history LEFT JOIN output_history USING (session, line)"
299 toget = "history.%s, output_history.output" % toget
299 toget = "history.%s, output_history.output" % toget
300 cur = self.db.execute("SELECT session, line, %s FROM %s " %\
300 cur = self.db.execute("SELECT session, line, %s FROM %s " %\
301 (toget, sqlfrom) + sql, params)
301 (toget, sqlfrom) + sql, params)
302 if output: # Regroup into 3-tuples, and parse JSON
302 if output: # Regroup into 3-tuples, and parse JSON
303 return ((ses, lin, (inp, out)) for ses, lin, inp, out in cur)
303 return ((ses, lin, (inp, out)) for ses, lin, inp, out in cur)
304 return cur
304 return cur
305
305
306 @needs_sqlite
306 @needs_sqlite
307 @catch_corrupt_db
307 @catch_corrupt_db
308 def get_session_info(self, session):
308 def get_session_info(self, session):
309 """Get info about a session.
309 """Get info about a session.
310
310
311 Parameters
311 Parameters
312 ----------
312 ----------
313
313
314 session : int
314 session : int
315 Session number to retrieve.
315 Session number to retrieve.
316
316
317 Returns
317 Returns
318 -------
318 -------
319
319
320 session_id : int
320 session_id : int
321 Session ID number
321 Session ID number
322 start : datetime
322 start : datetime
323 Timestamp for the start of the session.
323 Timestamp for the start of the session.
324 end : datetime
324 end : datetime
325 Timestamp for the end of the session, or None if IPython crashed.
325 Timestamp for the end of the session, or None if IPython crashed.
326 num_cmds : int
326 num_cmds : int
327 Number of commands run, or None if IPython crashed.
327 Number of commands run, or None if IPython crashed.
328 remark : unicode
328 remark : unicode
329 A manually set description.
329 A manually set description.
330 """
330 """
331 query = "SELECT * from sessions where session == ?"
331 query = "SELECT * from sessions where session == ?"
332 return self.db.execute(query, (session,)).fetchone()
332 return self.db.execute(query, (session,)).fetchone()
333
333
334 @catch_corrupt_db
334 @catch_corrupt_db
335 def get_last_session_id(self):
335 def get_last_session_id(self):
336 """Get the last session ID currently in the database.
336 """Get the last session ID currently in the database.
337
337
338 Within IPython, this should be the same as the value stored in
338 Within IPython, this should be the same as the value stored in
339 :attr:`HistoryManager.session_number`.
339 :attr:`HistoryManager.session_number`.
340 """
340 """
341 for record in self.get_tail(n=1, include_latest=True):
341 for record in self.get_tail(n=1, include_latest=True):
342 return record[0]
342 return record[0]
343
343
344 @catch_corrupt_db
344 @catch_corrupt_db
345 def get_tail(self, n=10, raw=True, output=False, include_latest=False):
345 def get_tail(self, n=10, raw=True, output=False, include_latest=False):
346 """Get the last n lines from the history database.
346 """Get the last n lines from the history database.
347
347
348 Parameters
348 Parameters
349 ----------
349 ----------
350 n : int
350 n : int
351 The number of lines to get
351 The number of lines to get
352 raw, output : bool
352 raw, output : bool
353 See :meth:`get_range`
353 See :meth:`get_range`
354 include_latest : bool
354 include_latest : bool
355 If False (default), n+1 lines are fetched, and the latest one
355 If False (default), n+1 lines are fetched, and the latest one
356 is discarded. This is intended to be used where the function
356 is discarded. This is intended to be used where the function
357 is called by a user command, which it should not return.
357 is called by a user command, which it should not return.
358
358
359 Returns
359 Returns
360 -------
360 -------
361 Tuples as :meth:`get_range`
361 Tuples as :meth:`get_range`
362 """
362 """
363 self.writeout_cache()
363 self.writeout_cache()
364 if not include_latest:
364 if not include_latest:
365 n += 1
365 n += 1
366 cur = self._run_sql("ORDER BY session DESC, line DESC LIMIT ?",
366 cur = self._run_sql("ORDER BY session DESC, line DESC LIMIT ?",
367 (n,), raw=raw, output=output)
367 (n,), raw=raw, output=output)
368 if not include_latest:
368 if not include_latest:
369 return reversed(list(cur)[1:])
369 return reversed(list(cur)[1:])
370 return reversed(list(cur))
370 return reversed(list(cur))
371
371
372 @catch_corrupt_db
372 @catch_corrupt_db
373 def search(self, pattern="*", raw=True, search_raw=True,
373 def search(self, pattern="*", raw=True, search_raw=True,
374 output=False, n=None, unique=False):
374 output=False, n=None, unique=False):
375 """Search the database using unix glob-style matching (wildcards
375 """Search the database using unix glob-style matching (wildcards
376 * and ?).
376 * and ?).
377
377
378 Parameters
378 Parameters
379 ----------
379 ----------
380 pattern : str
380 pattern : str
381 The wildcarded pattern to match when searching
381 The wildcarded pattern to match when searching
382 search_raw : bool
382 search_raw : bool
383 If True, search the raw input, otherwise, the parsed input
383 If True, search the raw input, otherwise, the parsed input
384 raw, output : bool
384 raw, output : bool
385 See :meth:`get_range`
385 See :meth:`get_range`
386 n : None or int
386 n : None or int
387 If an integer is given, it defines the limit of
387 If an integer is given, it defines the limit of
388 returned entries.
388 returned entries.
389 unique : bool
389 unique : bool
390 When it is true, return only unique entries.
390 When it is true, return only unique entries.
391
391
392 Returns
392 Returns
393 -------
393 -------
394 Tuples as :meth:`get_range`
394 Tuples as :meth:`get_range`
395 """
395 """
396 tosearch = "source_raw" if search_raw else "source"
396 tosearch = "source_raw" if search_raw else "source"
397 if output:
397 if output:
398 tosearch = "history." + tosearch
398 tosearch = "history." + tosearch
399 self.writeout_cache()
399 self.writeout_cache()
400 sqlform = "WHERE %s GLOB ?" % tosearch
400 sqlform = "WHERE %s GLOB ?" % tosearch
401 params = (pattern,)
401 params = (pattern,)
402 if unique:
402 if unique:
403 sqlform += ' GROUP BY {0}'.format(tosearch)
403 sqlform += ' GROUP BY {0}'.format(tosearch)
404 if n is not None:
404 if n is not None:
405 sqlform += " ORDER BY session DESC, line DESC LIMIT ?"
405 sqlform += " ORDER BY session DESC, line DESC LIMIT ?"
406 params += (n,)
406 params += (n,)
407 elif unique:
407 elif unique:
408 sqlform += " ORDER BY session, line"
408 sqlform += " ORDER BY session, line"
409 cur = self._run_sql(sqlform, params, raw=raw, output=output)
409 cur = self._run_sql(sqlform, params, raw=raw, output=output)
410 if n is not None:
410 if n is not None:
411 return reversed(list(cur))
411 return reversed(list(cur))
412 return cur
412 return cur
413
413
414 @catch_corrupt_db
414 @catch_corrupt_db
415 def get_range(self, session, start=1, stop=None, raw=True,output=False):
415 def get_range(self, session, start=1, stop=None, raw=True,output=False):
416 """Retrieve input by session.
416 """Retrieve input by session.
417
417
418 Parameters
418 Parameters
419 ----------
419 ----------
420 session : int
420 session : int
421 Session number to retrieve.
421 Session number to retrieve.
422 start : int
422 start : int
423 First line to retrieve.
423 First line to retrieve.
424 stop : int
424 stop : int
425 End of line range (excluded from output itself). If None, retrieve
425 End of line range (excluded from output itself). If None, retrieve
426 to the end of the session.
426 to the end of the session.
427 raw : bool
427 raw : bool
428 If True, return untranslated input
428 If True, return untranslated input
429 output : bool
429 output : bool
430 If True, attempt to include output. This will be 'real' Python
430 If True, attempt to include output. This will be 'real' Python
431 objects for the current session, or text reprs from previous
431 objects for the current session, or text reprs from previous
432 sessions if db_log_output was enabled at the time. Where no output
432 sessions if db_log_output was enabled at the time. Where no output
433 is found, None is used.
433 is found, None is used.
434
434
435 Returns
435 Returns
436 -------
436 -------
437 entries
437 entries
438 An iterator over the desired lines. Each line is a 3-tuple, either
438 An iterator over the desired lines. Each line is a 3-tuple, either
439 (session, line, input) if output is False, or
439 (session, line, input) if output is False, or
440 (session, line, (input, output)) if output is True.
440 (session, line, (input, output)) if output is True.
441 """
441 """
442 if stop:
442 if stop:
443 lineclause = "line >= ? AND line < ?"
443 lineclause = "line >= ? AND line < ?"
444 params = (session, start, stop)
444 params = (session, start, stop)
445 else:
445 else:
446 lineclause = "line>=?"
446 lineclause = "line>=?"
447 params = (session, start)
447 params = (session, start)
448
448
449 return self._run_sql("WHERE session==? AND %s" % lineclause,
449 return self._run_sql("WHERE session==? AND %s" % lineclause,
450 params, raw=raw, output=output)
450 params, raw=raw, output=output)
451
451
452 def get_range_by_str(self, rangestr, raw=True, output=False):
452 def get_range_by_str(self, rangestr, raw=True, output=False):
453 """Get lines of history from a string of ranges, as used by magic
453 """Get lines of history from a string of ranges, as used by magic
454 commands %hist, %save, %macro, etc.
454 commands %hist, %save, %macro, etc.
455
455
456 Parameters
456 Parameters
457 ----------
457 ----------
458 rangestr : str
458 rangestr : str
459 A string specifying ranges, e.g. "5 ~2/1-4". See
459 A string specifying ranges, e.g. "5 ~2/1-4". See
460 :func:`magic_history` for full details.
460 :func:`magic_history` for full details.
461 raw, output : bool
461 raw, output : bool
462 As :meth:`get_range`
462 As :meth:`get_range`
463
463
464 Returns
464 Returns
465 -------
465 -------
466 Tuples as :meth:`get_range`
466 Tuples as :meth:`get_range`
467 """
467 """
468 for sess, s, e in extract_hist_ranges(rangestr):
468 for sess, s, e in extract_hist_ranges(rangestr):
469 for line in self.get_range(sess, s, e, raw=raw, output=output):
469 for line in self.get_range(sess, s, e, raw=raw, output=output):
470 yield line
470 yield line
471
471
472
472
473 class HistoryManager(HistoryAccessor):
473 class HistoryManager(HistoryAccessor):
474 """A class to organize all history-related functionality in one place.
474 """A class to organize all history-related functionality in one place.
475 """
475 """
476 # Public interface
476 # Public interface
477
477
478 # An instance of the IPython shell we are attached to
478 # An instance of the IPython shell we are attached to
479 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
479 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
480 allow_none=True)
480 allow_none=True)
481 # Lists to hold processed and raw history. These start with a blank entry
481 # Lists to hold processed and raw history. These start with a blank entry
482 # so that we can index them starting from 1
482 # so that we can index them starting from 1
483 input_hist_parsed = List([""])
483 input_hist_parsed = List([""])
484 input_hist_raw = List([""])
484 input_hist_raw = List([""])
485 # A list of directories visited during session
485 # A list of directories visited during session
486 dir_hist = List()
486 dir_hist = List()
487 @default('dir_hist')
487 @default('dir_hist')
488 def _dir_hist_default(self):
488 def _dir_hist_default(self):
489 try:
489 try:
490 return [py3compat.getcwd()]
490 return [os.getcwd()]
491 except OSError:
491 except OSError:
492 return []
492 return []
493
493
494 # A dict of output history, keyed with ints from the shell's
494 # A dict of output history, keyed with ints from the shell's
495 # execution count.
495 # execution count.
496 output_hist = Dict()
496 output_hist = Dict()
497 # The text/plain repr of outputs.
497 # The text/plain repr of outputs.
498 output_hist_reprs = Dict()
498 output_hist_reprs = Dict()
499
499
500 # The number of the current session in the history database
500 # The number of the current session in the history database
501 session_number = Integer()
501 session_number = Integer()
502
502
503 db_log_output = Bool(False,
503 db_log_output = Bool(False,
504 help="Should the history database include output? (default: no)"
504 help="Should the history database include output? (default: no)"
505 ).tag(config=True)
505 ).tag(config=True)
506 db_cache_size = Integer(0,
506 db_cache_size = Integer(0,
507 help="Write to database every x commands (higher values save disk access & power).\n"
507 help="Write to database every x commands (higher values save disk access & power).\n"
508 "Values of 1 or less effectively disable caching."
508 "Values of 1 or less effectively disable caching."
509 ).tag(config=True)
509 ).tag(config=True)
510 # The input and output caches
510 # The input and output caches
511 db_input_cache = List()
511 db_input_cache = List()
512 db_output_cache = List()
512 db_output_cache = List()
513
513
514 # History saving in separate thread
514 # History saving in separate thread
515 save_thread = Instance('IPython.core.history.HistorySavingThread',
515 save_thread = Instance('IPython.core.history.HistorySavingThread',
516 allow_none=True)
516 allow_none=True)
517 try: # Event is a function returning an instance of _Event...
517 try: # Event is a function returning an instance of _Event...
518 save_flag = Instance(threading._Event, allow_none=True)
518 save_flag = Instance(threading._Event, allow_none=True)
519 except AttributeError: # ...until Python 3.3, when it's a class.
519 except AttributeError: # ...until Python 3.3, when it's a class.
520 save_flag = Instance(threading.Event, allow_none=True)
520 save_flag = Instance(threading.Event, allow_none=True)
521
521
522 # Private interface
522 # Private interface
523 # Variables used to store the three last inputs from the user. On each new
523 # Variables used to store the three last inputs from the user. On each new
524 # history update, we populate the user's namespace with these, shifted as
524 # history update, we populate the user's namespace with these, shifted as
525 # necessary.
525 # necessary.
526 _i00 = Unicode(u'')
526 _i00 = Unicode(u'')
527 _i = Unicode(u'')
527 _i = Unicode(u'')
528 _ii = Unicode(u'')
528 _ii = Unicode(u'')
529 _iii = Unicode(u'')
529 _iii = Unicode(u'')
530
530
531 # A regex matching all forms of the exit command, so that we don't store
531 # A regex matching all forms of the exit command, so that we don't store
532 # them in the history (it's annoying to rewind the first entry and land on
532 # them in the history (it's annoying to rewind the first entry and land on
533 # an exit call).
533 # an exit call).
534 _exit_re = re.compile(r"(exit|quit)(\s*\(.*\))?$")
534 _exit_re = re.compile(r"(exit|quit)(\s*\(.*\))?$")
535
535
536 def __init__(self, shell=None, config=None, **traits):
536 def __init__(self, shell=None, config=None, **traits):
537 """Create a new history manager associated with a shell instance.
537 """Create a new history manager associated with a shell instance.
538 """
538 """
539 # We need a pointer back to the shell for various tasks.
539 # We need a pointer back to the shell for various tasks.
540 super(HistoryManager, self).__init__(shell=shell, config=config,
540 super(HistoryManager, self).__init__(shell=shell, config=config,
541 **traits)
541 **traits)
542 self.save_flag = threading.Event()
542 self.save_flag = threading.Event()
543 self.db_input_cache_lock = threading.Lock()
543 self.db_input_cache_lock = threading.Lock()
544 self.db_output_cache_lock = threading.Lock()
544 self.db_output_cache_lock = threading.Lock()
545
545
546 try:
546 try:
547 self.new_session()
547 self.new_session()
548 except OperationalError:
548 except OperationalError:
549 self.log.error("Failed to create history session in %s. History will not be saved.",
549 self.log.error("Failed to create history session in %s. History will not be saved.",
550 self.hist_file, exc_info=True)
550 self.hist_file, exc_info=True)
551 self.hist_file = ':memory:'
551 self.hist_file = ':memory:'
552
552
553 if self.enabled and self.hist_file != ':memory:':
553 if self.enabled and self.hist_file != ':memory:':
554 self.save_thread = HistorySavingThread(self)
554 self.save_thread = HistorySavingThread(self)
555 self.save_thread.start()
555 self.save_thread.start()
556
556
557 def _get_hist_file_name(self, profile=None):
557 def _get_hist_file_name(self, profile=None):
558 """Get default history file name based on the Shell's profile.
558 """Get default history file name based on the Shell's profile.
559
559
560 The profile parameter is ignored, but must exist for compatibility with
560 The profile parameter is ignored, but must exist for compatibility with
561 the parent class."""
561 the parent class."""
562 profile_dir = self.shell.profile_dir.location
562 profile_dir = self.shell.profile_dir.location
563 return os.path.join(profile_dir, 'history.sqlite')
563 return os.path.join(profile_dir, 'history.sqlite')
564
564
565 @needs_sqlite
565 @needs_sqlite
566 def new_session(self, conn=None):
566 def new_session(self, conn=None):
567 """Get a new session number."""
567 """Get a new session number."""
568 if conn is None:
568 if conn is None:
569 conn = self.db
569 conn = self.db
570
570
571 with conn:
571 with conn:
572 cur = conn.execute("""INSERT INTO sessions VALUES (NULL, ?, NULL,
572 cur = conn.execute("""INSERT INTO sessions VALUES (NULL, ?, NULL,
573 NULL, "") """, (datetime.datetime.now(),))
573 NULL, "") """, (datetime.datetime.now(),))
574 self.session_number = cur.lastrowid
574 self.session_number = cur.lastrowid
575
575
576 def end_session(self):
576 def end_session(self):
577 """Close the database session, filling in the end time and line count."""
577 """Close the database session, filling in the end time and line count."""
578 self.writeout_cache()
578 self.writeout_cache()
579 with self.db:
579 with self.db:
580 self.db.execute("""UPDATE sessions SET end=?, num_cmds=? WHERE
580 self.db.execute("""UPDATE sessions SET end=?, num_cmds=? WHERE
581 session==?""", (datetime.datetime.now(),
581 session==?""", (datetime.datetime.now(),
582 len(self.input_hist_parsed)-1, self.session_number))
582 len(self.input_hist_parsed)-1, self.session_number))
583 self.session_number = 0
583 self.session_number = 0
584
584
585 def name_session(self, name):
585 def name_session(self, name):
586 """Give the current session a name in the history database."""
586 """Give the current session a name in the history database."""
587 with self.db:
587 with self.db:
588 self.db.execute("UPDATE sessions SET remark=? WHERE session==?",
588 self.db.execute("UPDATE sessions SET remark=? WHERE session==?",
589 (name, self.session_number))
589 (name, self.session_number))
590
590
591 def reset(self, new_session=True):
591 def reset(self, new_session=True):
592 """Clear the session history, releasing all object references, and
592 """Clear the session history, releasing all object references, and
593 optionally open a new session."""
593 optionally open a new session."""
594 self.output_hist.clear()
594 self.output_hist.clear()
595 # The directory history can't be completely empty
595 # The directory history can't be completely empty
596 self.dir_hist[:] = [py3compat.getcwd()]
596 self.dir_hist[:] = [os.getcwd()]
597
597
598 if new_session:
598 if new_session:
599 if self.session_number:
599 if self.session_number:
600 self.end_session()
600 self.end_session()
601 self.input_hist_parsed[:] = [""]
601 self.input_hist_parsed[:] = [""]
602 self.input_hist_raw[:] = [""]
602 self.input_hist_raw[:] = [""]
603 self.new_session()
603 self.new_session()
604
604
605 # ------------------------------
605 # ------------------------------
606 # Methods for retrieving history
606 # Methods for retrieving history
607 # ------------------------------
607 # ------------------------------
608 def get_session_info(self, session=0):
608 def get_session_info(self, session=0):
609 """Get info about a session.
609 """Get info about a session.
610
610
611 Parameters
611 Parameters
612 ----------
612 ----------
613
613
614 session : int
614 session : int
615 Session number to retrieve. The current session is 0, and negative
615 Session number to retrieve. The current session is 0, and negative
616 numbers count back from current session, so -1 is the previous session.
616 numbers count back from current session, so -1 is the previous session.
617
617
618 Returns
618 Returns
619 -------
619 -------
620
620
621 session_id : int
621 session_id : int
622 Session ID number
622 Session ID number
623 start : datetime
623 start : datetime
624 Timestamp for the start of the session.
624 Timestamp for the start of the session.
625 end : datetime
625 end : datetime
626 Timestamp for the end of the session, or None if IPython crashed.
626 Timestamp for the end of the session, or None if IPython crashed.
627 num_cmds : int
627 num_cmds : int
628 Number of commands run, or None if IPython crashed.
628 Number of commands run, or None if IPython crashed.
629 remark : unicode
629 remark : unicode
630 A manually set description.
630 A manually set description.
631 """
631 """
632 if session <= 0:
632 if session <= 0:
633 session += self.session_number
633 session += self.session_number
634
634
635 return super(HistoryManager, self).get_session_info(session=session)
635 return super(HistoryManager, self).get_session_info(session=session)
636
636
637 def _get_range_session(self, start=1, stop=None, raw=True, output=False):
637 def _get_range_session(self, start=1, stop=None, raw=True, output=False):
638 """Get input and output history from the current session. Called by
638 """Get input and output history from the current session. Called by
639 get_range, and takes similar parameters."""
639 get_range, and takes similar parameters."""
640 input_hist = self.input_hist_raw if raw else self.input_hist_parsed
640 input_hist = self.input_hist_raw if raw else self.input_hist_parsed
641
641
642 n = len(input_hist)
642 n = len(input_hist)
643 if start < 0:
643 if start < 0:
644 start += n
644 start += n
645 if not stop or (stop > n):
645 if not stop or (stop > n):
646 stop = n
646 stop = n
647 elif stop < 0:
647 elif stop < 0:
648 stop += n
648 stop += n
649
649
650 for i in range(start, stop):
650 for i in range(start, stop):
651 if output:
651 if output:
652 line = (input_hist[i], self.output_hist_reprs.get(i))
652 line = (input_hist[i], self.output_hist_reprs.get(i))
653 else:
653 else:
654 line = input_hist[i]
654 line = input_hist[i]
655 yield (0, i, line)
655 yield (0, i, line)
656
656
657 def get_range(self, session=0, start=1, stop=None, raw=True,output=False):
657 def get_range(self, session=0, start=1, stop=None, raw=True,output=False):
658 """Retrieve input by session.
658 """Retrieve input by session.
659
659
660 Parameters
660 Parameters
661 ----------
661 ----------
662 session : int
662 session : int
663 Session number to retrieve. The current session is 0, and negative
663 Session number to retrieve. The current session is 0, and negative
664 numbers count back from current session, so -1 is previous session.
664 numbers count back from current session, so -1 is previous session.
665 start : int
665 start : int
666 First line to retrieve.
666 First line to retrieve.
667 stop : int
667 stop : int
668 End of line range (excluded from output itself). If None, retrieve
668 End of line range (excluded from output itself). If None, retrieve
669 to the end of the session.
669 to the end of the session.
670 raw : bool
670 raw : bool
671 If True, return untranslated input
671 If True, return untranslated input
672 output : bool
672 output : bool
673 If True, attempt to include output. This will be 'real' Python
673 If True, attempt to include output. This will be 'real' Python
674 objects for the current session, or text reprs from previous
674 objects for the current session, or text reprs from previous
675 sessions if db_log_output was enabled at the time. Where no output
675 sessions if db_log_output was enabled at the time. Where no output
676 is found, None is used.
676 is found, None is used.
677
677
678 Returns
678 Returns
679 -------
679 -------
680 entries
680 entries
681 An iterator over the desired lines. Each line is a 3-tuple, either
681 An iterator over the desired lines. Each line is a 3-tuple, either
682 (session, line, input) if output is False, or
682 (session, line, input) if output is False, or
683 (session, line, (input, output)) if output is True.
683 (session, line, (input, output)) if output is True.
684 """
684 """
685 if session <= 0:
685 if session <= 0:
686 session += self.session_number
686 session += self.session_number
687 if session==self.session_number: # Current session
687 if session==self.session_number: # Current session
688 return self._get_range_session(start, stop, raw, output)
688 return self._get_range_session(start, stop, raw, output)
689 return super(HistoryManager, self).get_range(session, start, stop, raw,
689 return super(HistoryManager, self).get_range(session, start, stop, raw,
690 output)
690 output)
691
691
692 ## ----------------------------
692 ## ----------------------------
693 ## Methods for storing history:
693 ## Methods for storing history:
694 ## ----------------------------
694 ## ----------------------------
695 def store_inputs(self, line_num, source, source_raw=None):
695 def store_inputs(self, line_num, source, source_raw=None):
696 """Store source and raw input in history and create input cache
696 """Store source and raw input in history and create input cache
697 variables ``_i*``.
697 variables ``_i*``.
698
698
699 Parameters
699 Parameters
700 ----------
700 ----------
701 line_num : int
701 line_num : int
702 The prompt number of this input.
702 The prompt number of this input.
703
703
704 source : str
704 source : str
705 Python input.
705 Python input.
706
706
707 source_raw : str, optional
707 source_raw : str, optional
708 If given, this is the raw input without any IPython transformations
708 If given, this is the raw input without any IPython transformations
709 applied to it. If not given, ``source`` is used.
709 applied to it. If not given, ``source`` is used.
710 """
710 """
711 if source_raw is None:
711 if source_raw is None:
712 source_raw = source
712 source_raw = source
713 source = source.rstrip('\n')
713 source = source.rstrip('\n')
714 source_raw = source_raw.rstrip('\n')
714 source_raw = source_raw.rstrip('\n')
715
715
716 # do not store exit/quit commands
716 # do not store exit/quit commands
717 if self._exit_re.match(source_raw.strip()):
717 if self._exit_re.match(source_raw.strip()):
718 return
718 return
719
719
720 self.input_hist_parsed.append(source)
720 self.input_hist_parsed.append(source)
721 self.input_hist_raw.append(source_raw)
721 self.input_hist_raw.append(source_raw)
722
722
723 with self.db_input_cache_lock:
723 with self.db_input_cache_lock:
724 self.db_input_cache.append((line_num, source, source_raw))
724 self.db_input_cache.append((line_num, source, source_raw))
725 # Trigger to flush cache and write to DB.
725 # Trigger to flush cache and write to DB.
726 if len(self.db_input_cache) >= self.db_cache_size:
726 if len(self.db_input_cache) >= self.db_cache_size:
727 self.save_flag.set()
727 self.save_flag.set()
728
728
729 # update the auto _i variables
729 # update the auto _i variables
730 self._iii = self._ii
730 self._iii = self._ii
731 self._ii = self._i
731 self._ii = self._i
732 self._i = self._i00
732 self._i = self._i00
733 self._i00 = source_raw
733 self._i00 = source_raw
734
734
735 # hackish access to user namespace to create _i1,_i2... dynamically
735 # hackish access to user namespace to create _i1,_i2... dynamically
736 new_i = '_i%s' % line_num
736 new_i = '_i%s' % line_num
737 to_main = {'_i': self._i,
737 to_main = {'_i': self._i,
738 '_ii': self._ii,
738 '_ii': self._ii,
739 '_iii': self._iii,
739 '_iii': self._iii,
740 new_i : self._i00 }
740 new_i : self._i00 }
741
741
742 if self.shell is not None:
742 if self.shell is not None:
743 self.shell.push(to_main, interactive=False)
743 self.shell.push(to_main, interactive=False)
744
744
745 def store_output(self, line_num):
745 def store_output(self, line_num):
746 """If database output logging is enabled, this saves all the
746 """If database output logging is enabled, this saves all the
747 outputs from the indicated prompt number to the database. It's
747 outputs from the indicated prompt number to the database. It's
748 called by run_cell after code has been executed.
748 called by run_cell after code has been executed.
749
749
750 Parameters
750 Parameters
751 ----------
751 ----------
752 line_num : int
752 line_num : int
753 The line number from which to save outputs
753 The line number from which to save outputs
754 """
754 """
755 if (not self.db_log_output) or (line_num not in self.output_hist_reprs):
755 if (not self.db_log_output) or (line_num not in self.output_hist_reprs):
756 return
756 return
757 output = self.output_hist_reprs[line_num]
757 output = self.output_hist_reprs[line_num]
758
758
759 with self.db_output_cache_lock:
759 with self.db_output_cache_lock:
760 self.db_output_cache.append((line_num, output))
760 self.db_output_cache.append((line_num, output))
761 if self.db_cache_size <= 1:
761 if self.db_cache_size <= 1:
762 self.save_flag.set()
762 self.save_flag.set()
763
763
764 def _writeout_input_cache(self, conn):
764 def _writeout_input_cache(self, conn):
765 with conn:
765 with conn:
766 for line in self.db_input_cache:
766 for line in self.db_input_cache:
767 conn.execute("INSERT INTO history VALUES (?, ?, ?, ?)",
767 conn.execute("INSERT INTO history VALUES (?, ?, ?, ?)",
768 (self.session_number,)+line)
768 (self.session_number,)+line)
769
769
770 def _writeout_output_cache(self, conn):
770 def _writeout_output_cache(self, conn):
771 with conn:
771 with conn:
772 for line in self.db_output_cache:
772 for line in self.db_output_cache:
773 conn.execute("INSERT INTO output_history VALUES (?, ?, ?)",
773 conn.execute("INSERT INTO output_history VALUES (?, ?, ?)",
774 (self.session_number,)+line)
774 (self.session_number,)+line)
775
775
776 @needs_sqlite
776 @needs_sqlite
777 def writeout_cache(self, conn=None):
777 def writeout_cache(self, conn=None):
778 """Write any entries in the cache to the database."""
778 """Write any entries in the cache to the database."""
779 if conn is None:
779 if conn is None:
780 conn = self.db
780 conn = self.db
781
781
782 with self.db_input_cache_lock:
782 with self.db_input_cache_lock:
783 try:
783 try:
784 self._writeout_input_cache(conn)
784 self._writeout_input_cache(conn)
785 except sqlite3.IntegrityError:
785 except sqlite3.IntegrityError:
786 self.new_session(conn)
786 self.new_session(conn)
787 print("ERROR! Session/line number was not unique in",
787 print("ERROR! Session/line number was not unique in",
788 "database. History logging moved to new session",
788 "database. History logging moved to new session",
789 self.session_number)
789 self.session_number)
790 try:
790 try:
791 # Try writing to the new session. If this fails, don't
791 # Try writing to the new session. If this fails, don't
792 # recurse
792 # recurse
793 self._writeout_input_cache(conn)
793 self._writeout_input_cache(conn)
794 except sqlite3.IntegrityError:
794 except sqlite3.IntegrityError:
795 pass
795 pass
796 finally:
796 finally:
797 self.db_input_cache = []
797 self.db_input_cache = []
798
798
799 with self.db_output_cache_lock:
799 with self.db_output_cache_lock:
800 try:
800 try:
801 self._writeout_output_cache(conn)
801 self._writeout_output_cache(conn)
802 except sqlite3.IntegrityError:
802 except sqlite3.IntegrityError:
803 print("!! Session/line number for output was not unique",
803 print("!! Session/line number for output was not unique",
804 "in database. Output will not be stored.")
804 "in database. Output will not be stored.")
805 finally:
805 finally:
806 self.db_output_cache = []
806 self.db_output_cache = []
807
807
808
808
809 class HistorySavingThread(threading.Thread):
809 class HistorySavingThread(threading.Thread):
810 """This thread takes care of writing history to the database, so that
810 """This thread takes care of writing history to the database, so that
811 the UI isn't held up while that happens.
811 the UI isn't held up while that happens.
812
812
813 It waits for the HistoryManager's save_flag to be set, then writes out
813 It waits for the HistoryManager's save_flag to be set, then writes out
814 the history cache. The main thread is responsible for setting the flag when
814 the history cache. The main thread is responsible for setting the flag when
815 the cache size reaches a defined threshold."""
815 the cache size reaches a defined threshold."""
816 daemon = True
816 daemon = True
817 stop_now = False
817 stop_now = False
818 enabled = True
818 enabled = True
819 def __init__(self, history_manager):
819 def __init__(self, history_manager):
820 super(HistorySavingThread, self).__init__(name="IPythonHistorySavingThread")
820 super(HistorySavingThread, self).__init__(name="IPythonHistorySavingThread")
821 self.history_manager = history_manager
821 self.history_manager = history_manager
822 self.enabled = history_manager.enabled
822 self.enabled = history_manager.enabled
823 atexit.register(self.stop)
823 atexit.register(self.stop)
824
824
825 @needs_sqlite
825 @needs_sqlite
826 def run(self):
826 def run(self):
827 # We need a separate db connection per thread:
827 # We need a separate db connection per thread:
828 try:
828 try:
829 self.db = sqlite3.connect(self.history_manager.hist_file,
829 self.db = sqlite3.connect(self.history_manager.hist_file,
830 **self.history_manager.connection_options
830 **self.history_manager.connection_options
831 )
831 )
832 while True:
832 while True:
833 self.history_manager.save_flag.wait()
833 self.history_manager.save_flag.wait()
834 if self.stop_now:
834 if self.stop_now:
835 self.db.close()
835 self.db.close()
836 return
836 return
837 self.history_manager.save_flag.clear()
837 self.history_manager.save_flag.clear()
838 self.history_manager.writeout_cache(self.db)
838 self.history_manager.writeout_cache(self.db)
839 except Exception as e:
839 except Exception as e:
840 print(("The history saving thread hit an unexpected error (%s)."
840 print(("The history saving thread hit an unexpected error (%s)."
841 "History will not be written to the database.") % repr(e))
841 "History will not be written to the database.") % repr(e))
842
842
843 def stop(self):
843 def stop(self):
844 """This can be called from the main thread to safely stop this thread.
844 """This can be called from the main thread to safely stop this thread.
845
845
846 Note that it does not attempt to write out remaining history before
846 Note that it does not attempt to write out remaining history before
847 exiting. That should be done by calling the HistoryManager's
847 exiting. That should be done by calling the HistoryManager's
848 end_session method."""
848 end_session method."""
849 self.stop_now = True
849 self.stop_now = True
850 self.history_manager.save_flag.set()
850 self.history_manager.save_flag.set()
851 self.join()
851 self.join()
852
852
853
853
854 # To match, e.g. ~5/8-~2/3
854 # To match, e.g. ~5/8-~2/3
855 range_re = re.compile(r"""
855 range_re = re.compile(r"""
856 ((?P<startsess>~?\d+)/)?
856 ((?P<startsess>~?\d+)/)?
857 (?P<start>\d+)?
857 (?P<start>\d+)?
858 ((?P<sep>[\-:])
858 ((?P<sep>[\-:])
859 ((?P<endsess>~?\d+)/)?
859 ((?P<endsess>~?\d+)/)?
860 (?P<end>\d+))?
860 (?P<end>\d+))?
861 $""", re.VERBOSE)
861 $""", re.VERBOSE)
862
862
863
863
864 def extract_hist_ranges(ranges_str):
864 def extract_hist_ranges(ranges_str):
865 """Turn a string of history ranges into 3-tuples of (session, start, stop).
865 """Turn a string of history ranges into 3-tuples of (session, start, stop).
866
866
867 Examples
867 Examples
868 --------
868 --------
869 >>> list(extract_hist_ranges("~8/5-~7/4 2"))
869 >>> list(extract_hist_ranges("~8/5-~7/4 2"))
870 [(-8, 5, None), (-7, 1, 5), (0, 2, 3)]
870 [(-8, 5, None), (-7, 1, 5), (0, 2, 3)]
871 """
871 """
872 for range_str in ranges_str.split():
872 for range_str in ranges_str.split():
873 rmatch = range_re.match(range_str)
873 rmatch = range_re.match(range_str)
874 if not rmatch:
874 if not rmatch:
875 continue
875 continue
876 start = rmatch.group("start")
876 start = rmatch.group("start")
877 if start:
877 if start:
878 start = int(start)
878 start = int(start)
879 end = rmatch.group("end")
879 end = rmatch.group("end")
880 # If no end specified, get (a, a + 1)
880 # If no end specified, get (a, a + 1)
881 end = int(end) if end else start + 1
881 end = int(end) if end else start + 1
882 else: # start not specified
882 else: # start not specified
883 if not rmatch.group('startsess'): # no startsess
883 if not rmatch.group('startsess'): # no startsess
884 continue
884 continue
885 start = 1
885 start = 1
886 end = None # provide the entire session hist
886 end = None # provide the entire session hist
887
887
888 if rmatch.group("sep") == "-": # 1-3 == 1:4 --> [1, 2, 3]
888 if rmatch.group("sep") == "-": # 1-3 == 1:4 --> [1, 2, 3]
889 end += 1
889 end += 1
890 startsess = rmatch.group("startsess") or "0"
890 startsess = rmatch.group("startsess") or "0"
891 endsess = rmatch.group("endsess") or startsess
891 endsess = rmatch.group("endsess") or startsess
892 startsess = int(startsess.replace("~","-"))
892 startsess = int(startsess.replace("~","-"))
893 endsess = int(endsess.replace("~","-"))
893 endsess = int(endsess.replace("~","-"))
894 assert endsess >= startsess, "start session must be earlier than end session"
894 assert endsess >= startsess, "start session must be earlier than end session"
895
895
896 if endsess == startsess:
896 if endsess == startsess:
897 yield (startsess, start, end)
897 yield (startsess, start, end)
898 continue
898 continue
899 # Multiple sessions in one range:
899 # Multiple sessions in one range:
900 yield (startsess, start, None)
900 yield (startsess, start, None)
901 for sess in range(startsess+1, endsess):
901 for sess in range(startsess+1, endsess):
902 yield (sess, 1, None)
902 yield (sess, 1, None)
903 yield (endsess, 1, end)
903 yield (endsess, 1, end)
904
904
905
905
906 def _format_lineno(session, line):
906 def _format_lineno(session, line):
907 """Helper function to format line numbers properly."""
907 """Helper function to format line numbers properly."""
908 if session == 0:
908 if session == 0:
909 return str(line)
909 return str(line)
910 return "%s#%s" % (session, line)
910 return "%s#%s" % (session, line)
@@ -1,3226 +1,3223 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 import __future__
14 import __future__
15 import abc
15 import abc
16 import ast
16 import ast
17 import atexit
17 import atexit
18 import functools
18 import functools
19 import os
19 import os
20 import re
20 import re
21 import runpy
21 import runpy
22 import sys
22 import sys
23 import tempfile
23 import tempfile
24 import traceback
24 import traceback
25 import types
25 import types
26 import subprocess
26 import subprocess
27 import warnings
27 import warnings
28 from io import open as io_open
28 from io import open as io_open
29
29
30 from pickleshare import PickleShareDB
30 from pickleshare import PickleShareDB
31
31
32 from traitlets.config.configurable import SingletonConfigurable
32 from traitlets.config.configurable import SingletonConfigurable
33 from IPython.core import oinspect
33 from IPython.core import oinspect
34 from IPython.core import magic
34 from IPython.core import magic
35 from IPython.core import page
35 from IPython.core import page
36 from IPython.core import prefilter
36 from IPython.core import prefilter
37 from IPython.core import shadowns
37 from IPython.core import shadowns
38 from IPython.core import ultratb
38 from IPython.core import ultratb
39 from IPython.core.alias import Alias, AliasManager
39 from IPython.core.alias import Alias, AliasManager
40 from IPython.core.autocall import ExitAutocall
40 from IPython.core.autocall import ExitAutocall
41 from IPython.core.builtin_trap import BuiltinTrap
41 from IPython.core.builtin_trap import BuiltinTrap
42 from IPython.core.events import EventManager, available_events
42 from IPython.core.events import EventManager, available_events
43 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
43 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
44 from IPython.core.debugger import Pdb
44 from IPython.core.debugger import Pdb
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 InputRejected, UsageError
48 from IPython.core.error import InputRejected, 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 ESC_MAGIC, ESC_MAGIC2
52 from IPython.core.inputsplitter import 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.usage import default_banner
58 from IPython.core.usage import default_banner
59 from IPython.testing.skipdoctest import skip_doctest
59 from IPython.testing.skipdoctest import skip_doctest
60 from IPython.utils import PyColorize
60 from IPython.utils import PyColorize
61 from IPython.utils import io
61 from IPython.utils import io
62 from IPython.utils import py3compat
62 from IPython.utils import py3compat
63 from IPython.utils import openpy
63 from IPython.utils import openpy
64 from IPython.utils.decorators import undoc
64 from IPython.utils.decorators import undoc
65 from IPython.utils.io import ask_yes_no
65 from IPython.utils.io import ask_yes_no
66 from IPython.utils.ipstruct import Struct
66 from IPython.utils.ipstruct import Struct
67 from IPython.paths import get_ipython_dir
67 from IPython.paths import get_ipython_dir
68 from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
68 from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
69 from IPython.utils.process import system, getoutput
69 from IPython.utils.process import system, getoutput
70 from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
70 from IPython.utils.py3compat import builtin_mod, with_metaclass
71 with_metaclass, iteritems)
72 from IPython.utils.strdispatch import StrDispatch
71 from IPython.utils.strdispatch import StrDispatch
73 from IPython.utils.syspathcontext import prepended_to_syspath
72 from IPython.utils.syspathcontext import prepended_to_syspath
74 from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
73 from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
75 from IPython.utils.tempdir import TemporaryDirectory
74 from IPython.utils.tempdir import TemporaryDirectory
76 from traitlets import (
75 from traitlets import (
77 Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
76 Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
78 observe, default,
77 observe, default,
79 )
78 )
80 from warnings import warn
79 from warnings import warn
81 from logging import error
80 from logging import error
82 import IPython.core.hooks
81 import IPython.core.hooks
83
82
84 # NoOpContext is deprecated, but ipykernel imports it from here.
83 # NoOpContext is deprecated, but ipykernel imports it from here.
85 # See https://github.com/ipython/ipykernel/issues/157
84 # See https://github.com/ipython/ipykernel/issues/157
86 from IPython.utils.contexts import NoOpContext
85 from IPython.utils.contexts import NoOpContext
87
86
88 try:
87 try:
89 import docrepr.sphinxify as sphx
88 import docrepr.sphinxify as sphx
90
89
91 def sphinxify(doc):
90 def sphinxify(doc):
92 with TemporaryDirectory() as dirname:
91 with TemporaryDirectory() as dirname:
93 return {
92 return {
94 'text/html': sphx.sphinxify(doc, dirname),
93 'text/html': sphx.sphinxify(doc, dirname),
95 'text/plain': doc
94 'text/plain': doc
96 }
95 }
97 except ImportError:
96 except ImportError:
98 sphinxify = None
97 sphinxify = None
99
98
100
99
101 class ProvisionalWarning(DeprecationWarning):
100 class ProvisionalWarning(DeprecationWarning):
102 """
101 """
103 Warning class for unstable features
102 Warning class for unstable features
104 """
103 """
105 pass
104 pass
106
105
107 #-----------------------------------------------------------------------------
106 #-----------------------------------------------------------------------------
108 # Globals
107 # Globals
109 #-----------------------------------------------------------------------------
108 #-----------------------------------------------------------------------------
110
109
111 # compiled regexps for autoindent management
110 # compiled regexps for autoindent management
112 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
111 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
113
112
114 #-----------------------------------------------------------------------------
113 #-----------------------------------------------------------------------------
115 # Utilities
114 # Utilities
116 #-----------------------------------------------------------------------------
115 #-----------------------------------------------------------------------------
117
116
118 @undoc
117 @undoc
119 def softspace(file, newvalue):
118 def softspace(file, newvalue):
120 """Copied from code.py, to remove the dependency"""
119 """Copied from code.py, to remove the dependency"""
121
120
122 oldvalue = 0
121 oldvalue = 0
123 try:
122 try:
124 oldvalue = file.softspace
123 oldvalue = file.softspace
125 except AttributeError:
124 except AttributeError:
126 pass
125 pass
127 try:
126 try:
128 file.softspace = newvalue
127 file.softspace = newvalue
129 except (AttributeError, TypeError):
128 except (AttributeError, TypeError):
130 # "attribute-less object" or "read-only attributes"
129 # "attribute-less object" or "read-only attributes"
131 pass
130 pass
132 return oldvalue
131 return oldvalue
133
132
134 @undoc
133 @undoc
135 def no_op(*a, **kw): pass
134 def no_op(*a, **kw): pass
136
135
137
136
138 class SpaceInInput(Exception): pass
137 class SpaceInInput(Exception): pass
139
138
140
139
141 def get_default_colors():
140 def get_default_colors():
142 "DEPRECATED"
141 "DEPRECATED"
143 warn('get_default_color is Deprecated, and is `Neutral` on all platforms.',
142 warn('get_default_color is Deprecated, and is `Neutral` on all platforms.',
144 DeprecationWarning, stacklevel=2)
143 DeprecationWarning, stacklevel=2)
145 return 'Neutral'
144 return 'Neutral'
146
145
147
146
148 class SeparateUnicode(Unicode):
147 class SeparateUnicode(Unicode):
149 r"""A Unicode subclass to validate separate_in, separate_out, etc.
148 r"""A Unicode subclass to validate separate_in, separate_out, etc.
150
149
151 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
150 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
152 """
151 """
153
152
154 def validate(self, obj, value):
153 def validate(self, obj, value):
155 if value == '0': value = ''
154 if value == '0': value = ''
156 value = value.replace('\\n','\n')
155 value = value.replace('\\n','\n')
157 return super(SeparateUnicode, self).validate(obj, value)
156 return super(SeparateUnicode, self).validate(obj, value)
158
157
159
158
160 @undoc
159 @undoc
161 class DummyMod(object):
160 class DummyMod(object):
162 """A dummy module used for IPython's interactive module when
161 """A dummy module used for IPython's interactive module when
163 a namespace must be assigned to the module's __dict__."""
162 a namespace must be assigned to the module's __dict__."""
164 pass
163 pass
165
164
166
165
167 class ExecutionResult(object):
166 class ExecutionResult(object):
168 """The result of a call to :meth:`InteractiveShell.run_cell`
167 """The result of a call to :meth:`InteractiveShell.run_cell`
169
168
170 Stores information about what took place.
169 Stores information about what took place.
171 """
170 """
172 execution_count = None
171 execution_count = None
173 error_before_exec = None
172 error_before_exec = None
174 error_in_exec = None
173 error_in_exec = None
175 result = None
174 result = None
176
175
177 @property
176 @property
178 def success(self):
177 def success(self):
179 return (self.error_before_exec is None) and (self.error_in_exec is None)
178 return (self.error_before_exec is None) and (self.error_in_exec is None)
180
179
181 def raise_error(self):
180 def raise_error(self):
182 """Reraises error if `success` is `False`, otherwise does nothing"""
181 """Reraises error if `success` is `False`, otherwise does nothing"""
183 if self.error_before_exec is not None:
182 if self.error_before_exec is not None:
184 raise self.error_before_exec
183 raise self.error_before_exec
185 if self.error_in_exec is not None:
184 if self.error_in_exec is not None:
186 raise self.error_in_exec
185 raise self.error_in_exec
187
186
188 def __repr__(self):
187 def __repr__(self):
189 name = self.__class__.__qualname__
188 name = self.__class__.__qualname__
190 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\
189 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\
191 (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result))
190 (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result))
192
191
193
192
194 class InteractiveShell(SingletonConfigurable):
193 class InteractiveShell(SingletonConfigurable):
195 """An enhanced, interactive shell for Python."""
194 """An enhanced, interactive shell for Python."""
196
195
197 _instance = None
196 _instance = None
198
197
199 ast_transformers = List([], help=
198 ast_transformers = List([], help=
200 """
199 """
201 A list of ast.NodeTransformer subclass instances, which will be applied
200 A list of ast.NodeTransformer subclass instances, which will be applied
202 to user input before code is run.
201 to user input before code is run.
203 """
202 """
204 ).tag(config=True)
203 ).tag(config=True)
205
204
206 autocall = Enum((0,1,2), default_value=0, help=
205 autocall = Enum((0,1,2), default_value=0, help=
207 """
206 """
208 Make IPython automatically call any callable object even if you didn't
207 Make IPython automatically call any callable object even if you didn't
209 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
208 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
210 automatically. The value can be '0' to disable the feature, '1' for
209 automatically. The value can be '0' to disable the feature, '1' for
211 'smart' autocall, where it is not applied if there are no more
210 'smart' autocall, where it is not applied if there are no more
212 arguments on the line, and '2' for 'full' autocall, where all callable
211 arguments on the line, and '2' for 'full' autocall, where all callable
213 objects are automatically called (even if no arguments are present).
212 objects are automatically called (even if no arguments are present).
214 """
213 """
215 ).tag(config=True)
214 ).tag(config=True)
216 # TODO: remove all autoindent logic and put into frontends.
215 # TODO: remove all autoindent logic and put into frontends.
217 # We can't do this yet because even runlines uses the autoindent.
216 # We can't do this yet because even runlines uses the autoindent.
218 autoindent = Bool(True, help=
217 autoindent = Bool(True, help=
219 """
218 """
220 Autoindent IPython code entered interactively.
219 Autoindent IPython code entered interactively.
221 """
220 """
222 ).tag(config=True)
221 ).tag(config=True)
223
222
224 automagic = Bool(True, help=
223 automagic = Bool(True, help=
225 """
224 """
226 Enable magic commands to be called without the leading %.
225 Enable magic commands to be called without the leading %.
227 """
226 """
228 ).tag(config=True)
227 ).tag(config=True)
229
228
230 banner1 = Unicode(default_banner,
229 banner1 = Unicode(default_banner,
231 help="""The part of the banner to be printed before the profile"""
230 help="""The part of the banner to be printed before the profile"""
232 ).tag(config=True)
231 ).tag(config=True)
233 banner2 = Unicode('',
232 banner2 = Unicode('',
234 help="""The part of the banner to be printed after the profile"""
233 help="""The part of the banner to be printed after the profile"""
235 ).tag(config=True)
234 ).tag(config=True)
236
235
237 cache_size = Integer(1000, help=
236 cache_size = Integer(1000, help=
238 """
237 """
239 Set the size of the output cache. The default is 1000, you can
238 Set the size of the output cache. The default is 1000, you can
240 change it permanently in your config file. Setting it to 0 completely
239 change it permanently in your config file. Setting it to 0 completely
241 disables the caching system, and the minimum value accepted is 20 (if
240 disables the caching system, and the minimum value accepted is 20 (if
242 you provide a value less than 20, it is reset to 0 and a warning is
241 you provide a value less than 20, it is reset to 0 and a warning is
243 issued). This limit is defined because otherwise you'll spend more
242 issued). This limit is defined because otherwise you'll spend more
244 time re-flushing a too small cache than working
243 time re-flushing a too small cache than working
245 """
244 """
246 ).tag(config=True)
245 ).tag(config=True)
247 color_info = Bool(True, help=
246 color_info = Bool(True, help=
248 """
247 """
249 Use colors for displaying information about objects. Because this
248 Use colors for displaying information about objects. Because this
250 information is passed through a pager (like 'less'), and some pagers
249 information is passed through a pager (like 'less'), and some pagers
251 get confused with color codes, this capability can be turned off.
250 get confused with color codes, this capability can be turned off.
252 """
251 """
253 ).tag(config=True)
252 ).tag(config=True)
254 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
253 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
255 default_value='Neutral',
254 default_value='Neutral',
256 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
255 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
257 ).tag(config=True)
256 ).tag(config=True)
258 debug = Bool(False).tag(config=True)
257 debug = Bool(False).tag(config=True)
259 disable_failing_post_execute = Bool(False,
258 disable_failing_post_execute = Bool(False,
260 help="Don't call post-execute functions that have failed in the past."
259 help="Don't call post-execute functions that have failed in the past."
261 ).tag(config=True)
260 ).tag(config=True)
262 display_formatter = Instance(DisplayFormatter, allow_none=True)
261 display_formatter = Instance(DisplayFormatter, allow_none=True)
263 displayhook_class = Type(DisplayHook)
262 displayhook_class = Type(DisplayHook)
264 display_pub_class = Type(DisplayPublisher)
263 display_pub_class = Type(DisplayPublisher)
265
264
266 sphinxify_docstring = Bool(False, help=
265 sphinxify_docstring = Bool(False, help=
267 """
266 """
268 Enables rich html representation of docstrings. (This requires the
267 Enables rich html representation of docstrings. (This requires the
269 docrepr module).
268 docrepr module).
270 """).tag(config=True)
269 """).tag(config=True)
271
270
272 @observe("sphinxify_docstring")
271 @observe("sphinxify_docstring")
273 def _sphinxify_docstring_changed(self, change):
272 def _sphinxify_docstring_changed(self, change):
274 if change['new']:
273 if change['new']:
275 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
274 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
276
275
277 enable_html_pager = Bool(False, help=
276 enable_html_pager = Bool(False, help=
278 """
277 """
279 (Provisional API) enables html representation in mime bundles sent
278 (Provisional API) enables html representation in mime bundles sent
280 to pagers.
279 to pagers.
281 """).tag(config=True)
280 """).tag(config=True)
282
281
283 @observe("enable_html_pager")
282 @observe("enable_html_pager")
284 def _enable_html_pager_changed(self, change):
283 def _enable_html_pager_changed(self, change):
285 if change['new']:
284 if change['new']:
286 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
285 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
287
286
288 data_pub_class = None
287 data_pub_class = None
289
288
290 exit_now = Bool(False)
289 exit_now = Bool(False)
291 exiter = Instance(ExitAutocall)
290 exiter = Instance(ExitAutocall)
292 @default('exiter')
291 @default('exiter')
293 def _exiter_default(self):
292 def _exiter_default(self):
294 return ExitAutocall(self)
293 return ExitAutocall(self)
295 # Monotonically increasing execution counter
294 # Monotonically increasing execution counter
296 execution_count = Integer(1)
295 execution_count = Integer(1)
297 filename = Unicode("<ipython console>")
296 filename = Unicode("<ipython console>")
298 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
297 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
299
298
300 # Input splitter, to transform input line by line and detect when a block
299 # Input splitter, to transform input line by line and detect when a block
301 # is ready to be executed.
300 # is ready to be executed.
302 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
301 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
303 (), {'line_input_checker': True})
302 (), {'line_input_checker': True})
304
303
305 # This InputSplitter instance is used to transform completed cells before
304 # This InputSplitter instance is used to transform completed cells before
306 # running them. It allows cell magics to contain blank lines.
305 # running them. It allows cell magics to contain blank lines.
307 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
306 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
308 (), {'line_input_checker': False})
307 (), {'line_input_checker': False})
309
308
310 logstart = Bool(False, help=
309 logstart = Bool(False, help=
311 """
310 """
312 Start logging to the default log file in overwrite mode.
311 Start logging to the default log file in overwrite mode.
313 Use `logappend` to specify a log file to **append** logs to.
312 Use `logappend` to specify a log file to **append** logs to.
314 """
313 """
315 ).tag(config=True)
314 ).tag(config=True)
316 logfile = Unicode('', help=
315 logfile = Unicode('', help=
317 """
316 """
318 The name of the logfile to use.
317 The name of the logfile to use.
319 """
318 """
320 ).tag(config=True)
319 ).tag(config=True)
321 logappend = Unicode('', help=
320 logappend = Unicode('', help=
322 """
321 """
323 Start logging to the given file in append mode.
322 Start logging to the given file in append mode.
324 Use `logfile` to specify a log file to **overwrite** logs to.
323 Use `logfile` to specify a log file to **overwrite** logs to.
325 """
324 """
326 ).tag(config=True)
325 ).tag(config=True)
327 object_info_string_level = Enum((0,1,2), default_value=0,
326 object_info_string_level = Enum((0,1,2), default_value=0,
328 ).tag(config=True)
327 ).tag(config=True)
329 pdb = Bool(False, help=
328 pdb = Bool(False, help=
330 """
329 """
331 Automatically call the pdb debugger after every exception.
330 Automatically call the pdb debugger after every exception.
332 """
331 """
333 ).tag(config=True)
332 ).tag(config=True)
334 display_page = Bool(False,
333 display_page = Bool(False,
335 help="""If True, anything that would be passed to the pager
334 help="""If True, anything that would be passed to the pager
336 will be displayed as regular output instead."""
335 will be displayed as regular output instead."""
337 ).tag(config=True)
336 ).tag(config=True)
338
337
339 # deprecated prompt traits:
338 # deprecated prompt traits:
340
339
341 prompt_in1 = Unicode('In [\\#]: ',
340 prompt_in1 = Unicode('In [\\#]: ',
342 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
341 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
343 ).tag(config=True)
342 ).tag(config=True)
344 prompt_in2 = Unicode(' .\\D.: ',
343 prompt_in2 = Unicode(' .\\D.: ',
345 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
344 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
346 ).tag(config=True)
345 ).tag(config=True)
347 prompt_out = Unicode('Out[\\#]: ',
346 prompt_out = Unicode('Out[\\#]: ',
348 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
347 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
349 ).tag(config=True)
348 ).tag(config=True)
350 prompts_pad_left = Bool(True,
349 prompts_pad_left = Bool(True,
351 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
350 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
352 ).tag(config=True)
351 ).tag(config=True)
353
352
354 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
353 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
355 def _prompt_trait_changed(self, change):
354 def _prompt_trait_changed(self, change):
356 name = change['name']
355 name = change['name']
357 warn("InteractiveShell.{name} is deprecated since IPython 4.0"
356 warn("InteractiveShell.{name} is deprecated since IPython 4.0"
358 " and ignored since 5.0, set TerminalInteractiveShell.prompts"
357 " and ignored since 5.0, set TerminalInteractiveShell.prompts"
359 " object directly.".format(name=name))
358 " object directly.".format(name=name))
360
359
361 # protect against weird cases where self.config may not exist:
360 # protect against weird cases where self.config may not exist:
362
361
363 show_rewritten_input = Bool(True,
362 show_rewritten_input = Bool(True,
364 help="Show rewritten input, e.g. for autocall."
363 help="Show rewritten input, e.g. for autocall."
365 ).tag(config=True)
364 ).tag(config=True)
366
365
367 quiet = Bool(False).tag(config=True)
366 quiet = Bool(False).tag(config=True)
368
367
369 history_length = Integer(10000,
368 history_length = Integer(10000,
370 help='Total length of command history'
369 help='Total length of command history'
371 ).tag(config=True)
370 ).tag(config=True)
372
371
373 history_load_length = Integer(1000, help=
372 history_load_length = Integer(1000, help=
374 """
373 """
375 The number of saved history entries to be loaded
374 The number of saved history entries to be loaded
376 into the history buffer at startup.
375 into the history buffer at startup.
377 """
376 """
378 ).tag(config=True)
377 ).tag(config=True)
379
378
380 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
379 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
381 default_value='last_expr',
380 default_value='last_expr',
382 help="""
381 help="""
383 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
382 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
384 run interactively (displaying output from expressions)."""
383 run interactively (displaying output from expressions)."""
385 ).tag(config=True)
384 ).tag(config=True)
386
385
387 # TODO: this part of prompt management should be moved to the frontends.
386 # TODO: this part of prompt management should be moved to the frontends.
388 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
387 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
389 separate_in = SeparateUnicode('\n').tag(config=True)
388 separate_in = SeparateUnicode('\n').tag(config=True)
390 separate_out = SeparateUnicode('').tag(config=True)
389 separate_out = SeparateUnicode('').tag(config=True)
391 separate_out2 = SeparateUnicode('').tag(config=True)
390 separate_out2 = SeparateUnicode('').tag(config=True)
392 wildcards_case_sensitive = Bool(True).tag(config=True)
391 wildcards_case_sensitive = Bool(True).tag(config=True)
393 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
392 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
394 default_value='Context').tag(config=True)
393 default_value='Context').tag(config=True)
395
394
396 # Subcomponents of InteractiveShell
395 # Subcomponents of InteractiveShell
397 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
396 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
398 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
397 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
399 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
398 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
400 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
399 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
401 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
400 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
402 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
401 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
403 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
402 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
404 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
403 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
405
404
406 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
405 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
407 @property
406 @property
408 def profile(self):
407 def profile(self):
409 if self.profile_dir is not None:
408 if self.profile_dir is not None:
410 name = os.path.basename(self.profile_dir.location)
409 name = os.path.basename(self.profile_dir.location)
411 return name.replace('profile_','')
410 return name.replace('profile_','')
412
411
413
412
414 # Private interface
413 # Private interface
415 _post_execute = Dict()
414 _post_execute = Dict()
416
415
417 # Tracks any GUI loop loaded for pylab
416 # Tracks any GUI loop loaded for pylab
418 pylab_gui_select = None
417 pylab_gui_select = None
419
418
420 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
419 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
421
420
422 def __init__(self, ipython_dir=None, profile_dir=None,
421 def __init__(self, ipython_dir=None, profile_dir=None,
423 user_module=None, user_ns=None,
422 user_module=None, user_ns=None,
424 custom_exceptions=((), None), **kwargs):
423 custom_exceptions=((), None), **kwargs):
425
424
426 # This is where traits with a config_key argument are updated
425 # This is where traits with a config_key argument are updated
427 # from the values on config.
426 # from the values on config.
428 super(InteractiveShell, self).__init__(**kwargs)
427 super(InteractiveShell, self).__init__(**kwargs)
429 if 'PromptManager' in self.config:
428 if 'PromptManager' in self.config:
430 warn('As of IPython 5.0 `PromptManager` config will have no effect'
429 warn('As of IPython 5.0 `PromptManager` config will have no effect'
431 ' and has been replaced by TerminalInteractiveShell.prompts_class')
430 ' and has been replaced by TerminalInteractiveShell.prompts_class')
432 self.configurables = [self]
431 self.configurables = [self]
433
432
434 # These are relatively independent and stateless
433 # These are relatively independent and stateless
435 self.init_ipython_dir(ipython_dir)
434 self.init_ipython_dir(ipython_dir)
436 self.init_profile_dir(profile_dir)
435 self.init_profile_dir(profile_dir)
437 self.init_instance_attrs()
436 self.init_instance_attrs()
438 self.init_environment()
437 self.init_environment()
439
438
440 # Check if we're in a virtualenv, and set up sys.path.
439 # Check if we're in a virtualenv, and set up sys.path.
441 self.init_virtualenv()
440 self.init_virtualenv()
442
441
443 # Create namespaces (user_ns, user_global_ns, etc.)
442 # Create namespaces (user_ns, user_global_ns, etc.)
444 self.init_create_namespaces(user_module, user_ns)
443 self.init_create_namespaces(user_module, user_ns)
445 # This has to be done after init_create_namespaces because it uses
444 # This has to be done after init_create_namespaces because it uses
446 # something in self.user_ns, but before init_sys_modules, which
445 # something in self.user_ns, but before init_sys_modules, which
447 # is the first thing to modify sys.
446 # is the first thing to modify sys.
448 # TODO: When we override sys.stdout and sys.stderr before this class
447 # TODO: When we override sys.stdout and sys.stderr before this class
449 # is created, we are saving the overridden ones here. Not sure if this
448 # is created, we are saving the overridden ones here. Not sure if this
450 # is what we want to do.
449 # is what we want to do.
451 self.save_sys_module_state()
450 self.save_sys_module_state()
452 self.init_sys_modules()
451 self.init_sys_modules()
453
452
454 # While we're trying to have each part of the code directly access what
453 # While we're trying to have each part of the code directly access what
455 # it needs without keeping redundant references to objects, we have too
454 # it needs without keeping redundant references to objects, we have too
456 # much legacy code that expects ip.db to exist.
455 # much legacy code that expects ip.db to exist.
457 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
456 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
458
457
459 self.init_history()
458 self.init_history()
460 self.init_encoding()
459 self.init_encoding()
461 self.init_prefilter()
460 self.init_prefilter()
462
461
463 self.init_syntax_highlighting()
462 self.init_syntax_highlighting()
464 self.init_hooks()
463 self.init_hooks()
465 self.init_events()
464 self.init_events()
466 self.init_pushd_popd_magic()
465 self.init_pushd_popd_magic()
467 self.init_user_ns()
466 self.init_user_ns()
468 self.init_logger()
467 self.init_logger()
469 self.init_builtins()
468 self.init_builtins()
470
469
471 # The following was in post_config_initialization
470 # The following was in post_config_initialization
472 self.init_inspector()
471 self.init_inspector()
473 self.raw_input_original = input
472 self.raw_input_original = input
474 self.init_completer()
473 self.init_completer()
475 # TODO: init_io() needs to happen before init_traceback handlers
474 # TODO: init_io() needs to happen before init_traceback handlers
476 # because the traceback handlers hardcode the stdout/stderr streams.
475 # because the traceback handlers hardcode the stdout/stderr streams.
477 # This logic in in debugger.Pdb and should eventually be changed.
476 # This logic in in debugger.Pdb and should eventually be changed.
478 self.init_io()
477 self.init_io()
479 self.init_traceback_handlers(custom_exceptions)
478 self.init_traceback_handlers(custom_exceptions)
480 self.init_prompts()
479 self.init_prompts()
481 self.init_display_formatter()
480 self.init_display_formatter()
482 self.init_display_pub()
481 self.init_display_pub()
483 self.init_data_pub()
482 self.init_data_pub()
484 self.init_displayhook()
483 self.init_displayhook()
485 self.init_magics()
484 self.init_magics()
486 self.init_alias()
485 self.init_alias()
487 self.init_logstart()
486 self.init_logstart()
488 self.init_pdb()
487 self.init_pdb()
489 self.init_extension_manager()
488 self.init_extension_manager()
490 self.init_payload()
489 self.init_payload()
491 self.init_deprecation_warnings()
490 self.init_deprecation_warnings()
492 self.hooks.late_startup_hook()
491 self.hooks.late_startup_hook()
493 self.events.trigger('shell_initialized', self)
492 self.events.trigger('shell_initialized', self)
494 atexit.register(self.atexit_operations)
493 atexit.register(self.atexit_operations)
495
494
496 def get_ipython(self):
495 def get_ipython(self):
497 """Return the currently running IPython instance."""
496 """Return the currently running IPython instance."""
498 return self
497 return self
499
498
500 #-------------------------------------------------------------------------
499 #-------------------------------------------------------------------------
501 # Trait changed handlers
500 # Trait changed handlers
502 #-------------------------------------------------------------------------
501 #-------------------------------------------------------------------------
503 @observe('ipython_dir')
502 @observe('ipython_dir')
504 def _ipython_dir_changed(self, change):
503 def _ipython_dir_changed(self, change):
505 ensure_dir_exists(change['new'])
504 ensure_dir_exists(change['new'])
506
505
507 def set_autoindent(self,value=None):
506 def set_autoindent(self,value=None):
508 """Set the autoindent flag.
507 """Set the autoindent flag.
509
508
510 If called with no arguments, it acts as a toggle."""
509 If called with no arguments, it acts as a toggle."""
511 if value is None:
510 if value is None:
512 self.autoindent = not self.autoindent
511 self.autoindent = not self.autoindent
513 else:
512 else:
514 self.autoindent = value
513 self.autoindent = value
515
514
516 #-------------------------------------------------------------------------
515 #-------------------------------------------------------------------------
517 # init_* methods called by __init__
516 # init_* methods called by __init__
518 #-------------------------------------------------------------------------
517 #-------------------------------------------------------------------------
519
518
520 def init_ipython_dir(self, ipython_dir):
519 def init_ipython_dir(self, ipython_dir):
521 if ipython_dir is not None:
520 if ipython_dir is not None:
522 self.ipython_dir = ipython_dir
521 self.ipython_dir = ipython_dir
523 return
522 return
524
523
525 self.ipython_dir = get_ipython_dir()
524 self.ipython_dir = get_ipython_dir()
526
525
527 def init_profile_dir(self, profile_dir):
526 def init_profile_dir(self, profile_dir):
528 if profile_dir is not None:
527 if profile_dir is not None:
529 self.profile_dir = profile_dir
528 self.profile_dir = profile_dir
530 return
529 return
531 self.profile_dir =\
530 self.profile_dir =\
532 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
531 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
533
532
534 def init_instance_attrs(self):
533 def init_instance_attrs(self):
535 self.more = False
534 self.more = False
536
535
537 # command compiler
536 # command compiler
538 self.compile = CachingCompiler()
537 self.compile = CachingCompiler()
539
538
540 # Make an empty namespace, which extension writers can rely on both
539 # Make an empty namespace, which extension writers can rely on both
541 # existing and NEVER being used by ipython itself. This gives them a
540 # existing and NEVER being used by ipython itself. This gives them a
542 # convenient location for storing additional information and state
541 # convenient location for storing additional information and state
543 # their extensions may require, without fear of collisions with other
542 # their extensions may require, without fear of collisions with other
544 # ipython names that may develop later.
543 # ipython names that may develop later.
545 self.meta = Struct()
544 self.meta = Struct()
546
545
547 # Temporary files used for various purposes. Deleted at exit.
546 # Temporary files used for various purposes. Deleted at exit.
548 self.tempfiles = []
547 self.tempfiles = []
549 self.tempdirs = []
548 self.tempdirs = []
550
549
551 # keep track of where we started running (mainly for crash post-mortem)
550 # keep track of where we started running (mainly for crash post-mortem)
552 # This is not being used anywhere currently.
551 # This is not being used anywhere currently.
553 self.starting_dir = py3compat.getcwd()
552 self.starting_dir = os.getcwd()
554
553
555 # Indentation management
554 # Indentation management
556 self.indent_current_nsp = 0
555 self.indent_current_nsp = 0
557
556
558 # Dict to track post-execution functions that have been registered
557 # Dict to track post-execution functions that have been registered
559 self._post_execute = {}
558 self._post_execute = {}
560
559
561 def init_environment(self):
560 def init_environment(self):
562 """Any changes we need to make to the user's environment."""
561 """Any changes we need to make to the user's environment."""
563 pass
562 pass
564
563
565 def init_encoding(self):
564 def init_encoding(self):
566 # Get system encoding at startup time. Certain terminals (like Emacs
565 # Get system encoding at startup time. Certain terminals (like Emacs
567 # under Win32 have it set to None, and we need to have a known valid
566 # under Win32 have it set to None, and we need to have a known valid
568 # encoding to use in the raw_input() method
567 # encoding to use in the raw_input() method
569 try:
568 try:
570 self.stdin_encoding = sys.stdin.encoding or 'ascii'
569 self.stdin_encoding = sys.stdin.encoding or 'ascii'
571 except AttributeError:
570 except AttributeError:
572 self.stdin_encoding = 'ascii'
571 self.stdin_encoding = 'ascii'
573
572
574
573
575 @observe('colors')
574 @observe('colors')
576 def init_syntax_highlighting(self, changes=None):
575 def init_syntax_highlighting(self, changes=None):
577 # Python source parser/formatter for syntax highlighting
576 # Python source parser/formatter for syntax highlighting
578 pyformat = PyColorize.Parser(style=self.colors, parent=self).format
577 pyformat = PyColorize.Parser(style=self.colors, parent=self).format
579 self.pycolorize = lambda src: pyformat(src,'str')
578 self.pycolorize = lambda src: pyformat(src,'str')
580
579
581 def refresh_style(self):
580 def refresh_style(self):
582 # No-op here, used in subclass
581 # No-op here, used in subclass
583 pass
582 pass
584
583
585 def init_pushd_popd_magic(self):
584 def init_pushd_popd_magic(self):
586 # for pushd/popd management
585 # for pushd/popd management
587 self.home_dir = get_home_dir()
586 self.home_dir = get_home_dir()
588
587
589 self.dir_stack = []
588 self.dir_stack = []
590
589
591 def init_logger(self):
590 def init_logger(self):
592 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
591 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
593 logmode='rotate')
592 logmode='rotate')
594
593
595 def init_logstart(self):
594 def init_logstart(self):
596 """Initialize logging in case it was requested at the command line.
595 """Initialize logging in case it was requested at the command line.
597 """
596 """
598 if self.logappend:
597 if self.logappend:
599 self.magic('logstart %s append' % self.logappend)
598 self.magic('logstart %s append' % self.logappend)
600 elif self.logfile:
599 elif self.logfile:
601 self.magic('logstart %s' % self.logfile)
600 self.magic('logstart %s' % self.logfile)
602 elif self.logstart:
601 elif self.logstart:
603 self.magic('logstart')
602 self.magic('logstart')
604
603
605 def init_deprecation_warnings(self):
604 def init_deprecation_warnings(self):
606 """
605 """
607 register default filter for deprecation warning.
606 register default filter for deprecation warning.
608
607
609 This will allow deprecation warning of function used interactively to show
608 This will allow deprecation warning of function used interactively to show
610 warning to users, and still hide deprecation warning from libraries import.
609 warning to users, and still hide deprecation warning from libraries import.
611 """
610 """
612 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
611 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
613
612
614 def init_builtins(self):
613 def init_builtins(self):
615 # A single, static flag that we set to True. Its presence indicates
614 # A single, static flag that we set to True. Its presence indicates
616 # that an IPython shell has been created, and we make no attempts at
615 # that an IPython shell has been created, and we make no attempts at
617 # removing on exit or representing the existence of more than one
616 # removing on exit or representing the existence of more than one
618 # IPython at a time.
617 # IPython at a time.
619 builtin_mod.__dict__['__IPYTHON__'] = True
618 builtin_mod.__dict__['__IPYTHON__'] = True
620
619
621 self.builtin_trap = BuiltinTrap(shell=self)
620 self.builtin_trap = BuiltinTrap(shell=self)
622
621
623 def init_inspector(self):
622 def init_inspector(self):
624 # Object inspector
623 # Object inspector
625 self.inspector = oinspect.Inspector(oinspect.InspectColors,
624 self.inspector = oinspect.Inspector(oinspect.InspectColors,
626 PyColorize.ANSICodeColors,
625 PyColorize.ANSICodeColors,
627 'NoColor',
626 'NoColor',
628 self.object_info_string_level)
627 self.object_info_string_level)
629
628
630 def init_io(self):
629 def init_io(self):
631 # This will just use sys.stdout and sys.stderr. If you want to
630 # This will just use sys.stdout and sys.stderr. If you want to
632 # override sys.stdout and sys.stderr themselves, you need to do that
631 # override sys.stdout and sys.stderr themselves, you need to do that
633 # *before* instantiating this class, because io holds onto
632 # *before* instantiating this class, because io holds onto
634 # references to the underlying streams.
633 # references to the underlying streams.
635 # io.std* are deprecated, but don't show our own deprecation warnings
634 # io.std* are deprecated, but don't show our own deprecation warnings
636 # during initialization of the deprecated API.
635 # during initialization of the deprecated API.
637 with warnings.catch_warnings():
636 with warnings.catch_warnings():
638 warnings.simplefilter('ignore', DeprecationWarning)
637 warnings.simplefilter('ignore', DeprecationWarning)
639 io.stdout = io.IOStream(sys.stdout)
638 io.stdout = io.IOStream(sys.stdout)
640 io.stderr = io.IOStream(sys.stderr)
639 io.stderr = io.IOStream(sys.stderr)
641
640
642 def init_prompts(self):
641 def init_prompts(self):
643 # Set system prompts, so that scripts can decide if they are running
642 # Set system prompts, so that scripts can decide if they are running
644 # interactively.
643 # interactively.
645 sys.ps1 = 'In : '
644 sys.ps1 = 'In : '
646 sys.ps2 = '...: '
645 sys.ps2 = '...: '
647 sys.ps3 = 'Out: '
646 sys.ps3 = 'Out: '
648
647
649 def init_display_formatter(self):
648 def init_display_formatter(self):
650 self.display_formatter = DisplayFormatter(parent=self)
649 self.display_formatter = DisplayFormatter(parent=self)
651 self.configurables.append(self.display_formatter)
650 self.configurables.append(self.display_formatter)
652
651
653 def init_display_pub(self):
652 def init_display_pub(self):
654 self.display_pub = self.display_pub_class(parent=self)
653 self.display_pub = self.display_pub_class(parent=self)
655 self.configurables.append(self.display_pub)
654 self.configurables.append(self.display_pub)
656
655
657 def init_data_pub(self):
656 def init_data_pub(self):
658 if not self.data_pub_class:
657 if not self.data_pub_class:
659 self.data_pub = None
658 self.data_pub = None
660 return
659 return
661 self.data_pub = self.data_pub_class(parent=self)
660 self.data_pub = self.data_pub_class(parent=self)
662 self.configurables.append(self.data_pub)
661 self.configurables.append(self.data_pub)
663
662
664 def init_displayhook(self):
663 def init_displayhook(self):
665 # Initialize displayhook, set in/out prompts and printing system
664 # Initialize displayhook, set in/out prompts and printing system
666 self.displayhook = self.displayhook_class(
665 self.displayhook = self.displayhook_class(
667 parent=self,
666 parent=self,
668 shell=self,
667 shell=self,
669 cache_size=self.cache_size,
668 cache_size=self.cache_size,
670 )
669 )
671 self.configurables.append(self.displayhook)
670 self.configurables.append(self.displayhook)
672 # This is a context manager that installs/revmoes the displayhook at
671 # This is a context manager that installs/revmoes the displayhook at
673 # the appropriate time.
672 # the appropriate time.
674 self.display_trap = DisplayTrap(hook=self.displayhook)
673 self.display_trap = DisplayTrap(hook=self.displayhook)
675
674
676 def init_virtualenv(self):
675 def init_virtualenv(self):
677 """Add a virtualenv to sys.path so the user can import modules from it.
676 """Add a virtualenv to sys.path so the user can import modules from it.
678 This isn't perfect: it doesn't use the Python interpreter with which the
677 This isn't perfect: it doesn't use the Python interpreter with which the
679 virtualenv was built, and it ignores the --no-site-packages option. A
678 virtualenv was built, and it ignores the --no-site-packages option. A
680 warning will appear suggesting the user installs IPython in the
679 warning will appear suggesting the user installs IPython in the
681 virtualenv, but for many cases, it probably works well enough.
680 virtualenv, but for many cases, it probably works well enough.
682
681
683 Adapted from code snippets online.
682 Adapted from code snippets online.
684
683
685 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
684 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
686 """
685 """
687 if 'VIRTUAL_ENV' not in os.environ:
686 if 'VIRTUAL_ENV' not in os.environ:
688 # Not in a virtualenv
687 # Not in a virtualenv
689 return
688 return
690
689
691 # venv detection:
690 # venv detection:
692 # stdlib venv may symlink sys.executable, so we can't use realpath.
691 # stdlib venv may symlink sys.executable, so we can't use realpath.
693 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
692 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
694 # So we just check every item in the symlink tree (generally <= 3)
693 # So we just check every item in the symlink tree (generally <= 3)
695 p = os.path.normcase(sys.executable)
694 p = os.path.normcase(sys.executable)
696 paths = [p]
695 paths = [p]
697 while os.path.islink(p):
696 while os.path.islink(p):
698 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
697 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
699 paths.append(p)
698 paths.append(p)
700 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
699 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
701 if any(p.startswith(p_venv) for p in paths):
700 if any(p.startswith(p_venv) for p in paths):
702 # Running properly in the virtualenv, don't need to do anything
701 # Running properly in the virtualenv, don't need to do anything
703 return
702 return
704
703
705 warn("Attempting to work in a virtualenv. If you encounter problems, please "
704 warn("Attempting to work in a virtualenv. If you encounter problems, please "
706 "install IPython inside the virtualenv.")
705 "install IPython inside the virtualenv.")
707 if sys.platform == "win32":
706 if sys.platform == "win32":
708 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
707 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
709 else:
708 else:
710 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
709 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
711 'python%d.%d' % sys.version_info[:2], 'site-packages')
710 'python%d.%d' % sys.version_info[:2], 'site-packages')
712
711
713 import site
712 import site
714 sys.path.insert(0, virtual_env)
713 sys.path.insert(0, virtual_env)
715 site.addsitedir(virtual_env)
714 site.addsitedir(virtual_env)
716
715
717 #-------------------------------------------------------------------------
716 #-------------------------------------------------------------------------
718 # Things related to injections into the sys module
717 # Things related to injections into the sys module
719 #-------------------------------------------------------------------------
718 #-------------------------------------------------------------------------
720
719
721 def save_sys_module_state(self):
720 def save_sys_module_state(self):
722 """Save the state of hooks in the sys module.
721 """Save the state of hooks in the sys module.
723
722
724 This has to be called after self.user_module is created.
723 This has to be called after self.user_module is created.
725 """
724 """
726 self._orig_sys_module_state = {'stdin': sys.stdin,
725 self._orig_sys_module_state = {'stdin': sys.stdin,
727 'stdout': sys.stdout,
726 'stdout': sys.stdout,
728 'stderr': sys.stderr,
727 'stderr': sys.stderr,
729 'excepthook': sys.excepthook}
728 'excepthook': sys.excepthook}
730 self._orig_sys_modules_main_name = self.user_module.__name__
729 self._orig_sys_modules_main_name = self.user_module.__name__
731 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
730 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
732
731
733 def restore_sys_module_state(self):
732 def restore_sys_module_state(self):
734 """Restore the state of the sys module."""
733 """Restore the state of the sys module."""
735 try:
734 try:
736 for k, v in iteritems(self._orig_sys_module_state):
735 for k, v in self._orig_sys_module_state.items():
737 setattr(sys, k, v)
736 setattr(sys, k, v)
738 except AttributeError:
737 except AttributeError:
739 pass
738 pass
740 # Reset what what done in self.init_sys_modules
739 # Reset what what done in self.init_sys_modules
741 if self._orig_sys_modules_main_mod is not None:
740 if self._orig_sys_modules_main_mod is not None:
742 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
741 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
743
742
744 #-------------------------------------------------------------------------
743 #-------------------------------------------------------------------------
745 # Things related to the banner
744 # Things related to the banner
746 #-------------------------------------------------------------------------
745 #-------------------------------------------------------------------------
747
746
748 @property
747 @property
749 def banner(self):
748 def banner(self):
750 banner = self.banner1
749 banner = self.banner1
751 if self.profile and self.profile != 'default':
750 if self.profile and self.profile != 'default':
752 banner += '\nIPython profile: %s\n' % self.profile
751 banner += '\nIPython profile: %s\n' % self.profile
753 if self.banner2:
752 if self.banner2:
754 banner += '\n' + self.banner2
753 banner += '\n' + self.banner2
755 return banner
754 return banner
756
755
757 def show_banner(self, banner=None):
756 def show_banner(self, banner=None):
758 if banner is None:
757 if banner is None:
759 banner = self.banner
758 banner = self.banner
760 sys.stdout.write(banner)
759 sys.stdout.write(banner)
761
760
762 #-------------------------------------------------------------------------
761 #-------------------------------------------------------------------------
763 # Things related to hooks
762 # Things related to hooks
764 #-------------------------------------------------------------------------
763 #-------------------------------------------------------------------------
765
764
766 def init_hooks(self):
765 def init_hooks(self):
767 # hooks holds pointers used for user-side customizations
766 # hooks holds pointers used for user-side customizations
768 self.hooks = Struct()
767 self.hooks = Struct()
769
768
770 self.strdispatchers = {}
769 self.strdispatchers = {}
771
770
772 # Set all default hooks, defined in the IPython.hooks module.
771 # Set all default hooks, defined in the IPython.hooks module.
773 hooks = IPython.core.hooks
772 hooks = IPython.core.hooks
774 for hook_name in hooks.__all__:
773 for hook_name in hooks.__all__:
775 # default hooks have priority 100, i.e. low; user hooks should have
774 # default hooks have priority 100, i.e. low; user hooks should have
776 # 0-100 priority
775 # 0-100 priority
777 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
776 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
778
777
779 if self.display_page:
778 if self.display_page:
780 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
779 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
781
780
782 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
781 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
783 _warn_deprecated=True):
782 _warn_deprecated=True):
784 """set_hook(name,hook) -> sets an internal IPython hook.
783 """set_hook(name,hook) -> sets an internal IPython hook.
785
784
786 IPython exposes some of its internal API as user-modifiable hooks. By
785 IPython exposes some of its internal API as user-modifiable hooks. By
787 adding your function to one of these hooks, you can modify IPython's
786 adding your function to one of these hooks, you can modify IPython's
788 behavior to call at runtime your own routines."""
787 behavior to call at runtime your own routines."""
789
788
790 # At some point in the future, this should validate the hook before it
789 # At some point in the future, this should validate the hook before it
791 # accepts it. Probably at least check that the hook takes the number
790 # accepts it. Probably at least check that the hook takes the number
792 # of args it's supposed to.
791 # of args it's supposed to.
793
792
794 f = types.MethodType(hook,self)
793 f = types.MethodType(hook,self)
795
794
796 # check if the hook is for strdispatcher first
795 # check if the hook is for strdispatcher first
797 if str_key is not None:
796 if str_key is not None:
798 sdp = self.strdispatchers.get(name, StrDispatch())
797 sdp = self.strdispatchers.get(name, StrDispatch())
799 sdp.add_s(str_key, f, priority )
798 sdp.add_s(str_key, f, priority )
800 self.strdispatchers[name] = sdp
799 self.strdispatchers[name] = sdp
801 return
800 return
802 if re_key is not None:
801 if re_key is not None:
803 sdp = self.strdispatchers.get(name, StrDispatch())
802 sdp = self.strdispatchers.get(name, StrDispatch())
804 sdp.add_re(re.compile(re_key), f, priority )
803 sdp.add_re(re.compile(re_key), f, priority )
805 self.strdispatchers[name] = sdp
804 self.strdispatchers[name] = sdp
806 return
805 return
807
806
808 dp = getattr(self.hooks, name, None)
807 dp = getattr(self.hooks, name, None)
809 if name not in IPython.core.hooks.__all__:
808 if name not in IPython.core.hooks.__all__:
810 print("Warning! Hook '%s' is not one of %s" % \
809 print("Warning! Hook '%s' is not one of %s" % \
811 (name, IPython.core.hooks.__all__ ))
810 (name, IPython.core.hooks.__all__ ))
812
811
813 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
812 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
814 alternative = IPython.core.hooks.deprecated[name]
813 alternative = IPython.core.hooks.deprecated[name]
815 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative), stacklevel=2)
814 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative), stacklevel=2)
816
815
817 if not dp:
816 if not dp:
818 dp = IPython.core.hooks.CommandChainDispatcher()
817 dp = IPython.core.hooks.CommandChainDispatcher()
819
818
820 try:
819 try:
821 dp.add(f,priority)
820 dp.add(f,priority)
822 except AttributeError:
821 except AttributeError:
823 # it was not commandchain, plain old func - replace
822 # it was not commandchain, plain old func - replace
824 dp = f
823 dp = f
825
824
826 setattr(self.hooks,name, dp)
825 setattr(self.hooks,name, dp)
827
826
828 #-------------------------------------------------------------------------
827 #-------------------------------------------------------------------------
829 # Things related to events
828 # Things related to events
830 #-------------------------------------------------------------------------
829 #-------------------------------------------------------------------------
831
830
832 def init_events(self):
831 def init_events(self):
833 self.events = EventManager(self, available_events)
832 self.events = EventManager(self, available_events)
834
833
835 self.events.register("pre_execute", self._clear_warning_registry)
834 self.events.register("pre_execute", self._clear_warning_registry)
836
835
837 def register_post_execute(self, func):
836 def register_post_execute(self, func):
838 """DEPRECATED: Use ip.events.register('post_run_cell', func)
837 """DEPRECATED: Use ip.events.register('post_run_cell', func)
839
838
840 Register a function for calling after code execution.
839 Register a function for calling after code execution.
841 """
840 """
842 warn("ip.register_post_execute is deprecated, use "
841 warn("ip.register_post_execute is deprecated, use "
843 "ip.events.register('post_run_cell', func) instead.", stacklevel=2)
842 "ip.events.register('post_run_cell', func) instead.", stacklevel=2)
844 self.events.register('post_run_cell', func)
843 self.events.register('post_run_cell', func)
845
844
846 def _clear_warning_registry(self):
845 def _clear_warning_registry(self):
847 # clear the warning registry, so that different code blocks with
846 # clear the warning registry, so that different code blocks with
848 # overlapping line number ranges don't cause spurious suppression of
847 # overlapping line number ranges don't cause spurious suppression of
849 # warnings (see gh-6611 for details)
848 # warnings (see gh-6611 for details)
850 if "__warningregistry__" in self.user_global_ns:
849 if "__warningregistry__" in self.user_global_ns:
851 del self.user_global_ns["__warningregistry__"]
850 del self.user_global_ns["__warningregistry__"]
852
851
853 #-------------------------------------------------------------------------
852 #-------------------------------------------------------------------------
854 # Things related to the "main" module
853 # Things related to the "main" module
855 #-------------------------------------------------------------------------
854 #-------------------------------------------------------------------------
856
855
857 def new_main_mod(self, filename, modname):
856 def new_main_mod(self, filename, modname):
858 """Return a new 'main' module object for user code execution.
857 """Return a new 'main' module object for user code execution.
859
858
860 ``filename`` should be the path of the script which will be run in the
859 ``filename`` should be the path of the script which will be run in the
861 module. Requests with the same filename will get the same module, with
860 module. Requests with the same filename will get the same module, with
862 its namespace cleared.
861 its namespace cleared.
863
862
864 ``modname`` should be the module name - normally either '__main__' or
863 ``modname`` should be the module name - normally either '__main__' or
865 the basename of the file without the extension.
864 the basename of the file without the extension.
866
865
867 When scripts are executed via %run, we must keep a reference to their
866 When scripts are executed via %run, we must keep a reference to their
868 __main__ module around so that Python doesn't
867 __main__ module around so that Python doesn't
869 clear it, rendering references to module globals useless.
868 clear it, rendering references to module globals useless.
870
869
871 This method keeps said reference in a private dict, keyed by the
870 This method keeps said reference in a private dict, keyed by the
872 absolute path of the script. This way, for multiple executions of the
871 absolute path of the script. This way, for multiple executions of the
873 same script we only keep one copy of the namespace (the last one),
872 same script we only keep one copy of the namespace (the last one),
874 thus preventing memory leaks from old references while allowing the
873 thus preventing memory leaks from old references while allowing the
875 objects from the last execution to be accessible.
874 objects from the last execution to be accessible.
876 """
875 """
877 filename = os.path.abspath(filename)
876 filename = os.path.abspath(filename)
878 try:
877 try:
879 main_mod = self._main_mod_cache[filename]
878 main_mod = self._main_mod_cache[filename]
880 except KeyError:
879 except KeyError:
881 main_mod = self._main_mod_cache[filename] = types.ModuleType(
880 main_mod = self._main_mod_cache[filename] = types.ModuleType(
882 py3compat.cast_bytes_py2(modname),
881 py3compat.cast_bytes_py2(modname),
883 doc="Module created for script run in IPython")
882 doc="Module created for script run in IPython")
884 else:
883 else:
885 main_mod.__dict__.clear()
884 main_mod.__dict__.clear()
886 main_mod.__name__ = modname
885 main_mod.__name__ = modname
887
886
888 main_mod.__file__ = filename
887 main_mod.__file__ = filename
889 # It seems pydoc (and perhaps others) needs any module instance to
888 # It seems pydoc (and perhaps others) needs any module instance to
890 # implement a __nonzero__ method
889 # implement a __nonzero__ method
891 main_mod.__nonzero__ = lambda : True
890 main_mod.__nonzero__ = lambda : True
892
891
893 return main_mod
892 return main_mod
894
893
895 def clear_main_mod_cache(self):
894 def clear_main_mod_cache(self):
896 """Clear the cache of main modules.
895 """Clear the cache of main modules.
897
896
898 Mainly for use by utilities like %reset.
897 Mainly for use by utilities like %reset.
899
898
900 Examples
899 Examples
901 --------
900 --------
902
901
903 In [15]: import IPython
902 In [15]: import IPython
904
903
905 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
904 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
906
905
907 In [17]: len(_ip._main_mod_cache) > 0
906 In [17]: len(_ip._main_mod_cache) > 0
908 Out[17]: True
907 Out[17]: True
909
908
910 In [18]: _ip.clear_main_mod_cache()
909 In [18]: _ip.clear_main_mod_cache()
911
910
912 In [19]: len(_ip._main_mod_cache) == 0
911 In [19]: len(_ip._main_mod_cache) == 0
913 Out[19]: True
912 Out[19]: True
914 """
913 """
915 self._main_mod_cache.clear()
914 self._main_mod_cache.clear()
916
915
917 #-------------------------------------------------------------------------
916 #-------------------------------------------------------------------------
918 # Things related to debugging
917 # Things related to debugging
919 #-------------------------------------------------------------------------
918 #-------------------------------------------------------------------------
920
919
921 def init_pdb(self):
920 def init_pdb(self):
922 # Set calling of pdb on exceptions
921 # Set calling of pdb on exceptions
923 # self.call_pdb is a property
922 # self.call_pdb is a property
924 self.call_pdb = self.pdb
923 self.call_pdb = self.pdb
925
924
926 def _get_call_pdb(self):
925 def _get_call_pdb(self):
927 return self._call_pdb
926 return self._call_pdb
928
927
929 def _set_call_pdb(self,val):
928 def _set_call_pdb(self,val):
930
929
931 if val not in (0,1,False,True):
930 if val not in (0,1,False,True):
932 raise ValueError('new call_pdb value must be boolean')
931 raise ValueError('new call_pdb value must be boolean')
933
932
934 # store value in instance
933 # store value in instance
935 self._call_pdb = val
934 self._call_pdb = val
936
935
937 # notify the actual exception handlers
936 # notify the actual exception handlers
938 self.InteractiveTB.call_pdb = val
937 self.InteractiveTB.call_pdb = val
939
938
940 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
939 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
941 'Control auto-activation of pdb at exceptions')
940 'Control auto-activation of pdb at exceptions')
942
941
943 def debugger(self,force=False):
942 def debugger(self,force=False):
944 """Call the pdb debugger.
943 """Call the pdb debugger.
945
944
946 Keywords:
945 Keywords:
947
946
948 - force(False): by default, this routine checks the instance call_pdb
947 - force(False): by default, this routine checks the instance call_pdb
949 flag and does not actually invoke the debugger if the flag is false.
948 flag and does not actually invoke the debugger if the flag is false.
950 The 'force' option forces the debugger to activate even if the flag
949 The 'force' option forces the debugger to activate even if the flag
951 is false.
950 is false.
952 """
951 """
953
952
954 if not (force or self.call_pdb):
953 if not (force or self.call_pdb):
955 return
954 return
956
955
957 if not hasattr(sys,'last_traceback'):
956 if not hasattr(sys,'last_traceback'):
958 error('No traceback has been produced, nothing to debug.')
957 error('No traceback has been produced, nothing to debug.')
959 return
958 return
960
959
961 self.InteractiveTB.debugger(force=True)
960 self.InteractiveTB.debugger(force=True)
962
961
963 #-------------------------------------------------------------------------
962 #-------------------------------------------------------------------------
964 # Things related to IPython's various namespaces
963 # Things related to IPython's various namespaces
965 #-------------------------------------------------------------------------
964 #-------------------------------------------------------------------------
966 default_user_namespaces = True
965 default_user_namespaces = True
967
966
968 def init_create_namespaces(self, user_module=None, user_ns=None):
967 def init_create_namespaces(self, user_module=None, user_ns=None):
969 # Create the namespace where the user will operate. user_ns is
968 # Create the namespace where the user will operate. user_ns is
970 # normally the only one used, and it is passed to the exec calls as
969 # normally the only one used, and it is passed to the exec calls as
971 # the locals argument. But we do carry a user_global_ns namespace
970 # the locals argument. But we do carry a user_global_ns namespace
972 # given as the exec 'globals' argument, This is useful in embedding
971 # given as the exec 'globals' argument, This is useful in embedding
973 # situations where the ipython shell opens in a context where the
972 # situations where the ipython shell opens in a context where the
974 # distinction between locals and globals is meaningful. For
973 # distinction between locals and globals is meaningful. For
975 # non-embedded contexts, it is just the same object as the user_ns dict.
974 # non-embedded contexts, it is just the same object as the user_ns dict.
976
975
977 # FIXME. For some strange reason, __builtins__ is showing up at user
976 # FIXME. For some strange reason, __builtins__ is showing up at user
978 # level as a dict instead of a module. This is a manual fix, but I
977 # level as a dict instead of a module. This is a manual fix, but I
979 # should really track down where the problem is coming from. Alex
978 # should really track down where the problem is coming from. Alex
980 # Schmolck reported this problem first.
979 # Schmolck reported this problem first.
981
980
982 # A useful post by Alex Martelli on this topic:
981 # A useful post by Alex Martelli on this topic:
983 # Re: inconsistent value from __builtins__
982 # Re: inconsistent value from __builtins__
984 # Von: Alex Martelli <aleaxit@yahoo.com>
983 # Von: Alex Martelli <aleaxit@yahoo.com>
985 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
984 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
986 # Gruppen: comp.lang.python
985 # Gruppen: comp.lang.python
987
986
988 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
987 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
989 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
988 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
990 # > <type 'dict'>
989 # > <type 'dict'>
991 # > >>> print type(__builtins__)
990 # > >>> print type(__builtins__)
992 # > <type 'module'>
991 # > <type 'module'>
993 # > Is this difference in return value intentional?
992 # > Is this difference in return value intentional?
994
993
995 # Well, it's documented that '__builtins__' can be either a dictionary
994 # Well, it's documented that '__builtins__' can be either a dictionary
996 # or a module, and it's been that way for a long time. Whether it's
995 # or a module, and it's been that way for a long time. Whether it's
997 # intentional (or sensible), I don't know. In any case, the idea is
996 # intentional (or sensible), I don't know. In any case, the idea is
998 # that if you need to access the built-in namespace directly, you
997 # that if you need to access the built-in namespace directly, you
999 # should start with "import __builtin__" (note, no 's') which will
998 # should start with "import __builtin__" (note, no 's') which will
1000 # definitely give you a module. Yeah, it's somewhat confusing:-(.
999 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1001
1000
1002 # These routines return a properly built module and dict as needed by
1001 # These routines return a properly built module and dict as needed by
1003 # the rest of the code, and can also be used by extension writers to
1002 # the rest of the code, and can also be used by extension writers to
1004 # generate properly initialized namespaces.
1003 # generate properly initialized namespaces.
1005 if (user_ns is not None) or (user_module is not None):
1004 if (user_ns is not None) or (user_module is not None):
1006 self.default_user_namespaces = False
1005 self.default_user_namespaces = False
1007 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1006 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1008
1007
1009 # A record of hidden variables we have added to the user namespace, so
1008 # A record of hidden variables we have added to the user namespace, so
1010 # we can list later only variables defined in actual interactive use.
1009 # we can list later only variables defined in actual interactive use.
1011 self.user_ns_hidden = {}
1010 self.user_ns_hidden = {}
1012
1011
1013 # Now that FakeModule produces a real module, we've run into a nasty
1012 # Now that FakeModule produces a real module, we've run into a nasty
1014 # problem: after script execution (via %run), the module where the user
1013 # problem: after script execution (via %run), the module where the user
1015 # code ran is deleted. Now that this object is a true module (needed
1014 # code ran is deleted. Now that this object is a true module (needed
1016 # so doctest and other tools work correctly), the Python module
1015 # so doctest and other tools work correctly), the Python module
1017 # teardown mechanism runs over it, and sets to None every variable
1016 # teardown mechanism runs over it, and sets to None every variable
1018 # present in that module. Top-level references to objects from the
1017 # present in that module. Top-level references to objects from the
1019 # script survive, because the user_ns is updated with them. However,
1018 # script survive, because the user_ns is updated with them. However,
1020 # calling functions defined in the script that use other things from
1019 # calling functions defined in the script that use other things from
1021 # the script will fail, because the function's closure had references
1020 # the script will fail, because the function's closure had references
1022 # to the original objects, which are now all None. So we must protect
1021 # to the original objects, which are now all None. So we must protect
1023 # these modules from deletion by keeping a cache.
1022 # these modules from deletion by keeping a cache.
1024 #
1023 #
1025 # To avoid keeping stale modules around (we only need the one from the
1024 # To avoid keeping stale modules around (we only need the one from the
1026 # last run), we use a dict keyed with the full path to the script, so
1025 # last run), we use a dict keyed with the full path to the script, so
1027 # only the last version of the module is held in the cache. Note,
1026 # only the last version of the module is held in the cache. Note,
1028 # however, that we must cache the module *namespace contents* (their
1027 # however, that we must cache the module *namespace contents* (their
1029 # __dict__). Because if we try to cache the actual modules, old ones
1028 # __dict__). Because if we try to cache the actual modules, old ones
1030 # (uncached) could be destroyed while still holding references (such as
1029 # (uncached) could be destroyed while still holding references (such as
1031 # those held by GUI objects that tend to be long-lived)>
1030 # those held by GUI objects that tend to be long-lived)>
1032 #
1031 #
1033 # The %reset command will flush this cache. See the cache_main_mod()
1032 # The %reset command will flush this cache. See the cache_main_mod()
1034 # and clear_main_mod_cache() methods for details on use.
1033 # and clear_main_mod_cache() methods for details on use.
1035
1034
1036 # This is the cache used for 'main' namespaces
1035 # This is the cache used for 'main' namespaces
1037 self._main_mod_cache = {}
1036 self._main_mod_cache = {}
1038
1037
1039 # A table holding all the namespaces IPython deals with, so that
1038 # A table holding all the namespaces IPython deals with, so that
1040 # introspection facilities can search easily.
1039 # introspection facilities can search easily.
1041 self.ns_table = {'user_global':self.user_module.__dict__,
1040 self.ns_table = {'user_global':self.user_module.__dict__,
1042 'user_local':self.user_ns,
1041 'user_local':self.user_ns,
1043 'builtin':builtin_mod.__dict__
1042 'builtin':builtin_mod.__dict__
1044 }
1043 }
1045
1044
1046 @property
1045 @property
1047 def user_global_ns(self):
1046 def user_global_ns(self):
1048 return self.user_module.__dict__
1047 return self.user_module.__dict__
1049
1048
1050 def prepare_user_module(self, user_module=None, user_ns=None):
1049 def prepare_user_module(self, user_module=None, user_ns=None):
1051 """Prepare the module and namespace in which user code will be run.
1050 """Prepare the module and namespace in which user code will be run.
1052
1051
1053 When IPython is started normally, both parameters are None: a new module
1052 When IPython is started normally, both parameters are None: a new module
1054 is created automatically, and its __dict__ used as the namespace.
1053 is created automatically, and its __dict__ used as the namespace.
1055
1054
1056 If only user_module is provided, its __dict__ is used as the namespace.
1055 If only user_module is provided, its __dict__ is used as the namespace.
1057 If only user_ns is provided, a dummy module is created, and user_ns
1056 If only user_ns is provided, a dummy module is created, and user_ns
1058 becomes the global namespace. If both are provided (as they may be
1057 becomes the global namespace. If both are provided (as they may be
1059 when embedding), user_ns is the local namespace, and user_module
1058 when embedding), user_ns is the local namespace, and user_module
1060 provides the global namespace.
1059 provides the global namespace.
1061
1060
1062 Parameters
1061 Parameters
1063 ----------
1062 ----------
1064 user_module : module, optional
1063 user_module : module, optional
1065 The current user module in which IPython is being run. If None,
1064 The current user module in which IPython is being run. If None,
1066 a clean module will be created.
1065 a clean module will be created.
1067 user_ns : dict, optional
1066 user_ns : dict, optional
1068 A namespace in which to run interactive commands.
1067 A namespace in which to run interactive commands.
1069
1068
1070 Returns
1069 Returns
1071 -------
1070 -------
1072 A tuple of user_module and user_ns, each properly initialised.
1071 A tuple of user_module and user_ns, each properly initialised.
1073 """
1072 """
1074 if user_module is None and user_ns is not None:
1073 if user_module is None and user_ns is not None:
1075 user_ns.setdefault("__name__", "__main__")
1074 user_ns.setdefault("__name__", "__main__")
1076 user_module = DummyMod()
1075 user_module = DummyMod()
1077 user_module.__dict__ = user_ns
1076 user_module.__dict__ = user_ns
1078
1077
1079 if user_module is None:
1078 if user_module is None:
1080 user_module = types.ModuleType("__main__",
1079 user_module = types.ModuleType("__main__",
1081 doc="Automatically created module for IPython interactive environment")
1080 doc="Automatically created module for IPython interactive environment")
1082
1081
1083 # We must ensure that __builtin__ (without the final 's') is always
1082 # We must ensure that __builtin__ (without the final 's') is always
1084 # available and pointing to the __builtin__ *module*. For more details:
1083 # available and pointing to the __builtin__ *module*. For more details:
1085 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1084 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1086 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1085 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1087 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1086 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1088
1087
1089 if user_ns is None:
1088 if user_ns is None:
1090 user_ns = user_module.__dict__
1089 user_ns = user_module.__dict__
1091
1090
1092 return user_module, user_ns
1091 return user_module, user_ns
1093
1092
1094 def init_sys_modules(self):
1093 def init_sys_modules(self):
1095 # We need to insert into sys.modules something that looks like a
1094 # We need to insert into sys.modules something that looks like a
1096 # module but which accesses the IPython namespace, for shelve and
1095 # module but which accesses the IPython namespace, for shelve and
1097 # pickle to work interactively. Normally they rely on getting
1096 # pickle to work interactively. Normally they rely on getting
1098 # everything out of __main__, but for embedding purposes each IPython
1097 # everything out of __main__, but for embedding purposes each IPython
1099 # instance has its own private namespace, so we can't go shoving
1098 # instance has its own private namespace, so we can't go shoving
1100 # everything into __main__.
1099 # everything into __main__.
1101
1100
1102 # note, however, that we should only do this for non-embedded
1101 # note, however, that we should only do this for non-embedded
1103 # ipythons, which really mimic the __main__.__dict__ with their own
1102 # ipythons, which really mimic the __main__.__dict__ with their own
1104 # namespace. Embedded instances, on the other hand, should not do
1103 # namespace. Embedded instances, on the other hand, should not do
1105 # this because they need to manage the user local/global namespaces
1104 # this because they need to manage the user local/global namespaces
1106 # only, but they live within a 'normal' __main__ (meaning, they
1105 # only, but they live within a 'normal' __main__ (meaning, they
1107 # shouldn't overtake the execution environment of the script they're
1106 # shouldn't overtake the execution environment of the script they're
1108 # embedded in).
1107 # embedded in).
1109
1108
1110 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1109 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1111 main_name = self.user_module.__name__
1110 main_name = self.user_module.__name__
1112 sys.modules[main_name] = self.user_module
1111 sys.modules[main_name] = self.user_module
1113
1112
1114 def init_user_ns(self):
1113 def init_user_ns(self):
1115 """Initialize all user-visible namespaces to their minimum defaults.
1114 """Initialize all user-visible namespaces to their minimum defaults.
1116
1115
1117 Certain history lists are also initialized here, as they effectively
1116 Certain history lists are also initialized here, as they effectively
1118 act as user namespaces.
1117 act as user namespaces.
1119
1118
1120 Notes
1119 Notes
1121 -----
1120 -----
1122 All data structures here are only filled in, they are NOT reset by this
1121 All data structures here are only filled in, they are NOT reset by this
1123 method. If they were not empty before, data will simply be added to
1122 method. If they were not empty before, data will simply be added to
1124 therm.
1123 therm.
1125 """
1124 """
1126 # This function works in two parts: first we put a few things in
1125 # This function works in two parts: first we put a few things in
1127 # user_ns, and we sync that contents into user_ns_hidden so that these
1126 # user_ns, and we sync that contents into user_ns_hidden so that these
1128 # initial variables aren't shown by %who. After the sync, we add the
1127 # initial variables aren't shown by %who. After the sync, we add the
1129 # rest of what we *do* want the user to see with %who even on a new
1128 # rest of what we *do* want the user to see with %who even on a new
1130 # session (probably nothing, so they really only see their own stuff)
1129 # session (probably nothing, so they really only see their own stuff)
1131
1130
1132 # The user dict must *always* have a __builtin__ reference to the
1131 # The user dict must *always* have a __builtin__ reference to the
1133 # Python standard __builtin__ namespace, which must be imported.
1132 # Python standard __builtin__ namespace, which must be imported.
1134 # This is so that certain operations in prompt evaluation can be
1133 # This is so that certain operations in prompt evaluation can be
1135 # reliably executed with builtins. Note that we can NOT use
1134 # reliably executed with builtins. Note that we can NOT use
1136 # __builtins__ (note the 's'), because that can either be a dict or a
1135 # __builtins__ (note the 's'), because that can either be a dict or a
1137 # module, and can even mutate at runtime, depending on the context
1136 # module, and can even mutate at runtime, depending on the context
1138 # (Python makes no guarantees on it). In contrast, __builtin__ is
1137 # (Python makes no guarantees on it). In contrast, __builtin__ is
1139 # always a module object, though it must be explicitly imported.
1138 # always a module object, though it must be explicitly imported.
1140
1139
1141 # For more details:
1140 # For more details:
1142 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1141 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1143 ns = dict()
1142 ns = dict()
1144
1143
1145 # make global variables for user access to the histories
1144 # make global variables for user access to the histories
1146 ns['_ih'] = self.history_manager.input_hist_parsed
1145 ns['_ih'] = self.history_manager.input_hist_parsed
1147 ns['_oh'] = self.history_manager.output_hist
1146 ns['_oh'] = self.history_manager.output_hist
1148 ns['_dh'] = self.history_manager.dir_hist
1147 ns['_dh'] = self.history_manager.dir_hist
1149
1148
1150 ns['_sh'] = shadowns
1149 ns['_sh'] = shadowns
1151
1150
1152 # user aliases to input and output histories. These shouldn't show up
1151 # user aliases to input and output histories. These shouldn't show up
1153 # in %who, as they can have very large reprs.
1152 # in %who, as they can have very large reprs.
1154 ns['In'] = self.history_manager.input_hist_parsed
1153 ns['In'] = self.history_manager.input_hist_parsed
1155 ns['Out'] = self.history_manager.output_hist
1154 ns['Out'] = self.history_manager.output_hist
1156
1155
1157 # Store myself as the public api!!!
1156 # Store myself as the public api!!!
1158 ns['get_ipython'] = self.get_ipython
1157 ns['get_ipython'] = self.get_ipython
1159
1158
1160 ns['exit'] = self.exiter
1159 ns['exit'] = self.exiter
1161 ns['quit'] = self.exiter
1160 ns['quit'] = self.exiter
1162
1161
1163 # Sync what we've added so far to user_ns_hidden so these aren't seen
1162 # Sync what we've added so far to user_ns_hidden so these aren't seen
1164 # by %who
1163 # by %who
1165 self.user_ns_hidden.update(ns)
1164 self.user_ns_hidden.update(ns)
1166
1165
1167 # Anything put into ns now would show up in %who. Think twice before
1166 # Anything put into ns now would show up in %who. Think twice before
1168 # putting anything here, as we really want %who to show the user their
1167 # putting anything here, as we really want %who to show the user their
1169 # stuff, not our variables.
1168 # stuff, not our variables.
1170
1169
1171 # Finally, update the real user's namespace
1170 # Finally, update the real user's namespace
1172 self.user_ns.update(ns)
1171 self.user_ns.update(ns)
1173
1172
1174 @property
1173 @property
1175 def all_ns_refs(self):
1174 def all_ns_refs(self):
1176 """Get a list of references to all the namespace dictionaries in which
1175 """Get a list of references to all the namespace dictionaries in which
1177 IPython might store a user-created object.
1176 IPython might store a user-created object.
1178
1177
1179 Note that this does not include the displayhook, which also caches
1178 Note that this does not include the displayhook, which also caches
1180 objects from the output."""
1179 objects from the output."""
1181 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1180 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1182 [m.__dict__ for m in self._main_mod_cache.values()]
1181 [m.__dict__ for m in self._main_mod_cache.values()]
1183
1182
1184 def reset(self, new_session=True):
1183 def reset(self, new_session=True):
1185 """Clear all internal namespaces, and attempt to release references to
1184 """Clear all internal namespaces, and attempt to release references to
1186 user objects.
1185 user objects.
1187
1186
1188 If new_session is True, a new history session will be opened.
1187 If new_session is True, a new history session will be opened.
1189 """
1188 """
1190 # Clear histories
1189 # Clear histories
1191 self.history_manager.reset(new_session)
1190 self.history_manager.reset(new_session)
1192 # Reset counter used to index all histories
1191 # Reset counter used to index all histories
1193 if new_session:
1192 if new_session:
1194 self.execution_count = 1
1193 self.execution_count = 1
1195
1194
1196 # Flush cached output items
1195 # Flush cached output items
1197 if self.displayhook.do_full_cache:
1196 if self.displayhook.do_full_cache:
1198 self.displayhook.flush()
1197 self.displayhook.flush()
1199
1198
1200 # The main execution namespaces must be cleared very carefully,
1199 # The main execution namespaces must be cleared very carefully,
1201 # skipping the deletion of the builtin-related keys, because doing so
1200 # skipping the deletion of the builtin-related keys, because doing so
1202 # would cause errors in many object's __del__ methods.
1201 # would cause errors in many object's __del__ methods.
1203 if self.user_ns is not self.user_global_ns:
1202 if self.user_ns is not self.user_global_ns:
1204 self.user_ns.clear()
1203 self.user_ns.clear()
1205 ns = self.user_global_ns
1204 ns = self.user_global_ns
1206 drop_keys = set(ns.keys())
1205 drop_keys = set(ns.keys())
1207 drop_keys.discard('__builtin__')
1206 drop_keys.discard('__builtin__')
1208 drop_keys.discard('__builtins__')
1207 drop_keys.discard('__builtins__')
1209 drop_keys.discard('__name__')
1208 drop_keys.discard('__name__')
1210 for k in drop_keys:
1209 for k in drop_keys:
1211 del ns[k]
1210 del ns[k]
1212
1211
1213 self.user_ns_hidden.clear()
1212 self.user_ns_hidden.clear()
1214
1213
1215 # Restore the user namespaces to minimal usability
1214 # Restore the user namespaces to minimal usability
1216 self.init_user_ns()
1215 self.init_user_ns()
1217
1216
1218 # Restore the default and user aliases
1217 # Restore the default and user aliases
1219 self.alias_manager.clear_aliases()
1218 self.alias_manager.clear_aliases()
1220 self.alias_manager.init_aliases()
1219 self.alias_manager.init_aliases()
1221
1220
1222 # Flush the private list of module references kept for script
1221 # Flush the private list of module references kept for script
1223 # execution protection
1222 # execution protection
1224 self.clear_main_mod_cache()
1223 self.clear_main_mod_cache()
1225
1224
1226 def del_var(self, varname, by_name=False):
1225 def del_var(self, varname, by_name=False):
1227 """Delete a variable from the various namespaces, so that, as
1226 """Delete a variable from the various namespaces, so that, as
1228 far as possible, we're not keeping any hidden references to it.
1227 far as possible, we're not keeping any hidden references to it.
1229
1228
1230 Parameters
1229 Parameters
1231 ----------
1230 ----------
1232 varname : str
1231 varname : str
1233 The name of the variable to delete.
1232 The name of the variable to delete.
1234 by_name : bool
1233 by_name : bool
1235 If True, delete variables with the given name in each
1234 If True, delete variables with the given name in each
1236 namespace. If False (default), find the variable in the user
1235 namespace. If False (default), find the variable in the user
1237 namespace, and delete references to it.
1236 namespace, and delete references to it.
1238 """
1237 """
1239 if varname in ('__builtin__', '__builtins__'):
1238 if varname in ('__builtin__', '__builtins__'):
1240 raise ValueError("Refusing to delete %s" % varname)
1239 raise ValueError("Refusing to delete %s" % varname)
1241
1240
1242 ns_refs = self.all_ns_refs
1241 ns_refs = self.all_ns_refs
1243
1242
1244 if by_name: # Delete by name
1243 if by_name: # Delete by name
1245 for ns in ns_refs:
1244 for ns in ns_refs:
1246 try:
1245 try:
1247 del ns[varname]
1246 del ns[varname]
1248 except KeyError:
1247 except KeyError:
1249 pass
1248 pass
1250 else: # Delete by object
1249 else: # Delete by object
1251 try:
1250 try:
1252 obj = self.user_ns[varname]
1251 obj = self.user_ns[varname]
1253 except KeyError:
1252 except KeyError:
1254 raise NameError("name '%s' is not defined" % varname)
1253 raise NameError("name '%s' is not defined" % varname)
1255 # Also check in output history
1254 # Also check in output history
1256 ns_refs.append(self.history_manager.output_hist)
1255 ns_refs.append(self.history_manager.output_hist)
1257 for ns in ns_refs:
1256 for ns in ns_refs:
1258 to_delete = [n for n, o in iteritems(ns) if o is obj]
1257 to_delete = [n for n, o in ns.items() if o is obj]
1259 for name in to_delete:
1258 for name in to_delete:
1260 del ns[name]
1259 del ns[name]
1261
1260
1262 # displayhook keeps extra references, but not in a dictionary
1261 # displayhook keeps extra references, but not in a dictionary
1263 for name in ('_', '__', '___'):
1262 for name in ('_', '__', '___'):
1264 if getattr(self.displayhook, name) is obj:
1263 if getattr(self.displayhook, name) is obj:
1265 setattr(self.displayhook, name, None)
1264 setattr(self.displayhook, name, None)
1266
1265
1267 def reset_selective(self, regex=None):
1266 def reset_selective(self, regex=None):
1268 """Clear selective variables from internal namespaces based on a
1267 """Clear selective variables from internal namespaces based on a
1269 specified regular expression.
1268 specified regular expression.
1270
1269
1271 Parameters
1270 Parameters
1272 ----------
1271 ----------
1273 regex : string or compiled pattern, optional
1272 regex : string or compiled pattern, optional
1274 A regular expression pattern that will be used in searching
1273 A regular expression pattern that will be used in searching
1275 variable names in the users namespaces.
1274 variable names in the users namespaces.
1276 """
1275 """
1277 if regex is not None:
1276 if regex is not None:
1278 try:
1277 try:
1279 m = re.compile(regex)
1278 m = re.compile(regex)
1280 except TypeError:
1279 except TypeError:
1281 raise TypeError('regex must be a string or compiled pattern')
1280 raise TypeError('regex must be a string or compiled pattern')
1282 # Search for keys in each namespace that match the given regex
1281 # Search for keys in each namespace that match the given regex
1283 # If a match is found, delete the key/value pair.
1282 # If a match is found, delete the key/value pair.
1284 for ns in self.all_ns_refs:
1283 for ns in self.all_ns_refs:
1285 for var in ns:
1284 for var in ns:
1286 if m.search(var):
1285 if m.search(var):
1287 del ns[var]
1286 del ns[var]
1288
1287
1289 def push(self, variables, interactive=True):
1288 def push(self, variables, interactive=True):
1290 """Inject a group of variables into the IPython user namespace.
1289 """Inject a group of variables into the IPython user namespace.
1291
1290
1292 Parameters
1291 Parameters
1293 ----------
1292 ----------
1294 variables : dict, str or list/tuple of str
1293 variables : dict, str or list/tuple of str
1295 The variables to inject into the user's namespace. If a dict, a
1294 The variables to inject into the user's namespace. If a dict, a
1296 simple update is done. If a str, the string is assumed to have
1295 simple update is done. If a str, the string is assumed to have
1297 variable names separated by spaces. A list/tuple of str can also
1296 variable names separated by spaces. A list/tuple of str can also
1298 be used to give the variable names. If just the variable names are
1297 be used to give the variable names. If just the variable names are
1299 give (list/tuple/str) then the variable values looked up in the
1298 give (list/tuple/str) then the variable values looked up in the
1300 callers frame.
1299 callers frame.
1301 interactive : bool
1300 interactive : bool
1302 If True (default), the variables will be listed with the ``who``
1301 If True (default), the variables will be listed with the ``who``
1303 magic.
1302 magic.
1304 """
1303 """
1305 vdict = None
1304 vdict = None
1306
1305
1307 # We need a dict of name/value pairs to do namespace updates.
1306 # We need a dict of name/value pairs to do namespace updates.
1308 if isinstance(variables, dict):
1307 if isinstance(variables, dict):
1309 vdict = variables
1308 vdict = variables
1310 elif isinstance(variables, string_types+(list, tuple)):
1309 elif isinstance(variables, (str, list, tuple)):
1311 if isinstance(variables, string_types):
1310 if isinstance(variables, str):
1312 vlist = variables.split()
1311 vlist = variables.split()
1313 else:
1312 else:
1314 vlist = variables
1313 vlist = variables
1315 vdict = {}
1314 vdict = {}
1316 cf = sys._getframe(1)
1315 cf = sys._getframe(1)
1317 for name in vlist:
1316 for name in vlist:
1318 try:
1317 try:
1319 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1318 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1320 except:
1319 except:
1321 print('Could not get variable %s from %s' %
1320 print('Could not get variable %s from %s' %
1322 (name,cf.f_code.co_name))
1321 (name,cf.f_code.co_name))
1323 else:
1322 else:
1324 raise ValueError('variables must be a dict/str/list/tuple')
1323 raise ValueError('variables must be a dict/str/list/tuple')
1325
1324
1326 # Propagate variables to user namespace
1325 # Propagate variables to user namespace
1327 self.user_ns.update(vdict)
1326 self.user_ns.update(vdict)
1328
1327
1329 # And configure interactive visibility
1328 # And configure interactive visibility
1330 user_ns_hidden = self.user_ns_hidden
1329 user_ns_hidden = self.user_ns_hidden
1331 if interactive:
1330 if interactive:
1332 for name in vdict:
1331 for name in vdict:
1333 user_ns_hidden.pop(name, None)
1332 user_ns_hidden.pop(name, None)
1334 else:
1333 else:
1335 user_ns_hidden.update(vdict)
1334 user_ns_hidden.update(vdict)
1336
1335
1337 def drop_by_id(self, variables):
1336 def drop_by_id(self, variables):
1338 """Remove a dict of variables from the user namespace, if they are the
1337 """Remove a dict of variables from the user namespace, if they are the
1339 same as the values in the dictionary.
1338 same as the values in the dictionary.
1340
1339
1341 This is intended for use by extensions: variables that they've added can
1340 This is intended for use by extensions: variables that they've added can
1342 be taken back out if they are unloaded, without removing any that the
1341 be taken back out if they are unloaded, without removing any that the
1343 user has overwritten.
1342 user has overwritten.
1344
1343
1345 Parameters
1344 Parameters
1346 ----------
1345 ----------
1347 variables : dict
1346 variables : dict
1348 A dictionary mapping object names (as strings) to the objects.
1347 A dictionary mapping object names (as strings) to the objects.
1349 """
1348 """
1350 for name, obj in iteritems(variables):
1349 for name, obj in variables.items():
1351 if name in self.user_ns and self.user_ns[name] is obj:
1350 if name in self.user_ns and self.user_ns[name] is obj:
1352 del self.user_ns[name]
1351 del self.user_ns[name]
1353 self.user_ns_hidden.pop(name, None)
1352 self.user_ns_hidden.pop(name, None)
1354
1353
1355 #-------------------------------------------------------------------------
1354 #-------------------------------------------------------------------------
1356 # Things related to object introspection
1355 # Things related to object introspection
1357 #-------------------------------------------------------------------------
1356 #-------------------------------------------------------------------------
1358
1357
1359 def _ofind(self, oname, namespaces=None):
1358 def _ofind(self, oname, namespaces=None):
1360 """Find an object in the available namespaces.
1359 """Find an object in the available namespaces.
1361
1360
1362 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1361 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1363
1362
1364 Has special code to detect magic functions.
1363 Has special code to detect magic functions.
1365 """
1364 """
1366 oname = oname.strip()
1365 oname = oname.strip()
1367 #print '1- oname: <%r>' % oname # dbg
1366 #print '1- oname: <%r>' % oname # dbg
1368 if not oname.startswith(ESC_MAGIC) and \
1367 if not oname.startswith(ESC_MAGIC) and \
1369 not oname.startswith(ESC_MAGIC2) and \
1368 not oname.startswith(ESC_MAGIC2) and \
1370 not py3compat.isidentifier(oname, dotted=True):
1369 not py3compat.isidentifier(oname, dotted=True):
1371 return dict(found=False)
1370 return dict(found=False)
1372
1371
1373 if namespaces is None:
1372 if namespaces is None:
1374 # Namespaces to search in:
1373 # Namespaces to search in:
1375 # Put them in a list. The order is important so that we
1374 # Put them in a list. The order is important so that we
1376 # find things in the same order that Python finds them.
1375 # find things in the same order that Python finds them.
1377 namespaces = [ ('Interactive', self.user_ns),
1376 namespaces = [ ('Interactive', self.user_ns),
1378 ('Interactive (global)', self.user_global_ns),
1377 ('Interactive (global)', self.user_global_ns),
1379 ('Python builtin', builtin_mod.__dict__),
1378 ('Python builtin', builtin_mod.__dict__),
1380 ]
1379 ]
1381
1380
1382 # initialize results to 'null'
1381 # initialize results to 'null'
1383 found = False; obj = None; ospace = None;
1382 found = False; obj = None; ospace = None;
1384 ismagic = False; isalias = False; parent = None
1383 ismagic = False; isalias = False; parent = None
1385
1384
1386 # We need to special-case 'print', which as of python2.6 registers as a
1385 # We need to special-case 'print', which as of python2.6 registers as a
1387 # function but should only be treated as one if print_function was
1386 # function but should only be treated as one if print_function was
1388 # loaded with a future import. In this case, just bail.
1387 # loaded with a future import. In this case, just bail.
1389 if (oname == 'print' and not py3compat.PY3 and not \
1388 if (oname == 'print' and not py3compat.PY3 and not \
1390 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1389 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1391 return {'found':found, 'obj':obj, 'namespace':ospace,
1390 return {'found':found, 'obj':obj, 'namespace':ospace,
1392 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1391 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1393
1392
1394 # Look for the given name by splitting it in parts. If the head is
1393 # Look for the given name by splitting it in parts. If the head is
1395 # found, then we look for all the remaining parts as members, and only
1394 # found, then we look for all the remaining parts as members, and only
1396 # declare success if we can find them all.
1395 # declare success if we can find them all.
1397 oname_parts = oname.split('.')
1396 oname_parts = oname.split('.')
1398 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1397 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1399 for nsname,ns in namespaces:
1398 for nsname,ns in namespaces:
1400 try:
1399 try:
1401 obj = ns[oname_head]
1400 obj = ns[oname_head]
1402 except KeyError:
1401 except KeyError:
1403 continue
1402 continue
1404 else:
1403 else:
1405 #print 'oname_rest:', oname_rest # dbg
1404 #print 'oname_rest:', oname_rest # dbg
1406 for idx, part in enumerate(oname_rest):
1405 for idx, part in enumerate(oname_rest):
1407 try:
1406 try:
1408 parent = obj
1407 parent = obj
1409 # The last part is looked up in a special way to avoid
1408 # The last part is looked up in a special way to avoid
1410 # descriptor invocation as it may raise or have side
1409 # descriptor invocation as it may raise or have side
1411 # effects.
1410 # effects.
1412 if idx == len(oname_rest) - 1:
1411 if idx == len(oname_rest) - 1:
1413 obj = self._getattr_property(obj, part)
1412 obj = self._getattr_property(obj, part)
1414 else:
1413 else:
1415 obj = getattr(obj, part)
1414 obj = getattr(obj, part)
1416 except:
1415 except:
1417 # Blanket except b/c some badly implemented objects
1416 # Blanket except b/c some badly implemented objects
1418 # allow __getattr__ to raise exceptions other than
1417 # allow __getattr__ to raise exceptions other than
1419 # AttributeError, which then crashes IPython.
1418 # AttributeError, which then crashes IPython.
1420 break
1419 break
1421 else:
1420 else:
1422 # If we finish the for loop (no break), we got all members
1421 # If we finish the for loop (no break), we got all members
1423 found = True
1422 found = True
1424 ospace = nsname
1423 ospace = nsname
1425 break # namespace loop
1424 break # namespace loop
1426
1425
1427 # Try to see if it's magic
1426 # Try to see if it's magic
1428 if not found:
1427 if not found:
1429 obj = None
1428 obj = None
1430 if oname.startswith(ESC_MAGIC2):
1429 if oname.startswith(ESC_MAGIC2):
1431 oname = oname.lstrip(ESC_MAGIC2)
1430 oname = oname.lstrip(ESC_MAGIC2)
1432 obj = self.find_cell_magic(oname)
1431 obj = self.find_cell_magic(oname)
1433 elif oname.startswith(ESC_MAGIC):
1432 elif oname.startswith(ESC_MAGIC):
1434 oname = oname.lstrip(ESC_MAGIC)
1433 oname = oname.lstrip(ESC_MAGIC)
1435 obj = self.find_line_magic(oname)
1434 obj = self.find_line_magic(oname)
1436 else:
1435 else:
1437 # search without prefix, so run? will find %run?
1436 # search without prefix, so run? will find %run?
1438 obj = self.find_line_magic(oname)
1437 obj = self.find_line_magic(oname)
1439 if obj is None:
1438 if obj is None:
1440 obj = self.find_cell_magic(oname)
1439 obj = self.find_cell_magic(oname)
1441 if obj is not None:
1440 if obj is not None:
1442 found = True
1441 found = True
1443 ospace = 'IPython internal'
1442 ospace = 'IPython internal'
1444 ismagic = True
1443 ismagic = True
1445 isalias = isinstance(obj, Alias)
1444 isalias = isinstance(obj, Alias)
1446
1445
1447 # Last try: special-case some literals like '', [], {}, etc:
1446 # Last try: special-case some literals like '', [], {}, etc:
1448 if not found and oname_head in ["''",'""','[]','{}','()']:
1447 if not found and oname_head in ["''",'""','[]','{}','()']:
1449 obj = eval(oname_head)
1448 obj = eval(oname_head)
1450 found = True
1449 found = True
1451 ospace = 'Interactive'
1450 ospace = 'Interactive'
1452
1451
1453 return {'found':found, 'obj':obj, 'namespace':ospace,
1452 return {'found':found, 'obj':obj, 'namespace':ospace,
1454 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1453 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1455
1454
1456 @staticmethod
1455 @staticmethod
1457 def _getattr_property(obj, attrname):
1456 def _getattr_property(obj, attrname):
1458 """Property-aware getattr to use in object finding.
1457 """Property-aware getattr to use in object finding.
1459
1458
1460 If attrname represents a property, return it unevaluated (in case it has
1459 If attrname represents a property, return it unevaluated (in case it has
1461 side effects or raises an error.
1460 side effects or raises an error.
1462
1461
1463 """
1462 """
1464 if not isinstance(obj, type):
1463 if not isinstance(obj, type):
1465 try:
1464 try:
1466 # `getattr(type(obj), attrname)` is not guaranteed to return
1465 # `getattr(type(obj), attrname)` is not guaranteed to return
1467 # `obj`, but does so for property:
1466 # `obj`, but does so for property:
1468 #
1467 #
1469 # property.__get__(self, None, cls) -> self
1468 # property.__get__(self, None, cls) -> self
1470 #
1469 #
1471 # The universal alternative is to traverse the mro manually
1470 # The universal alternative is to traverse the mro manually
1472 # searching for attrname in class dicts.
1471 # searching for attrname in class dicts.
1473 attr = getattr(type(obj), attrname)
1472 attr = getattr(type(obj), attrname)
1474 except AttributeError:
1473 except AttributeError:
1475 pass
1474 pass
1476 else:
1475 else:
1477 # This relies on the fact that data descriptors (with both
1476 # This relies on the fact that data descriptors (with both
1478 # __get__ & __set__ magic methods) take precedence over
1477 # __get__ & __set__ magic methods) take precedence over
1479 # instance-level attributes:
1478 # instance-level attributes:
1480 #
1479 #
1481 # class A(object):
1480 # class A(object):
1482 # @property
1481 # @property
1483 # def foobar(self): return 123
1482 # def foobar(self): return 123
1484 # a = A()
1483 # a = A()
1485 # a.__dict__['foobar'] = 345
1484 # a.__dict__['foobar'] = 345
1486 # a.foobar # == 123
1485 # a.foobar # == 123
1487 #
1486 #
1488 # So, a property may be returned right away.
1487 # So, a property may be returned right away.
1489 if isinstance(attr, property):
1488 if isinstance(attr, property):
1490 return attr
1489 return attr
1491
1490
1492 # Nothing helped, fall back.
1491 # Nothing helped, fall back.
1493 return getattr(obj, attrname)
1492 return getattr(obj, attrname)
1494
1493
1495 def _object_find(self, oname, namespaces=None):
1494 def _object_find(self, oname, namespaces=None):
1496 """Find an object and return a struct with info about it."""
1495 """Find an object and return a struct with info about it."""
1497 return Struct(self._ofind(oname, namespaces))
1496 return Struct(self._ofind(oname, namespaces))
1498
1497
1499 def _inspect(self, meth, oname, namespaces=None, **kw):
1498 def _inspect(self, meth, oname, namespaces=None, **kw):
1500 """Generic interface to the inspector system.
1499 """Generic interface to the inspector system.
1501
1500
1502 This function is meant to be called by pdef, pdoc & friends.
1501 This function is meant to be called by pdef, pdoc & friends.
1503 """
1502 """
1504 info = self._object_find(oname, namespaces)
1503 info = self._object_find(oname, namespaces)
1505 docformat = sphinxify if self.sphinxify_docstring else None
1504 docformat = sphinxify if self.sphinxify_docstring else None
1506 if info.found:
1505 if info.found:
1507 pmethod = getattr(self.inspector, meth)
1506 pmethod = getattr(self.inspector, meth)
1508 # TODO: only apply format_screen to the plain/text repr of the mime
1507 # TODO: only apply format_screen to the plain/text repr of the mime
1509 # bundle.
1508 # bundle.
1510 formatter = format_screen if info.ismagic else docformat
1509 formatter = format_screen if info.ismagic else docformat
1511 if meth == 'pdoc':
1510 if meth == 'pdoc':
1512 pmethod(info.obj, oname, formatter)
1511 pmethod(info.obj, oname, formatter)
1513 elif meth == 'pinfo':
1512 elif meth == 'pinfo':
1514 pmethod(info.obj, oname, formatter, info,
1513 pmethod(info.obj, oname, formatter, info,
1515 enable_html_pager=self.enable_html_pager, **kw)
1514 enable_html_pager=self.enable_html_pager, **kw)
1516 else:
1515 else:
1517 pmethod(info.obj, oname)
1516 pmethod(info.obj, oname)
1518 else:
1517 else:
1519 print('Object `%s` not found.' % oname)
1518 print('Object `%s` not found.' % oname)
1520 return 'not found' # so callers can take other action
1519 return 'not found' # so callers can take other action
1521
1520
1522 def object_inspect(self, oname, detail_level=0):
1521 def object_inspect(self, oname, detail_level=0):
1523 """Get object info about oname"""
1522 """Get object info about oname"""
1524 with self.builtin_trap:
1523 with self.builtin_trap:
1525 info = self._object_find(oname)
1524 info = self._object_find(oname)
1526 if info.found:
1525 if info.found:
1527 return self.inspector.info(info.obj, oname, info=info,
1526 return self.inspector.info(info.obj, oname, info=info,
1528 detail_level=detail_level
1527 detail_level=detail_level
1529 )
1528 )
1530 else:
1529 else:
1531 return oinspect.object_info(name=oname, found=False)
1530 return oinspect.object_info(name=oname, found=False)
1532
1531
1533 def object_inspect_text(self, oname, detail_level=0):
1532 def object_inspect_text(self, oname, detail_level=0):
1534 """Get object info as formatted text"""
1533 """Get object info as formatted text"""
1535 return self.object_inspect_mime(oname, detail_level)['text/plain']
1534 return self.object_inspect_mime(oname, detail_level)['text/plain']
1536
1535
1537 def object_inspect_mime(self, oname, detail_level=0):
1536 def object_inspect_mime(self, oname, detail_level=0):
1538 """Get object info as a mimebundle of formatted representations.
1537 """Get object info as a mimebundle of formatted representations.
1539
1538
1540 A mimebundle is a dictionary, keyed by mime-type.
1539 A mimebundle is a dictionary, keyed by mime-type.
1541 It must always have the key `'text/plain'`.
1540 It must always have the key `'text/plain'`.
1542 """
1541 """
1543 with self.builtin_trap:
1542 with self.builtin_trap:
1544 info = self._object_find(oname)
1543 info = self._object_find(oname)
1545 if info.found:
1544 if info.found:
1546 return self.inspector._get_info(info.obj, oname, info=info,
1545 return self.inspector._get_info(info.obj, oname, info=info,
1547 detail_level=detail_level
1546 detail_level=detail_level
1548 )
1547 )
1549 else:
1548 else:
1550 raise KeyError(oname)
1549 raise KeyError(oname)
1551
1550
1552 #-------------------------------------------------------------------------
1551 #-------------------------------------------------------------------------
1553 # Things related to history management
1552 # Things related to history management
1554 #-------------------------------------------------------------------------
1553 #-------------------------------------------------------------------------
1555
1554
1556 def init_history(self):
1555 def init_history(self):
1557 """Sets up the command history, and starts regular autosaves."""
1556 """Sets up the command history, and starts regular autosaves."""
1558 self.history_manager = HistoryManager(shell=self, parent=self)
1557 self.history_manager = HistoryManager(shell=self, parent=self)
1559 self.configurables.append(self.history_manager)
1558 self.configurables.append(self.history_manager)
1560
1559
1561 #-------------------------------------------------------------------------
1560 #-------------------------------------------------------------------------
1562 # Things related to exception handling and tracebacks (not debugging)
1561 # Things related to exception handling and tracebacks (not debugging)
1563 #-------------------------------------------------------------------------
1562 #-------------------------------------------------------------------------
1564
1563
1565 debugger_cls = Pdb
1564 debugger_cls = Pdb
1566
1565
1567 def init_traceback_handlers(self, custom_exceptions):
1566 def init_traceback_handlers(self, custom_exceptions):
1568 # Syntax error handler.
1567 # Syntax error handler.
1569 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self)
1568 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self)
1570
1569
1571 # The interactive one is initialized with an offset, meaning we always
1570 # The interactive one is initialized with an offset, meaning we always
1572 # want to remove the topmost item in the traceback, which is our own
1571 # want to remove the topmost item in the traceback, which is our own
1573 # internal code. Valid modes: ['Plain','Context','Verbose']
1572 # internal code. Valid modes: ['Plain','Context','Verbose']
1574 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1573 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1575 color_scheme='NoColor',
1574 color_scheme='NoColor',
1576 tb_offset = 1,
1575 tb_offset = 1,
1577 check_cache=check_linecache_ipython,
1576 check_cache=check_linecache_ipython,
1578 debugger_cls=self.debugger_cls, parent=self)
1577 debugger_cls=self.debugger_cls, parent=self)
1579
1578
1580 # The instance will store a pointer to the system-wide exception hook,
1579 # The instance will store a pointer to the system-wide exception hook,
1581 # so that runtime code (such as magics) can access it. This is because
1580 # so that runtime code (such as magics) can access it. This is because
1582 # during the read-eval loop, it may get temporarily overwritten.
1581 # during the read-eval loop, it may get temporarily overwritten.
1583 self.sys_excepthook = sys.excepthook
1582 self.sys_excepthook = sys.excepthook
1584
1583
1585 # and add any custom exception handlers the user may have specified
1584 # and add any custom exception handlers the user may have specified
1586 self.set_custom_exc(*custom_exceptions)
1585 self.set_custom_exc(*custom_exceptions)
1587
1586
1588 # Set the exception mode
1587 # Set the exception mode
1589 self.InteractiveTB.set_mode(mode=self.xmode)
1588 self.InteractiveTB.set_mode(mode=self.xmode)
1590
1589
1591 def set_custom_exc(self, exc_tuple, handler):
1590 def set_custom_exc(self, exc_tuple, handler):
1592 """set_custom_exc(exc_tuple, handler)
1591 """set_custom_exc(exc_tuple, handler)
1593
1592
1594 Set a custom exception handler, which will be called if any of the
1593 Set a custom exception handler, which will be called if any of the
1595 exceptions in exc_tuple occur in the mainloop (specifically, in the
1594 exceptions in exc_tuple occur in the mainloop (specifically, in the
1596 run_code() method).
1595 run_code() method).
1597
1596
1598 Parameters
1597 Parameters
1599 ----------
1598 ----------
1600
1599
1601 exc_tuple : tuple of exception classes
1600 exc_tuple : tuple of exception classes
1602 A *tuple* of exception classes, for which to call the defined
1601 A *tuple* of exception classes, for which to call the defined
1603 handler. It is very important that you use a tuple, and NOT A
1602 handler. It is very important that you use a tuple, and NOT A
1604 LIST here, because of the way Python's except statement works. If
1603 LIST here, because of the way Python's except statement works. If
1605 you only want to trap a single exception, use a singleton tuple::
1604 you only want to trap a single exception, use a singleton tuple::
1606
1605
1607 exc_tuple == (MyCustomException,)
1606 exc_tuple == (MyCustomException,)
1608
1607
1609 handler : callable
1608 handler : callable
1610 handler must have the following signature::
1609 handler must have the following signature::
1611
1610
1612 def my_handler(self, etype, value, tb, tb_offset=None):
1611 def my_handler(self, etype, value, tb, tb_offset=None):
1613 ...
1612 ...
1614 return structured_traceback
1613 return structured_traceback
1615
1614
1616 Your handler must return a structured traceback (a list of strings),
1615 Your handler must return a structured traceback (a list of strings),
1617 or None.
1616 or None.
1618
1617
1619 This will be made into an instance method (via types.MethodType)
1618 This will be made into an instance method (via types.MethodType)
1620 of IPython itself, and it will be called if any of the exceptions
1619 of IPython itself, and it will be called if any of the exceptions
1621 listed in the exc_tuple are caught. If the handler is None, an
1620 listed in the exc_tuple are caught. If the handler is None, an
1622 internal basic one is used, which just prints basic info.
1621 internal basic one is used, which just prints basic info.
1623
1622
1624 To protect IPython from crashes, if your handler ever raises an
1623 To protect IPython from crashes, if your handler ever raises an
1625 exception or returns an invalid result, it will be immediately
1624 exception or returns an invalid result, it will be immediately
1626 disabled.
1625 disabled.
1627
1626
1628 WARNING: by putting in your own exception handler into IPython's main
1627 WARNING: by putting in your own exception handler into IPython's main
1629 execution loop, you run a very good chance of nasty crashes. This
1628 execution loop, you run a very good chance of nasty crashes. This
1630 facility should only be used if you really know what you are doing."""
1629 facility should only be used if you really know what you are doing."""
1631
1630
1632 assert type(exc_tuple)==type(()) , \
1631 assert type(exc_tuple)==type(()) , \
1633 "The custom exceptions must be given AS A TUPLE."
1632 "The custom exceptions must be given AS A TUPLE."
1634
1633
1635 def dummy_handler(self, etype, value, tb, tb_offset=None):
1634 def dummy_handler(self, etype, value, tb, tb_offset=None):
1636 print('*** Simple custom exception handler ***')
1635 print('*** Simple custom exception handler ***')
1637 print('Exception type :',etype)
1636 print('Exception type :',etype)
1638 print('Exception value:',value)
1637 print('Exception value:',value)
1639 print('Traceback :',tb)
1638 print('Traceback :',tb)
1640 #print 'Source code :','\n'.join(self.buffer)
1639 #print 'Source code :','\n'.join(self.buffer)
1641
1640
1642 def validate_stb(stb):
1641 def validate_stb(stb):
1643 """validate structured traceback return type
1642 """validate structured traceback return type
1644
1643
1645 return type of CustomTB *should* be a list of strings, but allow
1644 return type of CustomTB *should* be a list of strings, but allow
1646 single strings or None, which are harmless.
1645 single strings or None, which are harmless.
1647
1646
1648 This function will *always* return a list of strings,
1647 This function will *always* return a list of strings,
1649 and will raise a TypeError if stb is inappropriate.
1648 and will raise a TypeError if stb is inappropriate.
1650 """
1649 """
1651 msg = "CustomTB must return list of strings, not %r" % stb
1650 msg = "CustomTB must return list of strings, not %r" % stb
1652 if stb is None:
1651 if stb is None:
1653 return []
1652 return []
1654 elif isinstance(stb, string_types):
1653 elif isinstance(stb, str):
1655 return [stb]
1654 return [stb]
1656 elif not isinstance(stb, list):
1655 elif not isinstance(stb, list):
1657 raise TypeError(msg)
1656 raise TypeError(msg)
1658 # it's a list
1657 # it's a list
1659 for line in stb:
1658 for line in stb:
1660 # check every element
1659 # check every element
1661 if not isinstance(line, string_types):
1660 if not isinstance(line, str):
1662 raise TypeError(msg)
1661 raise TypeError(msg)
1663 return stb
1662 return stb
1664
1663
1665 if handler is None:
1664 if handler is None:
1666 wrapped = dummy_handler
1665 wrapped = dummy_handler
1667 else:
1666 else:
1668 def wrapped(self,etype,value,tb,tb_offset=None):
1667 def wrapped(self,etype,value,tb,tb_offset=None):
1669 """wrap CustomTB handler, to protect IPython from user code
1668 """wrap CustomTB handler, to protect IPython from user code
1670
1669
1671 This makes it harder (but not impossible) for custom exception
1670 This makes it harder (but not impossible) for custom exception
1672 handlers to crash IPython.
1671 handlers to crash IPython.
1673 """
1672 """
1674 try:
1673 try:
1675 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1674 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1676 return validate_stb(stb)
1675 return validate_stb(stb)
1677 except:
1676 except:
1678 # clear custom handler immediately
1677 # clear custom handler immediately
1679 self.set_custom_exc((), None)
1678 self.set_custom_exc((), None)
1680 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1679 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1681 # show the exception in handler first
1680 # show the exception in handler first
1682 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1681 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1683 print(self.InteractiveTB.stb2text(stb))
1682 print(self.InteractiveTB.stb2text(stb))
1684 print("The original exception:")
1683 print("The original exception:")
1685 stb = self.InteractiveTB.structured_traceback(
1684 stb = self.InteractiveTB.structured_traceback(
1686 (etype,value,tb), tb_offset=tb_offset
1685 (etype,value,tb), tb_offset=tb_offset
1687 )
1686 )
1688 return stb
1687 return stb
1689
1688
1690 self.CustomTB = types.MethodType(wrapped,self)
1689 self.CustomTB = types.MethodType(wrapped,self)
1691 self.custom_exceptions = exc_tuple
1690 self.custom_exceptions = exc_tuple
1692
1691
1693 def excepthook(self, etype, value, tb):
1692 def excepthook(self, etype, value, tb):
1694 """One more defense for GUI apps that call sys.excepthook.
1693 """One more defense for GUI apps that call sys.excepthook.
1695
1694
1696 GUI frameworks like wxPython trap exceptions and call
1695 GUI frameworks like wxPython trap exceptions and call
1697 sys.excepthook themselves. I guess this is a feature that
1696 sys.excepthook themselves. I guess this is a feature that
1698 enables them to keep running after exceptions that would
1697 enables them to keep running after exceptions that would
1699 otherwise kill their mainloop. This is a bother for IPython
1698 otherwise kill their mainloop. This is a bother for IPython
1700 which excepts to catch all of the program exceptions with a try:
1699 which excepts to catch all of the program exceptions with a try:
1701 except: statement.
1700 except: statement.
1702
1701
1703 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1702 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1704 any app directly invokes sys.excepthook, it will look to the user like
1703 any app directly invokes sys.excepthook, it will look to the user like
1705 IPython crashed. In order to work around this, we can disable the
1704 IPython crashed. In order to work around this, we can disable the
1706 CrashHandler and replace it with this excepthook instead, which prints a
1705 CrashHandler and replace it with this excepthook instead, which prints a
1707 regular traceback using our InteractiveTB. In this fashion, apps which
1706 regular traceback using our InteractiveTB. In this fashion, apps which
1708 call sys.excepthook will generate a regular-looking exception from
1707 call sys.excepthook will generate a regular-looking exception from
1709 IPython, and the CrashHandler will only be triggered by real IPython
1708 IPython, and the CrashHandler will only be triggered by real IPython
1710 crashes.
1709 crashes.
1711
1710
1712 This hook should be used sparingly, only in places which are not likely
1711 This hook should be used sparingly, only in places which are not likely
1713 to be true IPython errors.
1712 to be true IPython errors.
1714 """
1713 """
1715 self.showtraceback((etype, value, tb), tb_offset=0)
1714 self.showtraceback((etype, value, tb), tb_offset=0)
1716
1715
1717 def _get_exc_info(self, exc_tuple=None):
1716 def _get_exc_info(self, exc_tuple=None):
1718 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1717 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1719
1718
1720 Ensures sys.last_type,value,traceback hold the exc_info we found,
1719 Ensures sys.last_type,value,traceback hold the exc_info we found,
1721 from whichever source.
1720 from whichever source.
1722
1721
1723 raises ValueError if none of these contain any information
1722 raises ValueError if none of these contain any information
1724 """
1723 """
1725 if exc_tuple is None:
1724 if exc_tuple is None:
1726 etype, value, tb = sys.exc_info()
1725 etype, value, tb = sys.exc_info()
1727 else:
1726 else:
1728 etype, value, tb = exc_tuple
1727 etype, value, tb = exc_tuple
1729
1728
1730 if etype is None:
1729 if etype is None:
1731 if hasattr(sys, 'last_type'):
1730 if hasattr(sys, 'last_type'):
1732 etype, value, tb = sys.last_type, sys.last_value, \
1731 etype, value, tb = sys.last_type, sys.last_value, \
1733 sys.last_traceback
1732 sys.last_traceback
1734
1733
1735 if etype is None:
1734 if etype is None:
1736 raise ValueError("No exception to find")
1735 raise ValueError("No exception to find")
1737
1736
1738 # Now store the exception info in sys.last_type etc.
1737 # Now store the exception info in sys.last_type etc.
1739 # WARNING: these variables are somewhat deprecated and not
1738 # WARNING: these variables are somewhat deprecated and not
1740 # necessarily safe to use in a threaded environment, but tools
1739 # necessarily safe to use in a threaded environment, but tools
1741 # like pdb depend on their existence, so let's set them. If we
1740 # like pdb depend on their existence, so let's set them. If we
1742 # find problems in the field, we'll need to revisit their use.
1741 # find problems in the field, we'll need to revisit their use.
1743 sys.last_type = etype
1742 sys.last_type = etype
1744 sys.last_value = value
1743 sys.last_value = value
1745 sys.last_traceback = tb
1744 sys.last_traceback = tb
1746
1745
1747 return etype, value, tb
1746 return etype, value, tb
1748
1747
1749 def show_usage_error(self, exc):
1748 def show_usage_error(self, exc):
1750 """Show a short message for UsageErrors
1749 """Show a short message for UsageErrors
1751
1750
1752 These are special exceptions that shouldn't show a traceback.
1751 These are special exceptions that shouldn't show a traceback.
1753 """
1752 """
1754 print("UsageError: %s" % exc, file=sys.stderr)
1753 print("UsageError: %s" % exc, file=sys.stderr)
1755
1754
1756 def get_exception_only(self, exc_tuple=None):
1755 def get_exception_only(self, exc_tuple=None):
1757 """
1756 """
1758 Return as a string (ending with a newline) the exception that
1757 Return as a string (ending with a newline) the exception that
1759 just occurred, without any traceback.
1758 just occurred, without any traceback.
1760 """
1759 """
1761 etype, value, tb = self._get_exc_info(exc_tuple)
1760 etype, value, tb = self._get_exc_info(exc_tuple)
1762 msg = traceback.format_exception_only(etype, value)
1761 msg = traceback.format_exception_only(etype, value)
1763 return ''.join(msg)
1762 return ''.join(msg)
1764
1763
1765 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1764 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1766 exception_only=False):
1765 exception_only=False):
1767 """Display the exception that just occurred.
1766 """Display the exception that just occurred.
1768
1767
1769 If nothing is known about the exception, this is the method which
1768 If nothing is known about the exception, this is the method which
1770 should be used throughout the code for presenting user tracebacks,
1769 should be used throughout the code for presenting user tracebacks,
1771 rather than directly invoking the InteractiveTB object.
1770 rather than directly invoking the InteractiveTB object.
1772
1771
1773 A specific showsyntaxerror() also exists, but this method can take
1772 A specific showsyntaxerror() also exists, but this method can take
1774 care of calling it if needed, so unless you are explicitly catching a
1773 care of calling it if needed, so unless you are explicitly catching a
1775 SyntaxError exception, don't try to analyze the stack manually and
1774 SyntaxError exception, don't try to analyze the stack manually and
1776 simply call this method."""
1775 simply call this method."""
1777
1776
1778 try:
1777 try:
1779 try:
1778 try:
1780 etype, value, tb = self._get_exc_info(exc_tuple)
1779 etype, value, tb = self._get_exc_info(exc_tuple)
1781 except ValueError:
1780 except ValueError:
1782 print('No traceback available to show.', file=sys.stderr)
1781 print('No traceback available to show.', file=sys.stderr)
1783 return
1782 return
1784
1783
1785 if issubclass(etype, SyntaxError):
1784 if issubclass(etype, SyntaxError):
1786 # Though this won't be called by syntax errors in the input
1785 # Though this won't be called by syntax errors in the input
1787 # line, there may be SyntaxError cases with imported code.
1786 # line, there may be SyntaxError cases with imported code.
1788 self.showsyntaxerror(filename)
1787 self.showsyntaxerror(filename)
1789 elif etype is UsageError:
1788 elif etype is UsageError:
1790 self.show_usage_error(value)
1789 self.show_usage_error(value)
1791 else:
1790 else:
1792 if exception_only:
1791 if exception_only:
1793 stb = ['An exception has occurred, use %tb to see '
1792 stb = ['An exception has occurred, use %tb to see '
1794 'the full traceback.\n']
1793 'the full traceback.\n']
1795 stb.extend(self.InteractiveTB.get_exception_only(etype,
1794 stb.extend(self.InteractiveTB.get_exception_only(etype,
1796 value))
1795 value))
1797 else:
1796 else:
1798 try:
1797 try:
1799 # Exception classes can customise their traceback - we
1798 # Exception classes can customise their traceback - we
1800 # use this in IPython.parallel for exceptions occurring
1799 # use this in IPython.parallel for exceptions occurring
1801 # in the engines. This should return a list of strings.
1800 # in the engines. This should return a list of strings.
1802 stb = value._render_traceback_()
1801 stb = value._render_traceback_()
1803 except Exception:
1802 except Exception:
1804 stb = self.InteractiveTB.structured_traceback(etype,
1803 stb = self.InteractiveTB.structured_traceback(etype,
1805 value, tb, tb_offset=tb_offset)
1804 value, tb, tb_offset=tb_offset)
1806
1805
1807 self._showtraceback(etype, value, stb)
1806 self._showtraceback(etype, value, stb)
1808 if self.call_pdb:
1807 if self.call_pdb:
1809 # drop into debugger
1808 # drop into debugger
1810 self.debugger(force=True)
1809 self.debugger(force=True)
1811 return
1810 return
1812
1811
1813 # Actually show the traceback
1812 # Actually show the traceback
1814 self._showtraceback(etype, value, stb)
1813 self._showtraceback(etype, value, stb)
1815
1814
1816 except KeyboardInterrupt:
1815 except KeyboardInterrupt:
1817 print('\n' + self.get_exception_only(), file=sys.stderr)
1816 print('\n' + self.get_exception_only(), file=sys.stderr)
1818
1817
1819 def _showtraceback(self, etype, evalue, stb):
1818 def _showtraceback(self, etype, evalue, stb):
1820 """Actually show a traceback.
1819 """Actually show a traceback.
1821
1820
1822 Subclasses may override this method to put the traceback on a different
1821 Subclasses may override this method to put the traceback on a different
1823 place, like a side channel.
1822 place, like a side channel.
1824 """
1823 """
1825 print(self.InteractiveTB.stb2text(stb))
1824 print(self.InteractiveTB.stb2text(stb))
1826
1825
1827 def showsyntaxerror(self, filename=None):
1826 def showsyntaxerror(self, filename=None):
1828 """Display the syntax error that just occurred.
1827 """Display the syntax error that just occurred.
1829
1828
1830 This doesn't display a stack trace because there isn't one.
1829 This doesn't display a stack trace because there isn't one.
1831
1830
1832 If a filename is given, it is stuffed in the exception instead
1831 If a filename is given, it is stuffed in the exception instead
1833 of what was there before (because Python's parser always uses
1832 of what was there before (because Python's parser always uses
1834 "<string>" when reading from a string).
1833 "<string>" when reading from a string).
1835 """
1834 """
1836 etype, value, last_traceback = self._get_exc_info()
1835 etype, value, last_traceback = self._get_exc_info()
1837
1836
1838 if filename and issubclass(etype, SyntaxError):
1837 if filename and issubclass(etype, SyntaxError):
1839 try:
1838 try:
1840 value.filename = filename
1839 value.filename = filename
1841 except:
1840 except:
1842 # Not the format we expect; leave it alone
1841 # Not the format we expect; leave it alone
1843 pass
1842 pass
1844
1843
1845 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1844 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1846 self._showtraceback(etype, value, stb)
1845 self._showtraceback(etype, value, stb)
1847
1846
1848 # This is overridden in TerminalInteractiveShell to show a message about
1847 # This is overridden in TerminalInteractiveShell to show a message about
1849 # the %paste magic.
1848 # the %paste magic.
1850 def showindentationerror(self):
1849 def showindentationerror(self):
1851 """Called by run_cell when there's an IndentationError in code entered
1850 """Called by run_cell when there's an IndentationError in code entered
1852 at the prompt.
1851 at the prompt.
1853
1852
1854 This is overridden in TerminalInteractiveShell to show a message about
1853 This is overridden in TerminalInteractiveShell to show a message about
1855 the %paste magic."""
1854 the %paste magic."""
1856 self.showsyntaxerror()
1855 self.showsyntaxerror()
1857
1856
1858 #-------------------------------------------------------------------------
1857 #-------------------------------------------------------------------------
1859 # Things related to readline
1858 # Things related to readline
1860 #-------------------------------------------------------------------------
1859 #-------------------------------------------------------------------------
1861
1860
1862 def init_readline(self):
1861 def init_readline(self):
1863 """DEPRECATED
1862 """DEPRECATED
1864
1863
1865 Moved to terminal subclass, here only to simplify the init logic."""
1864 Moved to terminal subclass, here only to simplify the init logic."""
1866 # Set a number of methods that depend on readline to be no-op
1865 # Set a number of methods that depend on readline to be no-op
1867 warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated',
1866 warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated',
1868 DeprecationWarning, stacklevel=2)
1867 DeprecationWarning, stacklevel=2)
1869 self.set_custom_completer = no_op
1868 self.set_custom_completer = no_op
1870
1869
1871 @skip_doctest
1870 @skip_doctest
1872 def set_next_input(self, s, replace=False):
1871 def set_next_input(self, s, replace=False):
1873 """ Sets the 'default' input string for the next command line.
1872 """ Sets the 'default' input string for the next command line.
1874
1873
1875 Example::
1874 Example::
1876
1875
1877 In [1]: _ip.set_next_input("Hello Word")
1876 In [1]: _ip.set_next_input("Hello Word")
1878 In [2]: Hello Word_ # cursor is here
1877 In [2]: Hello Word_ # cursor is here
1879 """
1878 """
1880 self.rl_next_input = py3compat.cast_bytes_py2(s)
1879 self.rl_next_input = py3compat.cast_bytes_py2(s)
1881
1880
1882 def _indent_current_str(self):
1881 def _indent_current_str(self):
1883 """return the current level of indentation as a string"""
1882 """return the current level of indentation as a string"""
1884 return self.input_splitter.indent_spaces * ' '
1883 return self.input_splitter.indent_spaces * ' '
1885
1884
1886 #-------------------------------------------------------------------------
1885 #-------------------------------------------------------------------------
1887 # Things related to text completion
1886 # Things related to text completion
1888 #-------------------------------------------------------------------------
1887 #-------------------------------------------------------------------------
1889
1888
1890 def init_completer(self):
1889 def init_completer(self):
1891 """Initialize the completion machinery.
1890 """Initialize the completion machinery.
1892
1891
1893 This creates completion machinery that can be used by client code,
1892 This creates completion machinery that can be used by client code,
1894 either interactively in-process (typically triggered by the readline
1893 either interactively in-process (typically triggered by the readline
1895 library), programmatically (such as in test suites) or out-of-process
1894 library), programmatically (such as in test suites) or out-of-process
1896 (typically over the network by remote frontends).
1895 (typically over the network by remote frontends).
1897 """
1896 """
1898 from IPython.core.completer import IPCompleter
1897 from IPython.core.completer import IPCompleter
1899 from IPython.core.completerlib import (module_completer,
1898 from IPython.core.completerlib import (module_completer,
1900 magic_run_completer, cd_completer, reset_completer)
1899 magic_run_completer, cd_completer, reset_completer)
1901
1900
1902 self.Completer = IPCompleter(shell=self,
1901 self.Completer = IPCompleter(shell=self,
1903 namespace=self.user_ns,
1902 namespace=self.user_ns,
1904 global_namespace=self.user_global_ns,
1903 global_namespace=self.user_global_ns,
1905 parent=self,
1904 parent=self,
1906 )
1905 )
1907 self.configurables.append(self.Completer)
1906 self.configurables.append(self.Completer)
1908
1907
1909 # Add custom completers to the basic ones built into IPCompleter
1908 # Add custom completers to the basic ones built into IPCompleter
1910 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1909 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1911 self.strdispatchers['complete_command'] = sdisp
1910 self.strdispatchers['complete_command'] = sdisp
1912 self.Completer.custom_completers = sdisp
1911 self.Completer.custom_completers = sdisp
1913
1912
1914 self.set_hook('complete_command', module_completer, str_key = 'import')
1913 self.set_hook('complete_command', module_completer, str_key = 'import')
1915 self.set_hook('complete_command', module_completer, str_key = 'from')
1914 self.set_hook('complete_command', module_completer, str_key = 'from')
1916 self.set_hook('complete_command', module_completer, str_key = '%aimport')
1915 self.set_hook('complete_command', module_completer, str_key = '%aimport')
1917 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1916 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1918 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1917 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1919 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1918 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1920
1919
1921
1920
1922 def complete(self, text, line=None, cursor_pos=None):
1921 def complete(self, text, line=None, cursor_pos=None):
1923 """Return the completed text and a list of completions.
1922 """Return the completed text and a list of completions.
1924
1923
1925 Parameters
1924 Parameters
1926 ----------
1925 ----------
1927
1926
1928 text : string
1927 text : string
1929 A string of text to be completed on. It can be given as empty and
1928 A string of text to be completed on. It can be given as empty and
1930 instead a line/position pair are given. In this case, the
1929 instead a line/position pair are given. In this case, the
1931 completer itself will split the line like readline does.
1930 completer itself will split the line like readline does.
1932
1931
1933 line : string, optional
1932 line : string, optional
1934 The complete line that text is part of.
1933 The complete line that text is part of.
1935
1934
1936 cursor_pos : int, optional
1935 cursor_pos : int, optional
1937 The position of the cursor on the input line.
1936 The position of the cursor on the input line.
1938
1937
1939 Returns
1938 Returns
1940 -------
1939 -------
1941 text : string
1940 text : string
1942 The actual text that was completed.
1941 The actual text that was completed.
1943
1942
1944 matches : list
1943 matches : list
1945 A sorted list with all possible completions.
1944 A sorted list with all possible completions.
1946
1945
1947 The optional arguments allow the completion to take more context into
1946 The optional arguments allow the completion to take more context into
1948 account, and are part of the low-level completion API.
1947 account, and are part of the low-level completion API.
1949
1948
1950 This is a wrapper around the completion mechanism, similar to what
1949 This is a wrapper around the completion mechanism, similar to what
1951 readline does at the command line when the TAB key is hit. By
1950 readline does at the command line when the TAB key is hit. By
1952 exposing it as a method, it can be used by other non-readline
1951 exposing it as a method, it can be used by other non-readline
1953 environments (such as GUIs) for text completion.
1952 environments (such as GUIs) for text completion.
1954
1953
1955 Simple usage example:
1954 Simple usage example:
1956
1955
1957 In [1]: x = 'hello'
1956 In [1]: x = 'hello'
1958
1957
1959 In [2]: _ip.complete('x.l')
1958 In [2]: _ip.complete('x.l')
1960 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1959 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1961 """
1960 """
1962
1961
1963 # Inject names into __builtin__ so we can complete on the added names.
1962 # Inject names into __builtin__ so we can complete on the added names.
1964 with self.builtin_trap:
1963 with self.builtin_trap:
1965 return self.Completer.complete(text, line, cursor_pos)
1964 return self.Completer.complete(text, line, cursor_pos)
1966
1965
1967 def set_custom_completer(self, completer, pos=0):
1966 def set_custom_completer(self, completer, pos=0):
1968 """Adds a new custom completer function.
1967 """Adds a new custom completer function.
1969
1968
1970 The position argument (defaults to 0) is the index in the completers
1969 The position argument (defaults to 0) is the index in the completers
1971 list where you want the completer to be inserted."""
1970 list where you want the completer to be inserted."""
1972
1971
1973 newcomp = types.MethodType(completer,self.Completer)
1972 newcomp = types.MethodType(completer,self.Completer)
1974 self.Completer.matchers.insert(pos,newcomp)
1973 self.Completer.matchers.insert(pos,newcomp)
1975
1974
1976 def set_completer_frame(self, frame=None):
1975 def set_completer_frame(self, frame=None):
1977 """Set the frame of the completer."""
1976 """Set the frame of the completer."""
1978 if frame:
1977 if frame:
1979 self.Completer.namespace = frame.f_locals
1978 self.Completer.namespace = frame.f_locals
1980 self.Completer.global_namespace = frame.f_globals
1979 self.Completer.global_namespace = frame.f_globals
1981 else:
1980 else:
1982 self.Completer.namespace = self.user_ns
1981 self.Completer.namespace = self.user_ns
1983 self.Completer.global_namespace = self.user_global_ns
1982 self.Completer.global_namespace = self.user_global_ns
1984
1983
1985 #-------------------------------------------------------------------------
1984 #-------------------------------------------------------------------------
1986 # Things related to magics
1985 # Things related to magics
1987 #-------------------------------------------------------------------------
1986 #-------------------------------------------------------------------------
1988
1987
1989 def init_magics(self):
1988 def init_magics(self):
1990 from IPython.core import magics as m
1989 from IPython.core import magics as m
1991 self.magics_manager = magic.MagicsManager(shell=self,
1990 self.magics_manager = magic.MagicsManager(shell=self,
1992 parent=self,
1991 parent=self,
1993 user_magics=m.UserMagics(self))
1992 user_magics=m.UserMagics(self))
1994 self.configurables.append(self.magics_manager)
1993 self.configurables.append(self.magics_manager)
1995
1994
1996 # Expose as public API from the magics manager
1995 # Expose as public API from the magics manager
1997 self.register_magics = self.magics_manager.register
1996 self.register_magics = self.magics_manager.register
1998
1997
1999 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
1998 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2000 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
1999 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
2001 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2000 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2002 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2001 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2003 )
2002 )
2004
2003
2005 # Register Magic Aliases
2004 # Register Magic Aliases
2006 mman = self.magics_manager
2005 mman = self.magics_manager
2007 # FIXME: magic aliases should be defined by the Magics classes
2006 # FIXME: magic aliases should be defined by the Magics classes
2008 # or in MagicsManager, not here
2007 # or in MagicsManager, not here
2009 mman.register_alias('ed', 'edit')
2008 mman.register_alias('ed', 'edit')
2010 mman.register_alias('hist', 'history')
2009 mman.register_alias('hist', 'history')
2011 mman.register_alias('rep', 'recall')
2010 mman.register_alias('rep', 'recall')
2012 mman.register_alias('SVG', 'svg', 'cell')
2011 mman.register_alias('SVG', 'svg', 'cell')
2013 mman.register_alias('HTML', 'html', 'cell')
2012 mman.register_alias('HTML', 'html', 'cell')
2014 mman.register_alias('file', 'writefile', 'cell')
2013 mman.register_alias('file', 'writefile', 'cell')
2015
2014
2016 # FIXME: Move the color initialization to the DisplayHook, which
2015 # FIXME: Move the color initialization to the DisplayHook, which
2017 # should be split into a prompt manager and displayhook. We probably
2016 # should be split into a prompt manager and displayhook. We probably
2018 # even need a centralize colors management object.
2017 # even need a centralize colors management object.
2019 self.magic('colors %s' % self.colors)
2018 self.magic('colors %s' % self.colors)
2020
2019
2021 # Defined here so that it's included in the documentation
2020 # Defined here so that it's included in the documentation
2022 @functools.wraps(magic.MagicsManager.register_function)
2021 @functools.wraps(magic.MagicsManager.register_function)
2023 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2022 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2024 self.magics_manager.register_function(func,
2023 self.magics_manager.register_function(func,
2025 magic_kind=magic_kind, magic_name=magic_name)
2024 magic_kind=magic_kind, magic_name=magic_name)
2026
2025
2027 def run_line_magic(self, magic_name, line):
2026 def run_line_magic(self, magic_name, line):
2028 """Execute the given line magic.
2027 """Execute the given line magic.
2029
2028
2030 Parameters
2029 Parameters
2031 ----------
2030 ----------
2032 magic_name : str
2031 magic_name : str
2033 Name of the desired magic function, without '%' prefix.
2032 Name of the desired magic function, without '%' prefix.
2034
2033
2035 line : str
2034 line : str
2036 The rest of the input line as a single string.
2035 The rest of the input line as a single string.
2037 """
2036 """
2038 fn = self.find_line_magic(magic_name)
2037 fn = self.find_line_magic(magic_name)
2039 if fn is None:
2038 if fn is None:
2040 cm = self.find_cell_magic(magic_name)
2039 cm = self.find_cell_magic(magic_name)
2041 etpl = "Line magic function `%%%s` not found%s."
2040 etpl = "Line magic function `%%%s` not found%s."
2042 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2041 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2043 'did you mean that instead?)' % magic_name )
2042 'did you mean that instead?)' % magic_name )
2044 error(etpl % (magic_name, extra))
2043 error(etpl % (magic_name, extra))
2045 else:
2044 else:
2046 # Note: this is the distance in the stack to the user's frame.
2045 # Note: this is the distance in the stack to the user's frame.
2047 # This will need to be updated if the internal calling logic gets
2046 # This will need to be updated if the internal calling logic gets
2048 # refactored, or else we'll be expanding the wrong variables.
2047 # refactored, or else we'll be expanding the wrong variables.
2049 stack_depth = 2
2048 stack_depth = 2
2050 magic_arg_s = self.var_expand(line, stack_depth)
2049 magic_arg_s = self.var_expand(line, stack_depth)
2051 # Put magic args in a list so we can call with f(*a) syntax
2050 # Put magic args in a list so we can call with f(*a) syntax
2052 args = [magic_arg_s]
2051 args = [magic_arg_s]
2053 kwargs = {}
2052 kwargs = {}
2054 # Grab local namespace if we need it:
2053 # Grab local namespace if we need it:
2055 if getattr(fn, "needs_local_scope", False):
2054 if getattr(fn, "needs_local_scope", False):
2056 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2055 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2057 with self.builtin_trap:
2056 with self.builtin_trap:
2058 result = fn(*args,**kwargs)
2057 result = fn(*args,**kwargs)
2059 return result
2058 return result
2060
2059
2061 def run_cell_magic(self, magic_name, line, cell):
2060 def run_cell_magic(self, magic_name, line, cell):
2062 """Execute the given cell magic.
2061 """Execute the given cell magic.
2063
2062
2064 Parameters
2063 Parameters
2065 ----------
2064 ----------
2066 magic_name : str
2065 magic_name : str
2067 Name of the desired magic function, without '%' prefix.
2066 Name of the desired magic function, without '%' prefix.
2068
2067
2069 line : str
2068 line : str
2070 The rest of the first input line as a single string.
2069 The rest of the first input line as a single string.
2071
2070
2072 cell : str
2071 cell : str
2073 The body of the cell as a (possibly multiline) string.
2072 The body of the cell as a (possibly multiline) string.
2074 """
2073 """
2075 fn = self.find_cell_magic(magic_name)
2074 fn = self.find_cell_magic(magic_name)
2076 if fn is None:
2075 if fn is None:
2077 lm = self.find_line_magic(magic_name)
2076 lm = self.find_line_magic(magic_name)
2078 etpl = "Cell magic `%%{0}` not found{1}."
2077 etpl = "Cell magic `%%{0}` not found{1}."
2079 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2078 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2080 'did you mean that instead?)'.format(magic_name))
2079 'did you mean that instead?)'.format(magic_name))
2081 error(etpl.format(magic_name, extra))
2080 error(etpl.format(magic_name, extra))
2082 elif cell == '':
2081 elif cell == '':
2083 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2082 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2084 if self.find_line_magic(magic_name) is not None:
2083 if self.find_line_magic(magic_name) is not None:
2085 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2084 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2086 raise UsageError(message)
2085 raise UsageError(message)
2087 else:
2086 else:
2088 # Note: this is the distance in the stack to the user's frame.
2087 # Note: this is the distance in the stack to the user's frame.
2089 # This will need to be updated if the internal calling logic gets
2088 # This will need to be updated if the internal calling logic gets
2090 # refactored, or else we'll be expanding the wrong variables.
2089 # refactored, or else we'll be expanding the wrong variables.
2091 stack_depth = 2
2090 stack_depth = 2
2092 magic_arg_s = self.var_expand(line, stack_depth)
2091 magic_arg_s = self.var_expand(line, stack_depth)
2093 with self.builtin_trap:
2092 with self.builtin_trap:
2094 result = fn(magic_arg_s, cell)
2093 result = fn(magic_arg_s, cell)
2095 return result
2094 return result
2096
2095
2097 def find_line_magic(self, magic_name):
2096 def find_line_magic(self, magic_name):
2098 """Find and return a line magic by name.
2097 """Find and return a line magic by name.
2099
2098
2100 Returns None if the magic isn't found."""
2099 Returns None if the magic isn't found."""
2101 return self.magics_manager.magics['line'].get(magic_name)
2100 return self.magics_manager.magics['line'].get(magic_name)
2102
2101
2103 def find_cell_magic(self, magic_name):
2102 def find_cell_magic(self, magic_name):
2104 """Find and return a cell magic by name.
2103 """Find and return a cell magic by name.
2105
2104
2106 Returns None if the magic isn't found."""
2105 Returns None if the magic isn't found."""
2107 return self.magics_manager.magics['cell'].get(magic_name)
2106 return self.magics_manager.magics['cell'].get(magic_name)
2108
2107
2109 def find_magic(self, magic_name, magic_kind='line'):
2108 def find_magic(self, magic_name, magic_kind='line'):
2110 """Find and return a magic of the given type by name.
2109 """Find and return a magic of the given type by name.
2111
2110
2112 Returns None if the magic isn't found."""
2111 Returns None if the magic isn't found."""
2113 return self.magics_manager.magics[magic_kind].get(magic_name)
2112 return self.magics_manager.magics[magic_kind].get(magic_name)
2114
2113
2115 def magic(self, arg_s):
2114 def magic(self, arg_s):
2116 """DEPRECATED. Use run_line_magic() instead.
2115 """DEPRECATED. Use run_line_magic() instead.
2117
2116
2118 Call a magic function by name.
2117 Call a magic function by name.
2119
2118
2120 Input: a string containing the name of the magic function to call and
2119 Input: a string containing the name of the magic function to call and
2121 any additional arguments to be passed to the magic.
2120 any additional arguments to be passed to the magic.
2122
2121
2123 magic('name -opt foo bar') is equivalent to typing at the ipython
2122 magic('name -opt foo bar') is equivalent to typing at the ipython
2124 prompt:
2123 prompt:
2125
2124
2126 In[1]: %name -opt foo bar
2125 In[1]: %name -opt foo bar
2127
2126
2128 To call a magic without arguments, simply use magic('name').
2127 To call a magic without arguments, simply use magic('name').
2129
2128
2130 This provides a proper Python function to call IPython's magics in any
2129 This provides a proper Python function to call IPython's magics in any
2131 valid Python code you can type at the interpreter, including loops and
2130 valid Python code you can type at the interpreter, including loops and
2132 compound statements.
2131 compound statements.
2133 """
2132 """
2134 # TODO: should we issue a loud deprecation warning here?
2133 # TODO: should we issue a loud deprecation warning here?
2135 magic_name, _, magic_arg_s = arg_s.partition(' ')
2134 magic_name, _, magic_arg_s = arg_s.partition(' ')
2136 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2135 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2137 return self.run_line_magic(magic_name, magic_arg_s)
2136 return self.run_line_magic(magic_name, magic_arg_s)
2138
2137
2139 #-------------------------------------------------------------------------
2138 #-------------------------------------------------------------------------
2140 # Things related to macros
2139 # Things related to macros
2141 #-------------------------------------------------------------------------
2140 #-------------------------------------------------------------------------
2142
2141
2143 def define_macro(self, name, themacro):
2142 def define_macro(self, name, themacro):
2144 """Define a new macro
2143 """Define a new macro
2145
2144
2146 Parameters
2145 Parameters
2147 ----------
2146 ----------
2148 name : str
2147 name : str
2149 The name of the macro.
2148 The name of the macro.
2150 themacro : str or Macro
2149 themacro : str or Macro
2151 The action to do upon invoking the macro. If a string, a new
2150 The action to do upon invoking the macro. If a string, a new
2152 Macro object is created by passing the string to it.
2151 Macro object is created by passing the string to it.
2153 """
2152 """
2154
2153
2155 from IPython.core import macro
2154 from IPython.core import macro
2156
2155
2157 if isinstance(themacro, string_types):
2156 if isinstance(themacro, str):
2158 themacro = macro.Macro(themacro)
2157 themacro = macro.Macro(themacro)
2159 if not isinstance(themacro, macro.Macro):
2158 if not isinstance(themacro, macro.Macro):
2160 raise ValueError('A macro must be a string or a Macro instance.')
2159 raise ValueError('A macro must be a string or a Macro instance.')
2161 self.user_ns[name] = themacro
2160 self.user_ns[name] = themacro
2162
2161
2163 #-------------------------------------------------------------------------
2162 #-------------------------------------------------------------------------
2164 # Things related to the running of system commands
2163 # Things related to the running of system commands
2165 #-------------------------------------------------------------------------
2164 #-------------------------------------------------------------------------
2166
2165
2167 def system_piped(self, cmd):
2166 def system_piped(self, cmd):
2168 """Call the given cmd in a subprocess, piping stdout/err
2167 """Call the given cmd in a subprocess, piping stdout/err
2169
2168
2170 Parameters
2169 Parameters
2171 ----------
2170 ----------
2172 cmd : str
2171 cmd : str
2173 Command to execute (can not end in '&', as background processes are
2172 Command to execute (can not end in '&', as background processes are
2174 not supported. Should not be a command that expects input
2173 not supported. Should not be a command that expects input
2175 other than simple text.
2174 other than simple text.
2176 """
2175 """
2177 if cmd.rstrip().endswith('&'):
2176 if cmd.rstrip().endswith('&'):
2178 # this is *far* from a rigorous test
2177 # this is *far* from a rigorous test
2179 # We do not support backgrounding processes because we either use
2178 # We do not support backgrounding processes because we either use
2180 # pexpect or pipes to read from. Users can always just call
2179 # pexpect or pipes to read from. Users can always just call
2181 # os.system() or use ip.system=ip.system_raw
2180 # os.system() or use ip.system=ip.system_raw
2182 # if they really want a background process.
2181 # if they really want a background process.
2183 raise OSError("Background processes not supported.")
2182 raise OSError("Background processes not supported.")
2184
2183
2185 # we explicitly do NOT return the subprocess status code, because
2184 # we explicitly do NOT return the subprocess status code, because
2186 # a non-None value would trigger :func:`sys.displayhook` calls.
2185 # a non-None value would trigger :func:`sys.displayhook` calls.
2187 # Instead, we store the exit_code in user_ns.
2186 # Instead, we store the exit_code in user_ns.
2188 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2187 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2189
2188
2190 def system_raw(self, cmd):
2189 def system_raw(self, cmd):
2191 """Call the given cmd in a subprocess using os.system on Windows or
2190 """Call the given cmd in a subprocess using os.system on Windows or
2192 subprocess.call using the system shell on other platforms.
2191 subprocess.call using the system shell on other platforms.
2193
2192
2194 Parameters
2193 Parameters
2195 ----------
2194 ----------
2196 cmd : str
2195 cmd : str
2197 Command to execute.
2196 Command to execute.
2198 """
2197 """
2199 cmd = self.var_expand(cmd, depth=1)
2198 cmd = self.var_expand(cmd, depth=1)
2200 # protect os.system from UNC paths on Windows, which it can't handle:
2199 # protect os.system from UNC paths on Windows, which it can't handle:
2201 if sys.platform == 'win32':
2200 if sys.platform == 'win32':
2202 from IPython.utils._process_win32 import AvoidUNCPath
2201 from IPython.utils._process_win32 import AvoidUNCPath
2203 with AvoidUNCPath() as path:
2202 with AvoidUNCPath() as path:
2204 if path is not None:
2203 if path is not None:
2205 cmd = '"pushd %s &&"%s' % (path, cmd)
2204 cmd = '"pushd %s &&"%s' % (path, cmd)
2206 cmd = py3compat.unicode_to_str(cmd)
2207 try:
2205 try:
2208 ec = os.system(cmd)
2206 ec = os.system(cmd)
2209 except KeyboardInterrupt:
2207 except KeyboardInterrupt:
2210 print('\n' + self.get_exception_only(), file=sys.stderr)
2208 print('\n' + self.get_exception_only(), file=sys.stderr)
2211 ec = -2
2209 ec = -2
2212 else:
2210 else:
2213 cmd = py3compat.unicode_to_str(cmd)
2214 # For posix the result of the subprocess.call() below is an exit
2211 # For posix the result of the subprocess.call() below is an exit
2215 # code, which by convention is zero for success, positive for
2212 # code, which by convention is zero for success, positive for
2216 # program failure. Exit codes above 128 are reserved for signals,
2213 # program failure. Exit codes above 128 are reserved for signals,
2217 # and the formula for converting a signal to an exit code is usually
2214 # and the formula for converting a signal to an exit code is usually
2218 # signal_number+128. To more easily differentiate between exit
2215 # signal_number+128. To more easily differentiate between exit
2219 # codes and signals, ipython uses negative numbers. For instance
2216 # codes and signals, ipython uses negative numbers. For instance
2220 # since control-c is signal 2 but exit code 130, ipython's
2217 # since control-c is signal 2 but exit code 130, ipython's
2221 # _exit_code variable will read -2. Note that some shells like
2218 # _exit_code variable will read -2. Note that some shells like
2222 # csh and fish don't follow sh/bash conventions for exit codes.
2219 # csh and fish don't follow sh/bash conventions for exit codes.
2223 executable = os.environ.get('SHELL', None)
2220 executable = os.environ.get('SHELL', None)
2224 try:
2221 try:
2225 # Use env shell instead of default /bin/sh
2222 # Use env shell instead of default /bin/sh
2226 ec = subprocess.call(cmd, shell=True, executable=executable)
2223 ec = subprocess.call(cmd, shell=True, executable=executable)
2227 except KeyboardInterrupt:
2224 except KeyboardInterrupt:
2228 # intercept control-C; a long traceback is not useful here
2225 # intercept control-C; a long traceback is not useful here
2229 print('\n' + self.get_exception_only(), file=sys.stderr)
2226 print('\n' + self.get_exception_only(), file=sys.stderr)
2230 ec = 130
2227 ec = 130
2231 if ec > 128:
2228 if ec > 128:
2232 ec = -(ec - 128)
2229 ec = -(ec - 128)
2233
2230
2234 # We explicitly do NOT return the subprocess status code, because
2231 # We explicitly do NOT return the subprocess status code, because
2235 # a non-None value would trigger :func:`sys.displayhook` calls.
2232 # a non-None value would trigger :func:`sys.displayhook` calls.
2236 # Instead, we store the exit_code in user_ns. Note the semantics
2233 # Instead, we store the exit_code in user_ns. Note the semantics
2237 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2234 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2238 # but raising SystemExit(_exit_code) will give status 254!
2235 # but raising SystemExit(_exit_code) will give status 254!
2239 self.user_ns['_exit_code'] = ec
2236 self.user_ns['_exit_code'] = ec
2240
2237
2241 # use piped system by default, because it is better behaved
2238 # use piped system by default, because it is better behaved
2242 system = system_piped
2239 system = system_piped
2243
2240
2244 def getoutput(self, cmd, split=True, depth=0):
2241 def getoutput(self, cmd, split=True, depth=0):
2245 """Get output (possibly including stderr) from a subprocess.
2242 """Get output (possibly including stderr) from a subprocess.
2246
2243
2247 Parameters
2244 Parameters
2248 ----------
2245 ----------
2249 cmd : str
2246 cmd : str
2250 Command to execute (can not end in '&', as background processes are
2247 Command to execute (can not end in '&', as background processes are
2251 not supported.
2248 not supported.
2252 split : bool, optional
2249 split : bool, optional
2253 If True, split the output into an IPython SList. Otherwise, an
2250 If True, split the output into an IPython SList. Otherwise, an
2254 IPython LSString is returned. These are objects similar to normal
2251 IPython LSString is returned. These are objects similar to normal
2255 lists and strings, with a few convenience attributes for easier
2252 lists and strings, with a few convenience attributes for easier
2256 manipulation of line-based output. You can use '?' on them for
2253 manipulation of line-based output. You can use '?' on them for
2257 details.
2254 details.
2258 depth : int, optional
2255 depth : int, optional
2259 How many frames above the caller are the local variables which should
2256 How many frames above the caller are the local variables which should
2260 be expanded in the command string? The default (0) assumes that the
2257 be expanded in the command string? The default (0) assumes that the
2261 expansion variables are in the stack frame calling this function.
2258 expansion variables are in the stack frame calling this function.
2262 """
2259 """
2263 if cmd.rstrip().endswith('&'):
2260 if cmd.rstrip().endswith('&'):
2264 # this is *far* from a rigorous test
2261 # this is *far* from a rigorous test
2265 raise OSError("Background processes not supported.")
2262 raise OSError("Background processes not supported.")
2266 out = getoutput(self.var_expand(cmd, depth=depth+1))
2263 out = getoutput(self.var_expand(cmd, depth=depth+1))
2267 if split:
2264 if split:
2268 out = SList(out.splitlines())
2265 out = SList(out.splitlines())
2269 else:
2266 else:
2270 out = LSString(out)
2267 out = LSString(out)
2271 return out
2268 return out
2272
2269
2273 #-------------------------------------------------------------------------
2270 #-------------------------------------------------------------------------
2274 # Things related to aliases
2271 # Things related to aliases
2275 #-------------------------------------------------------------------------
2272 #-------------------------------------------------------------------------
2276
2273
2277 def init_alias(self):
2274 def init_alias(self):
2278 self.alias_manager = AliasManager(shell=self, parent=self)
2275 self.alias_manager = AliasManager(shell=self, parent=self)
2279 self.configurables.append(self.alias_manager)
2276 self.configurables.append(self.alias_manager)
2280
2277
2281 #-------------------------------------------------------------------------
2278 #-------------------------------------------------------------------------
2282 # Things related to extensions
2279 # Things related to extensions
2283 #-------------------------------------------------------------------------
2280 #-------------------------------------------------------------------------
2284
2281
2285 def init_extension_manager(self):
2282 def init_extension_manager(self):
2286 self.extension_manager = ExtensionManager(shell=self, parent=self)
2283 self.extension_manager = ExtensionManager(shell=self, parent=self)
2287 self.configurables.append(self.extension_manager)
2284 self.configurables.append(self.extension_manager)
2288
2285
2289 #-------------------------------------------------------------------------
2286 #-------------------------------------------------------------------------
2290 # Things related to payloads
2287 # Things related to payloads
2291 #-------------------------------------------------------------------------
2288 #-------------------------------------------------------------------------
2292
2289
2293 def init_payload(self):
2290 def init_payload(self):
2294 self.payload_manager = PayloadManager(parent=self)
2291 self.payload_manager = PayloadManager(parent=self)
2295 self.configurables.append(self.payload_manager)
2292 self.configurables.append(self.payload_manager)
2296
2293
2297 #-------------------------------------------------------------------------
2294 #-------------------------------------------------------------------------
2298 # Things related to the prefilter
2295 # Things related to the prefilter
2299 #-------------------------------------------------------------------------
2296 #-------------------------------------------------------------------------
2300
2297
2301 def init_prefilter(self):
2298 def init_prefilter(self):
2302 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2299 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2303 self.configurables.append(self.prefilter_manager)
2300 self.configurables.append(self.prefilter_manager)
2304 # Ultimately this will be refactored in the new interpreter code, but
2301 # Ultimately this will be refactored in the new interpreter code, but
2305 # for now, we should expose the main prefilter method (there's legacy
2302 # for now, we should expose the main prefilter method (there's legacy
2306 # code out there that may rely on this).
2303 # code out there that may rely on this).
2307 self.prefilter = self.prefilter_manager.prefilter_lines
2304 self.prefilter = self.prefilter_manager.prefilter_lines
2308
2305
2309 def auto_rewrite_input(self, cmd):
2306 def auto_rewrite_input(self, cmd):
2310 """Print to the screen the rewritten form of the user's command.
2307 """Print to the screen the rewritten form of the user's command.
2311
2308
2312 This shows visual feedback by rewriting input lines that cause
2309 This shows visual feedback by rewriting input lines that cause
2313 automatic calling to kick in, like::
2310 automatic calling to kick in, like::
2314
2311
2315 /f x
2312 /f x
2316
2313
2317 into::
2314 into::
2318
2315
2319 ------> f(x)
2316 ------> f(x)
2320
2317
2321 after the user's input prompt. This helps the user understand that the
2318 after the user's input prompt. This helps the user understand that the
2322 input line was transformed automatically by IPython.
2319 input line was transformed automatically by IPython.
2323 """
2320 """
2324 if not self.show_rewritten_input:
2321 if not self.show_rewritten_input:
2325 return
2322 return
2326
2323
2327 # This is overridden in TerminalInteractiveShell to use fancy prompts
2324 # This is overridden in TerminalInteractiveShell to use fancy prompts
2328 print("------> " + cmd)
2325 print("------> " + cmd)
2329
2326
2330 #-------------------------------------------------------------------------
2327 #-------------------------------------------------------------------------
2331 # Things related to extracting values/expressions from kernel and user_ns
2328 # Things related to extracting values/expressions from kernel and user_ns
2332 #-------------------------------------------------------------------------
2329 #-------------------------------------------------------------------------
2333
2330
2334 def _user_obj_error(self):
2331 def _user_obj_error(self):
2335 """return simple exception dict
2332 """return simple exception dict
2336
2333
2337 for use in user_expressions
2334 for use in user_expressions
2338 """
2335 """
2339
2336
2340 etype, evalue, tb = self._get_exc_info()
2337 etype, evalue, tb = self._get_exc_info()
2341 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2338 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2342
2339
2343 exc_info = {
2340 exc_info = {
2344 u'status' : 'error',
2341 u'status' : 'error',
2345 u'traceback' : stb,
2342 u'traceback' : stb,
2346 u'ename' : unicode_type(etype.__name__),
2343 u'ename' : etype.__name__,
2347 u'evalue' : py3compat.safe_unicode(evalue),
2344 u'evalue' : py3compat.safe_unicode(evalue),
2348 }
2345 }
2349
2346
2350 return exc_info
2347 return exc_info
2351
2348
2352 def _format_user_obj(self, obj):
2349 def _format_user_obj(self, obj):
2353 """format a user object to display dict
2350 """format a user object to display dict
2354
2351
2355 for use in user_expressions
2352 for use in user_expressions
2356 """
2353 """
2357
2354
2358 data, md = self.display_formatter.format(obj)
2355 data, md = self.display_formatter.format(obj)
2359 value = {
2356 value = {
2360 'status' : 'ok',
2357 'status' : 'ok',
2361 'data' : data,
2358 'data' : data,
2362 'metadata' : md,
2359 'metadata' : md,
2363 }
2360 }
2364 return value
2361 return value
2365
2362
2366 def user_expressions(self, expressions):
2363 def user_expressions(self, expressions):
2367 """Evaluate a dict of expressions in the user's namespace.
2364 """Evaluate a dict of expressions in the user's namespace.
2368
2365
2369 Parameters
2366 Parameters
2370 ----------
2367 ----------
2371 expressions : dict
2368 expressions : dict
2372 A dict with string keys and string values. The expression values
2369 A dict with string keys and string values. The expression values
2373 should be valid Python expressions, each of which will be evaluated
2370 should be valid Python expressions, each of which will be evaluated
2374 in the user namespace.
2371 in the user namespace.
2375
2372
2376 Returns
2373 Returns
2377 -------
2374 -------
2378 A dict, keyed like the input expressions dict, with the rich mime-typed
2375 A dict, keyed like the input expressions dict, with the rich mime-typed
2379 display_data of each value.
2376 display_data of each value.
2380 """
2377 """
2381 out = {}
2378 out = {}
2382 user_ns = self.user_ns
2379 user_ns = self.user_ns
2383 global_ns = self.user_global_ns
2380 global_ns = self.user_global_ns
2384
2381
2385 for key, expr in iteritems(expressions):
2382 for key, expr in expressions.items():
2386 try:
2383 try:
2387 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2384 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2388 except:
2385 except:
2389 value = self._user_obj_error()
2386 value = self._user_obj_error()
2390 out[key] = value
2387 out[key] = value
2391 return out
2388 return out
2392
2389
2393 #-------------------------------------------------------------------------
2390 #-------------------------------------------------------------------------
2394 # Things related to the running of code
2391 # Things related to the running of code
2395 #-------------------------------------------------------------------------
2392 #-------------------------------------------------------------------------
2396
2393
2397 def ex(self, cmd):
2394 def ex(self, cmd):
2398 """Execute a normal python statement in user namespace."""
2395 """Execute a normal python statement in user namespace."""
2399 with self.builtin_trap:
2396 with self.builtin_trap:
2400 exec(cmd, self.user_global_ns, self.user_ns)
2397 exec(cmd, self.user_global_ns, self.user_ns)
2401
2398
2402 def ev(self, expr):
2399 def ev(self, expr):
2403 """Evaluate python expression expr in user namespace.
2400 """Evaluate python expression expr in user namespace.
2404
2401
2405 Returns the result of evaluation
2402 Returns the result of evaluation
2406 """
2403 """
2407 with self.builtin_trap:
2404 with self.builtin_trap:
2408 return eval(expr, self.user_global_ns, self.user_ns)
2405 return eval(expr, self.user_global_ns, self.user_ns)
2409
2406
2410 def safe_execfile(self, fname, *where, **kw):
2407 def safe_execfile(self, fname, *where, **kw):
2411 """A safe version of the builtin execfile().
2408 """A safe version of the builtin execfile().
2412
2409
2413 This version will never throw an exception, but instead print
2410 This version will never throw an exception, but instead print
2414 helpful error messages to the screen. This only works on pure
2411 helpful error messages to the screen. This only works on pure
2415 Python files with the .py extension.
2412 Python files with the .py extension.
2416
2413
2417 Parameters
2414 Parameters
2418 ----------
2415 ----------
2419 fname : string
2416 fname : string
2420 The name of the file to be executed.
2417 The name of the file to be executed.
2421 where : tuple
2418 where : tuple
2422 One or two namespaces, passed to execfile() as (globals,locals).
2419 One or two namespaces, passed to execfile() as (globals,locals).
2423 If only one is given, it is passed as both.
2420 If only one is given, it is passed as both.
2424 exit_ignore : bool (False)
2421 exit_ignore : bool (False)
2425 If True, then silence SystemExit for non-zero status (it is always
2422 If True, then silence SystemExit for non-zero status (it is always
2426 silenced for zero status, as it is so common).
2423 silenced for zero status, as it is so common).
2427 raise_exceptions : bool (False)
2424 raise_exceptions : bool (False)
2428 If True raise exceptions everywhere. Meant for testing.
2425 If True raise exceptions everywhere. Meant for testing.
2429 shell_futures : bool (False)
2426 shell_futures : bool (False)
2430 If True, the code will share future statements with the interactive
2427 If True, the code will share future statements with the interactive
2431 shell. It will both be affected by previous __future__ imports, and
2428 shell. It will both be affected by previous __future__ imports, and
2432 any __future__ imports in the code will affect the shell. If False,
2429 any __future__ imports in the code will affect the shell. If False,
2433 __future__ imports are not shared in either direction.
2430 __future__ imports are not shared in either direction.
2434
2431
2435 """
2432 """
2436 kw.setdefault('exit_ignore', False)
2433 kw.setdefault('exit_ignore', False)
2437 kw.setdefault('raise_exceptions', False)
2434 kw.setdefault('raise_exceptions', False)
2438 kw.setdefault('shell_futures', False)
2435 kw.setdefault('shell_futures', False)
2439
2436
2440 fname = os.path.abspath(os.path.expanduser(fname))
2437 fname = os.path.abspath(os.path.expanduser(fname))
2441
2438
2442 # Make sure we can open the file
2439 # Make sure we can open the file
2443 try:
2440 try:
2444 with open(fname):
2441 with open(fname):
2445 pass
2442 pass
2446 except:
2443 except:
2447 warn('Could not open file <%s> for safe execution.' % fname)
2444 warn('Could not open file <%s> for safe execution.' % fname)
2448 return
2445 return
2449
2446
2450 # Find things also in current directory. This is needed to mimic the
2447 # Find things also in current directory. This is needed to mimic the
2451 # behavior of running a script from the system command line, where
2448 # behavior of running a script from the system command line, where
2452 # Python inserts the script's directory into sys.path
2449 # Python inserts the script's directory into sys.path
2453 dname = os.path.dirname(fname)
2450 dname = os.path.dirname(fname)
2454
2451
2455 with prepended_to_syspath(dname), self.builtin_trap:
2452 with prepended_to_syspath(dname), self.builtin_trap:
2456 try:
2453 try:
2457 glob, loc = (where + (None, ))[:2]
2454 glob, loc = (where + (None, ))[:2]
2458 py3compat.execfile(
2455 py3compat.execfile(
2459 fname, glob, loc,
2456 fname, glob, loc,
2460 self.compile if kw['shell_futures'] else None)
2457 self.compile if kw['shell_futures'] else None)
2461 except SystemExit as status:
2458 except SystemExit as status:
2462 # If the call was made with 0 or None exit status (sys.exit(0)
2459 # If the call was made with 0 or None exit status (sys.exit(0)
2463 # or sys.exit() ), don't bother showing a traceback, as both of
2460 # or sys.exit() ), don't bother showing a traceback, as both of
2464 # these are considered normal by the OS:
2461 # these are considered normal by the OS:
2465 # > python -c'import sys;sys.exit(0)'; echo $?
2462 # > python -c'import sys;sys.exit(0)'; echo $?
2466 # 0
2463 # 0
2467 # > python -c'import sys;sys.exit()'; echo $?
2464 # > python -c'import sys;sys.exit()'; echo $?
2468 # 0
2465 # 0
2469 # For other exit status, we show the exception unless
2466 # For other exit status, we show the exception unless
2470 # explicitly silenced, but only in short form.
2467 # explicitly silenced, but only in short form.
2471 if status.code:
2468 if status.code:
2472 if kw['raise_exceptions']:
2469 if kw['raise_exceptions']:
2473 raise
2470 raise
2474 if not kw['exit_ignore']:
2471 if not kw['exit_ignore']:
2475 self.showtraceback(exception_only=True)
2472 self.showtraceback(exception_only=True)
2476 except:
2473 except:
2477 if kw['raise_exceptions']:
2474 if kw['raise_exceptions']:
2478 raise
2475 raise
2479 # tb offset is 2 because we wrap execfile
2476 # tb offset is 2 because we wrap execfile
2480 self.showtraceback(tb_offset=2)
2477 self.showtraceback(tb_offset=2)
2481
2478
2482 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2479 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2483 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2480 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2484
2481
2485 Parameters
2482 Parameters
2486 ----------
2483 ----------
2487 fname : str
2484 fname : str
2488 The name of the file to execute. The filename must have a
2485 The name of the file to execute. The filename must have a
2489 .ipy or .ipynb extension.
2486 .ipy or .ipynb extension.
2490 shell_futures : bool (False)
2487 shell_futures : bool (False)
2491 If True, the code will share future statements with the interactive
2488 If True, the code will share future statements with the interactive
2492 shell. It will both be affected by previous __future__ imports, and
2489 shell. It will both be affected by previous __future__ imports, and
2493 any __future__ imports in the code will affect the shell. If False,
2490 any __future__ imports in the code will affect the shell. If False,
2494 __future__ imports are not shared in either direction.
2491 __future__ imports are not shared in either direction.
2495 raise_exceptions : bool (False)
2492 raise_exceptions : bool (False)
2496 If True raise exceptions everywhere. Meant for testing.
2493 If True raise exceptions everywhere. Meant for testing.
2497 """
2494 """
2498 fname = os.path.abspath(os.path.expanduser(fname))
2495 fname = os.path.abspath(os.path.expanduser(fname))
2499
2496
2500 # Make sure we can open the file
2497 # Make sure we can open the file
2501 try:
2498 try:
2502 with open(fname):
2499 with open(fname):
2503 pass
2500 pass
2504 except:
2501 except:
2505 warn('Could not open file <%s> for safe execution.' % fname)
2502 warn('Could not open file <%s> for safe execution.' % fname)
2506 return
2503 return
2507
2504
2508 # Find things also in current directory. This is needed to mimic the
2505 # Find things also in current directory. This is needed to mimic the
2509 # behavior of running a script from the system command line, where
2506 # behavior of running a script from the system command line, where
2510 # Python inserts the script's directory into sys.path
2507 # Python inserts the script's directory into sys.path
2511 dname = os.path.dirname(fname)
2508 dname = os.path.dirname(fname)
2512
2509
2513 def get_cells():
2510 def get_cells():
2514 """generator for sequence of code blocks to run"""
2511 """generator for sequence of code blocks to run"""
2515 if fname.endswith('.ipynb'):
2512 if fname.endswith('.ipynb'):
2516 from nbformat import read
2513 from nbformat import read
2517 with io_open(fname) as f:
2514 with io_open(fname) as f:
2518 nb = read(f, as_version=4)
2515 nb = read(f, as_version=4)
2519 if not nb.cells:
2516 if not nb.cells:
2520 return
2517 return
2521 for cell in nb.cells:
2518 for cell in nb.cells:
2522 if cell.cell_type == 'code':
2519 if cell.cell_type == 'code':
2523 yield cell.source
2520 yield cell.source
2524 else:
2521 else:
2525 with open(fname) as f:
2522 with open(fname) as f:
2526 yield f.read()
2523 yield f.read()
2527
2524
2528 with prepended_to_syspath(dname):
2525 with prepended_to_syspath(dname):
2529 try:
2526 try:
2530 for cell in get_cells():
2527 for cell in get_cells():
2531 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2528 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2532 if raise_exceptions:
2529 if raise_exceptions:
2533 result.raise_error()
2530 result.raise_error()
2534 elif not result.success:
2531 elif not result.success:
2535 break
2532 break
2536 except:
2533 except:
2537 if raise_exceptions:
2534 if raise_exceptions:
2538 raise
2535 raise
2539 self.showtraceback()
2536 self.showtraceback()
2540 warn('Unknown failure executing file: <%s>' % fname)
2537 warn('Unknown failure executing file: <%s>' % fname)
2541
2538
2542 def safe_run_module(self, mod_name, where):
2539 def safe_run_module(self, mod_name, where):
2543 """A safe version of runpy.run_module().
2540 """A safe version of runpy.run_module().
2544
2541
2545 This version will never throw an exception, but instead print
2542 This version will never throw an exception, but instead print
2546 helpful error messages to the screen.
2543 helpful error messages to the screen.
2547
2544
2548 `SystemExit` exceptions with status code 0 or None are ignored.
2545 `SystemExit` exceptions with status code 0 or None are ignored.
2549
2546
2550 Parameters
2547 Parameters
2551 ----------
2548 ----------
2552 mod_name : string
2549 mod_name : string
2553 The name of the module to be executed.
2550 The name of the module to be executed.
2554 where : dict
2551 where : dict
2555 The globals namespace.
2552 The globals namespace.
2556 """
2553 """
2557 try:
2554 try:
2558 try:
2555 try:
2559 where.update(
2556 where.update(
2560 runpy.run_module(str(mod_name), run_name="__main__",
2557 runpy.run_module(str(mod_name), run_name="__main__",
2561 alter_sys=True)
2558 alter_sys=True)
2562 )
2559 )
2563 except SystemExit as status:
2560 except SystemExit as status:
2564 if status.code:
2561 if status.code:
2565 raise
2562 raise
2566 except:
2563 except:
2567 self.showtraceback()
2564 self.showtraceback()
2568 warn('Unknown failure executing module: <%s>' % mod_name)
2565 warn('Unknown failure executing module: <%s>' % mod_name)
2569
2566
2570 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2567 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2571 """Run a complete IPython cell.
2568 """Run a complete IPython cell.
2572
2569
2573 Parameters
2570 Parameters
2574 ----------
2571 ----------
2575 raw_cell : str
2572 raw_cell : str
2576 The code (including IPython code such as %magic functions) to run.
2573 The code (including IPython code such as %magic functions) to run.
2577 store_history : bool
2574 store_history : bool
2578 If True, the raw and translated cell will be stored in IPython's
2575 If True, the raw and translated cell will be stored in IPython's
2579 history. For user code calling back into IPython's machinery, this
2576 history. For user code calling back into IPython's machinery, this
2580 should be set to False.
2577 should be set to False.
2581 silent : bool
2578 silent : bool
2582 If True, avoid side-effects, such as implicit displayhooks and
2579 If True, avoid side-effects, such as implicit displayhooks and
2583 and logging. silent=True forces store_history=False.
2580 and logging. silent=True forces store_history=False.
2584 shell_futures : bool
2581 shell_futures : bool
2585 If True, the code will share future statements with the interactive
2582 If True, the code will share future statements with the interactive
2586 shell. It will both be affected by previous __future__ imports, and
2583 shell. It will both be affected by previous __future__ imports, and
2587 any __future__ imports in the code will affect the shell. If False,
2584 any __future__ imports in the code will affect the shell. If False,
2588 __future__ imports are not shared in either direction.
2585 __future__ imports are not shared in either direction.
2589
2586
2590 Returns
2587 Returns
2591 -------
2588 -------
2592 result : :class:`ExecutionResult`
2589 result : :class:`ExecutionResult`
2593 """
2590 """
2594 result = ExecutionResult()
2591 result = ExecutionResult()
2595
2592
2596 if (not raw_cell) or raw_cell.isspace():
2593 if (not raw_cell) or raw_cell.isspace():
2597 self.last_execution_succeeded = True
2594 self.last_execution_succeeded = True
2598 return result
2595 return result
2599
2596
2600 if silent:
2597 if silent:
2601 store_history = False
2598 store_history = False
2602
2599
2603 if store_history:
2600 if store_history:
2604 result.execution_count = self.execution_count
2601 result.execution_count = self.execution_count
2605
2602
2606 def error_before_exec(value):
2603 def error_before_exec(value):
2607 result.error_before_exec = value
2604 result.error_before_exec = value
2608 self.last_execution_succeeded = False
2605 self.last_execution_succeeded = False
2609 return result
2606 return result
2610
2607
2611 self.events.trigger('pre_execute')
2608 self.events.trigger('pre_execute')
2612 if not silent:
2609 if not silent:
2613 self.events.trigger('pre_run_cell')
2610 self.events.trigger('pre_run_cell')
2614
2611
2615 # If any of our input transformation (input_transformer_manager or
2612 # If any of our input transformation (input_transformer_manager or
2616 # prefilter_manager) raises an exception, we store it in this variable
2613 # prefilter_manager) raises an exception, we store it in this variable
2617 # so that we can display the error after logging the input and storing
2614 # so that we can display the error after logging the input and storing
2618 # it in the history.
2615 # it in the history.
2619 preprocessing_exc_tuple = None
2616 preprocessing_exc_tuple = None
2620 try:
2617 try:
2621 # Static input transformations
2618 # Static input transformations
2622 cell = self.input_transformer_manager.transform_cell(raw_cell)
2619 cell = self.input_transformer_manager.transform_cell(raw_cell)
2623 except SyntaxError:
2620 except SyntaxError:
2624 preprocessing_exc_tuple = sys.exc_info()
2621 preprocessing_exc_tuple = sys.exc_info()
2625 cell = raw_cell # cell has to exist so it can be stored/logged
2622 cell = raw_cell # cell has to exist so it can be stored/logged
2626 else:
2623 else:
2627 if len(cell.splitlines()) == 1:
2624 if len(cell.splitlines()) == 1:
2628 # Dynamic transformations - only applied for single line commands
2625 # Dynamic transformations - only applied for single line commands
2629 with self.builtin_trap:
2626 with self.builtin_trap:
2630 try:
2627 try:
2631 # use prefilter_lines to handle trailing newlines
2628 # use prefilter_lines to handle trailing newlines
2632 # restore trailing newline for ast.parse
2629 # restore trailing newline for ast.parse
2633 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2630 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2634 except Exception:
2631 except Exception:
2635 # don't allow prefilter errors to crash IPython
2632 # don't allow prefilter errors to crash IPython
2636 preprocessing_exc_tuple = sys.exc_info()
2633 preprocessing_exc_tuple = sys.exc_info()
2637
2634
2638 # Store raw and processed history
2635 # Store raw and processed history
2639 if store_history:
2636 if store_history:
2640 self.history_manager.store_inputs(self.execution_count,
2637 self.history_manager.store_inputs(self.execution_count,
2641 cell, raw_cell)
2638 cell, raw_cell)
2642 if not silent:
2639 if not silent:
2643 self.logger.log(cell, raw_cell)
2640 self.logger.log(cell, raw_cell)
2644
2641
2645 # Display the exception if input processing failed.
2642 # Display the exception if input processing failed.
2646 if preprocessing_exc_tuple is not None:
2643 if preprocessing_exc_tuple is not None:
2647 self.showtraceback(preprocessing_exc_tuple)
2644 self.showtraceback(preprocessing_exc_tuple)
2648 if store_history:
2645 if store_history:
2649 self.execution_count += 1
2646 self.execution_count += 1
2650 return error_before_exec(preprocessing_exc_tuple[2])
2647 return error_before_exec(preprocessing_exc_tuple[2])
2651
2648
2652 # Our own compiler remembers the __future__ environment. If we want to
2649 # Our own compiler remembers the __future__ environment. If we want to
2653 # run code with a separate __future__ environment, use the default
2650 # run code with a separate __future__ environment, use the default
2654 # compiler
2651 # compiler
2655 compiler = self.compile if shell_futures else CachingCompiler()
2652 compiler = self.compile if shell_futures else CachingCompiler()
2656
2653
2657 with self.builtin_trap:
2654 with self.builtin_trap:
2658 cell_name = self.compile.cache(cell, self.execution_count)
2655 cell_name = self.compile.cache(cell, self.execution_count)
2659
2656
2660 with self.display_trap:
2657 with self.display_trap:
2661 # Compile to bytecode
2658 # Compile to bytecode
2662 try:
2659 try:
2663 code_ast = compiler.ast_parse(cell, filename=cell_name)
2660 code_ast = compiler.ast_parse(cell, filename=cell_name)
2664 except self.custom_exceptions as e:
2661 except self.custom_exceptions as e:
2665 etype, value, tb = sys.exc_info()
2662 etype, value, tb = sys.exc_info()
2666 self.CustomTB(etype, value, tb)
2663 self.CustomTB(etype, value, tb)
2667 return error_before_exec(e)
2664 return error_before_exec(e)
2668 except IndentationError as e:
2665 except IndentationError as e:
2669 self.showindentationerror()
2666 self.showindentationerror()
2670 if store_history:
2667 if store_history:
2671 self.execution_count += 1
2668 self.execution_count += 1
2672 return error_before_exec(e)
2669 return error_before_exec(e)
2673 except (OverflowError, SyntaxError, ValueError, TypeError,
2670 except (OverflowError, SyntaxError, ValueError, TypeError,
2674 MemoryError) as e:
2671 MemoryError) as e:
2675 self.showsyntaxerror()
2672 self.showsyntaxerror()
2676 if store_history:
2673 if store_history:
2677 self.execution_count += 1
2674 self.execution_count += 1
2678 return error_before_exec(e)
2675 return error_before_exec(e)
2679
2676
2680 # Apply AST transformations
2677 # Apply AST transformations
2681 try:
2678 try:
2682 code_ast = self.transform_ast(code_ast)
2679 code_ast = self.transform_ast(code_ast)
2683 except InputRejected as e:
2680 except InputRejected as e:
2684 self.showtraceback()
2681 self.showtraceback()
2685 if store_history:
2682 if store_history:
2686 self.execution_count += 1
2683 self.execution_count += 1
2687 return error_before_exec(e)
2684 return error_before_exec(e)
2688
2685
2689 # Give the displayhook a reference to our ExecutionResult so it
2686 # Give the displayhook a reference to our ExecutionResult so it
2690 # can fill in the output value.
2687 # can fill in the output value.
2691 self.displayhook.exec_result = result
2688 self.displayhook.exec_result = result
2692
2689
2693 # Execute the user code
2690 # Execute the user code
2694 interactivity = "none" if silent else self.ast_node_interactivity
2691 interactivity = "none" if silent else self.ast_node_interactivity
2695 has_raised = self.run_ast_nodes(code_ast.body, cell_name,
2692 has_raised = self.run_ast_nodes(code_ast.body, cell_name,
2696 interactivity=interactivity, compiler=compiler, result=result)
2693 interactivity=interactivity, compiler=compiler, result=result)
2697
2694
2698 self.last_execution_succeeded = not has_raised
2695 self.last_execution_succeeded = not has_raised
2699
2696
2700 # Reset this so later displayed values do not modify the
2697 # Reset this so later displayed values do not modify the
2701 # ExecutionResult
2698 # ExecutionResult
2702 self.displayhook.exec_result = None
2699 self.displayhook.exec_result = None
2703
2700
2704 self.events.trigger('post_execute')
2701 self.events.trigger('post_execute')
2705 if not silent:
2702 if not silent:
2706 self.events.trigger('post_run_cell')
2703 self.events.trigger('post_run_cell')
2707
2704
2708 if store_history:
2705 if store_history:
2709 # Write output to the database. Does nothing unless
2706 # Write output to the database. Does nothing unless
2710 # history output logging is enabled.
2707 # history output logging is enabled.
2711 self.history_manager.store_output(self.execution_count)
2708 self.history_manager.store_output(self.execution_count)
2712 # Each cell is a *single* input, regardless of how many lines it has
2709 # Each cell is a *single* input, regardless of how many lines it has
2713 self.execution_count += 1
2710 self.execution_count += 1
2714
2711
2715 return result
2712 return result
2716
2713
2717 def transform_ast(self, node):
2714 def transform_ast(self, node):
2718 """Apply the AST transformations from self.ast_transformers
2715 """Apply the AST transformations from self.ast_transformers
2719
2716
2720 Parameters
2717 Parameters
2721 ----------
2718 ----------
2722 node : ast.Node
2719 node : ast.Node
2723 The root node to be transformed. Typically called with the ast.Module
2720 The root node to be transformed. Typically called with the ast.Module
2724 produced by parsing user input.
2721 produced by parsing user input.
2725
2722
2726 Returns
2723 Returns
2727 -------
2724 -------
2728 An ast.Node corresponding to the node it was called with. Note that it
2725 An ast.Node corresponding to the node it was called with. Note that it
2729 may also modify the passed object, so don't rely on references to the
2726 may also modify the passed object, so don't rely on references to the
2730 original AST.
2727 original AST.
2731 """
2728 """
2732 for transformer in self.ast_transformers:
2729 for transformer in self.ast_transformers:
2733 try:
2730 try:
2734 node = transformer.visit(node)
2731 node = transformer.visit(node)
2735 except InputRejected:
2732 except InputRejected:
2736 # User-supplied AST transformers can reject an input by raising
2733 # User-supplied AST transformers can reject an input by raising
2737 # an InputRejected. Short-circuit in this case so that we
2734 # an InputRejected. Short-circuit in this case so that we
2738 # don't unregister the transform.
2735 # don't unregister the transform.
2739 raise
2736 raise
2740 except Exception:
2737 except Exception:
2741 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2738 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2742 self.ast_transformers.remove(transformer)
2739 self.ast_transformers.remove(transformer)
2743
2740
2744 if self.ast_transformers:
2741 if self.ast_transformers:
2745 ast.fix_missing_locations(node)
2742 ast.fix_missing_locations(node)
2746 return node
2743 return node
2747
2744
2748
2745
2749 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2746 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2750 compiler=compile, result=None):
2747 compiler=compile, result=None):
2751 """Run a sequence of AST nodes. The execution mode depends on the
2748 """Run a sequence of AST nodes. The execution mode depends on the
2752 interactivity parameter.
2749 interactivity parameter.
2753
2750
2754 Parameters
2751 Parameters
2755 ----------
2752 ----------
2756 nodelist : list
2753 nodelist : list
2757 A sequence of AST nodes to run.
2754 A sequence of AST nodes to run.
2758 cell_name : str
2755 cell_name : str
2759 Will be passed to the compiler as the filename of the cell. Typically
2756 Will be passed to the compiler as the filename of the cell. Typically
2760 the value returned by ip.compile.cache(cell).
2757 the value returned by ip.compile.cache(cell).
2761 interactivity : str
2758 interactivity : str
2762 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2759 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2763 run interactively (displaying output from expressions). 'last_expr'
2760 run interactively (displaying output from expressions). 'last_expr'
2764 will run the last node interactively only if it is an expression (i.e.
2761 will run the last node interactively only if it is an expression (i.e.
2765 expressions in loops or other blocks are not displayed. Other values
2762 expressions in loops or other blocks are not displayed. Other values
2766 for this parameter will raise a ValueError.
2763 for this parameter will raise a ValueError.
2767 compiler : callable
2764 compiler : callable
2768 A function with the same interface as the built-in compile(), to turn
2765 A function with the same interface as the built-in compile(), to turn
2769 the AST nodes into code objects. Default is the built-in compile().
2766 the AST nodes into code objects. Default is the built-in compile().
2770 result : ExecutionResult, optional
2767 result : ExecutionResult, optional
2771 An object to store exceptions that occur during execution.
2768 An object to store exceptions that occur during execution.
2772
2769
2773 Returns
2770 Returns
2774 -------
2771 -------
2775 True if an exception occurred while running code, False if it finished
2772 True if an exception occurred while running code, False if it finished
2776 running.
2773 running.
2777 """
2774 """
2778 if not nodelist:
2775 if not nodelist:
2779 return
2776 return
2780
2777
2781 if interactivity == 'last_expr':
2778 if interactivity == 'last_expr':
2782 if isinstance(nodelist[-1], ast.Expr):
2779 if isinstance(nodelist[-1], ast.Expr):
2783 interactivity = "last"
2780 interactivity = "last"
2784 else:
2781 else:
2785 interactivity = "none"
2782 interactivity = "none"
2786
2783
2787 if interactivity == 'none':
2784 if interactivity == 'none':
2788 to_run_exec, to_run_interactive = nodelist, []
2785 to_run_exec, to_run_interactive = nodelist, []
2789 elif interactivity == 'last':
2786 elif interactivity == 'last':
2790 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2787 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2791 elif interactivity == 'all':
2788 elif interactivity == 'all':
2792 to_run_exec, to_run_interactive = [], nodelist
2789 to_run_exec, to_run_interactive = [], nodelist
2793 else:
2790 else:
2794 raise ValueError("Interactivity was %r" % interactivity)
2791 raise ValueError("Interactivity was %r" % interactivity)
2795
2792
2796 try:
2793 try:
2797 for i, node in enumerate(to_run_exec):
2794 for i, node in enumerate(to_run_exec):
2798 mod = ast.Module([node])
2795 mod = ast.Module([node])
2799 code = compiler(mod, cell_name, "exec")
2796 code = compiler(mod, cell_name, "exec")
2800 if self.run_code(code, result):
2797 if self.run_code(code, result):
2801 return True
2798 return True
2802
2799
2803 for i, node in enumerate(to_run_interactive):
2800 for i, node in enumerate(to_run_interactive):
2804 mod = ast.Interactive([node])
2801 mod = ast.Interactive([node])
2805 code = compiler(mod, cell_name, "single")
2802 code = compiler(mod, cell_name, "single")
2806 if self.run_code(code, result):
2803 if self.run_code(code, result):
2807 return True
2804 return True
2808
2805
2809 # Flush softspace
2806 # Flush softspace
2810 if softspace(sys.stdout, 0):
2807 if softspace(sys.stdout, 0):
2811 print()
2808 print()
2812
2809
2813 except:
2810 except:
2814 # It's possible to have exceptions raised here, typically by
2811 # It's possible to have exceptions raised here, typically by
2815 # compilation of odd code (such as a naked 'return' outside a
2812 # compilation of odd code (such as a naked 'return' outside a
2816 # function) that did parse but isn't valid. Typically the exception
2813 # function) that did parse but isn't valid. Typically the exception
2817 # is a SyntaxError, but it's safest just to catch anything and show
2814 # is a SyntaxError, but it's safest just to catch anything and show
2818 # the user a traceback.
2815 # the user a traceback.
2819
2816
2820 # We do only one try/except outside the loop to minimize the impact
2817 # We do only one try/except outside the loop to minimize the impact
2821 # on runtime, and also because if any node in the node list is
2818 # on runtime, and also because if any node in the node list is
2822 # broken, we should stop execution completely.
2819 # broken, we should stop execution completely.
2823 if result:
2820 if result:
2824 result.error_before_exec = sys.exc_info()[1]
2821 result.error_before_exec = sys.exc_info()[1]
2825 self.showtraceback()
2822 self.showtraceback()
2826 return True
2823 return True
2827
2824
2828 return False
2825 return False
2829
2826
2830 def run_code(self, code_obj, result=None):
2827 def run_code(self, code_obj, result=None):
2831 """Execute a code object.
2828 """Execute a code object.
2832
2829
2833 When an exception occurs, self.showtraceback() is called to display a
2830 When an exception occurs, self.showtraceback() is called to display a
2834 traceback.
2831 traceback.
2835
2832
2836 Parameters
2833 Parameters
2837 ----------
2834 ----------
2838 code_obj : code object
2835 code_obj : code object
2839 A compiled code object, to be executed
2836 A compiled code object, to be executed
2840 result : ExecutionResult, optional
2837 result : ExecutionResult, optional
2841 An object to store exceptions that occur during execution.
2838 An object to store exceptions that occur during execution.
2842
2839
2843 Returns
2840 Returns
2844 -------
2841 -------
2845 False : successful execution.
2842 False : successful execution.
2846 True : an error occurred.
2843 True : an error occurred.
2847 """
2844 """
2848 # Set our own excepthook in case the user code tries to call it
2845 # Set our own excepthook in case the user code tries to call it
2849 # directly, so that the IPython crash handler doesn't get triggered
2846 # directly, so that the IPython crash handler doesn't get triggered
2850 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2847 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2851
2848
2852 # we save the original sys.excepthook in the instance, in case config
2849 # we save the original sys.excepthook in the instance, in case config
2853 # code (such as magics) needs access to it.
2850 # code (such as magics) needs access to it.
2854 self.sys_excepthook = old_excepthook
2851 self.sys_excepthook = old_excepthook
2855 outflag = 1 # happens in more places, so it's easier as default
2852 outflag = 1 # happens in more places, so it's easier as default
2856 try:
2853 try:
2857 try:
2854 try:
2858 self.hooks.pre_run_code_hook()
2855 self.hooks.pre_run_code_hook()
2859 #rprint('Running code', repr(code_obj)) # dbg
2856 #rprint('Running code', repr(code_obj)) # dbg
2860 exec(code_obj, self.user_global_ns, self.user_ns)
2857 exec(code_obj, self.user_global_ns, self.user_ns)
2861 finally:
2858 finally:
2862 # Reset our crash handler in place
2859 # Reset our crash handler in place
2863 sys.excepthook = old_excepthook
2860 sys.excepthook = old_excepthook
2864 except SystemExit as e:
2861 except SystemExit as e:
2865 if result is not None:
2862 if result is not None:
2866 result.error_in_exec = e
2863 result.error_in_exec = e
2867 self.showtraceback(exception_only=True)
2864 self.showtraceback(exception_only=True)
2868 warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
2865 warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
2869 except self.custom_exceptions:
2866 except self.custom_exceptions:
2870 etype, value, tb = sys.exc_info()
2867 etype, value, tb = sys.exc_info()
2871 if result is not None:
2868 if result is not None:
2872 result.error_in_exec = value
2869 result.error_in_exec = value
2873 self.CustomTB(etype, value, tb)
2870 self.CustomTB(etype, value, tb)
2874 except:
2871 except:
2875 if result is not None:
2872 if result is not None:
2876 result.error_in_exec = sys.exc_info()[1]
2873 result.error_in_exec = sys.exc_info()[1]
2877 self.showtraceback()
2874 self.showtraceback()
2878 else:
2875 else:
2879 outflag = 0
2876 outflag = 0
2880 return outflag
2877 return outflag
2881
2878
2882 # For backwards compatibility
2879 # For backwards compatibility
2883 runcode = run_code
2880 runcode = run_code
2884
2881
2885 #-------------------------------------------------------------------------
2882 #-------------------------------------------------------------------------
2886 # Things related to GUI support and pylab
2883 # Things related to GUI support and pylab
2887 #-------------------------------------------------------------------------
2884 #-------------------------------------------------------------------------
2888
2885
2889 active_eventloop = None
2886 active_eventloop = None
2890
2887
2891 def enable_gui(self, gui=None):
2888 def enable_gui(self, gui=None):
2892 raise NotImplementedError('Implement enable_gui in a subclass')
2889 raise NotImplementedError('Implement enable_gui in a subclass')
2893
2890
2894 def enable_matplotlib(self, gui=None):
2891 def enable_matplotlib(self, gui=None):
2895 """Enable interactive matplotlib and inline figure support.
2892 """Enable interactive matplotlib and inline figure support.
2896
2893
2897 This takes the following steps:
2894 This takes the following steps:
2898
2895
2899 1. select the appropriate eventloop and matplotlib backend
2896 1. select the appropriate eventloop and matplotlib backend
2900 2. set up matplotlib for interactive use with that backend
2897 2. set up matplotlib for interactive use with that backend
2901 3. configure formatters for inline figure display
2898 3. configure formatters for inline figure display
2902 4. enable the selected gui eventloop
2899 4. enable the selected gui eventloop
2903
2900
2904 Parameters
2901 Parameters
2905 ----------
2902 ----------
2906 gui : optional, string
2903 gui : optional, string
2907 If given, dictates the choice of matplotlib GUI backend to use
2904 If given, dictates the choice of matplotlib GUI backend to use
2908 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2905 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2909 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2906 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2910 matplotlib (as dictated by the matplotlib build-time options plus the
2907 matplotlib (as dictated by the matplotlib build-time options plus the
2911 user's matplotlibrc configuration file). Note that not all backends
2908 user's matplotlibrc configuration file). Note that not all backends
2912 make sense in all contexts, for example a terminal ipython can't
2909 make sense in all contexts, for example a terminal ipython can't
2913 display figures inline.
2910 display figures inline.
2914 """
2911 """
2915 from IPython.core import pylabtools as pt
2912 from IPython.core import pylabtools as pt
2916 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2913 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2917
2914
2918 if gui != 'inline':
2915 if gui != 'inline':
2919 # If we have our first gui selection, store it
2916 # If we have our first gui selection, store it
2920 if self.pylab_gui_select is None:
2917 if self.pylab_gui_select is None:
2921 self.pylab_gui_select = gui
2918 self.pylab_gui_select = gui
2922 # Otherwise if they are different
2919 # Otherwise if they are different
2923 elif gui != self.pylab_gui_select:
2920 elif gui != self.pylab_gui_select:
2924 print ('Warning: Cannot change to a different GUI toolkit: %s.'
2921 print ('Warning: Cannot change to a different GUI toolkit: %s.'
2925 ' Using %s instead.' % (gui, self.pylab_gui_select))
2922 ' Using %s instead.' % (gui, self.pylab_gui_select))
2926 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2923 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2927
2924
2928 pt.activate_matplotlib(backend)
2925 pt.activate_matplotlib(backend)
2929 pt.configure_inline_support(self, backend)
2926 pt.configure_inline_support(self, backend)
2930
2927
2931 # Now we must activate the gui pylab wants to use, and fix %run to take
2928 # Now we must activate the gui pylab wants to use, and fix %run to take
2932 # plot updates into account
2929 # plot updates into account
2933 self.enable_gui(gui)
2930 self.enable_gui(gui)
2934 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2931 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2935 pt.mpl_runner(self.safe_execfile)
2932 pt.mpl_runner(self.safe_execfile)
2936
2933
2937 return gui, backend
2934 return gui, backend
2938
2935
2939 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2936 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2940 """Activate pylab support at runtime.
2937 """Activate pylab support at runtime.
2941
2938
2942 This turns on support for matplotlib, preloads into the interactive
2939 This turns on support for matplotlib, preloads into the interactive
2943 namespace all of numpy and pylab, and configures IPython to correctly
2940 namespace all of numpy and pylab, and configures IPython to correctly
2944 interact with the GUI event loop. The GUI backend to be used can be
2941 interact with the GUI event loop. The GUI backend to be used can be
2945 optionally selected with the optional ``gui`` argument.
2942 optionally selected with the optional ``gui`` argument.
2946
2943
2947 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
2944 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
2948
2945
2949 Parameters
2946 Parameters
2950 ----------
2947 ----------
2951 gui : optional, string
2948 gui : optional, string
2952 If given, dictates the choice of matplotlib GUI backend to use
2949 If given, dictates the choice of matplotlib GUI backend to use
2953 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2950 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2954 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2951 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2955 matplotlib (as dictated by the matplotlib build-time options plus the
2952 matplotlib (as dictated by the matplotlib build-time options plus the
2956 user's matplotlibrc configuration file). Note that not all backends
2953 user's matplotlibrc configuration file). Note that not all backends
2957 make sense in all contexts, for example a terminal ipython can't
2954 make sense in all contexts, for example a terminal ipython can't
2958 display figures inline.
2955 display figures inline.
2959 import_all : optional, bool, default: True
2956 import_all : optional, bool, default: True
2960 Whether to do `from numpy import *` and `from pylab import *`
2957 Whether to do `from numpy import *` and `from pylab import *`
2961 in addition to module imports.
2958 in addition to module imports.
2962 welcome_message : deprecated
2959 welcome_message : deprecated
2963 This argument is ignored, no welcome message will be displayed.
2960 This argument is ignored, no welcome message will be displayed.
2964 """
2961 """
2965 from IPython.core.pylabtools import import_pylab
2962 from IPython.core.pylabtools import import_pylab
2966
2963
2967 gui, backend = self.enable_matplotlib(gui)
2964 gui, backend = self.enable_matplotlib(gui)
2968
2965
2969 # We want to prevent the loading of pylab to pollute the user's
2966 # We want to prevent the loading of pylab to pollute the user's
2970 # namespace as shown by the %who* magics, so we execute the activation
2967 # namespace as shown by the %who* magics, so we execute the activation
2971 # code in an empty namespace, and we update *both* user_ns and
2968 # code in an empty namespace, and we update *both* user_ns and
2972 # user_ns_hidden with this information.
2969 # user_ns_hidden with this information.
2973 ns = {}
2970 ns = {}
2974 import_pylab(ns, import_all)
2971 import_pylab(ns, import_all)
2975 # warn about clobbered names
2972 # warn about clobbered names
2976 ignored = {"__builtins__"}
2973 ignored = {"__builtins__"}
2977 both = set(ns).intersection(self.user_ns).difference(ignored)
2974 both = set(ns).intersection(self.user_ns).difference(ignored)
2978 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
2975 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
2979 self.user_ns.update(ns)
2976 self.user_ns.update(ns)
2980 self.user_ns_hidden.update(ns)
2977 self.user_ns_hidden.update(ns)
2981 return gui, backend, clobbered
2978 return gui, backend, clobbered
2982
2979
2983 #-------------------------------------------------------------------------
2980 #-------------------------------------------------------------------------
2984 # Utilities
2981 # Utilities
2985 #-------------------------------------------------------------------------
2982 #-------------------------------------------------------------------------
2986
2983
2987 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2984 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2988 """Expand python variables in a string.
2985 """Expand python variables in a string.
2989
2986
2990 The depth argument indicates how many frames above the caller should
2987 The depth argument indicates how many frames above the caller should
2991 be walked to look for the local namespace where to expand variables.
2988 be walked to look for the local namespace where to expand variables.
2992
2989
2993 The global namespace for expansion is always the user's interactive
2990 The global namespace for expansion is always the user's interactive
2994 namespace.
2991 namespace.
2995 """
2992 """
2996 ns = self.user_ns.copy()
2993 ns = self.user_ns.copy()
2997 try:
2994 try:
2998 frame = sys._getframe(depth+1)
2995 frame = sys._getframe(depth+1)
2999 except ValueError:
2996 except ValueError:
3000 # This is thrown if there aren't that many frames on the stack,
2997 # This is thrown if there aren't that many frames on the stack,
3001 # e.g. if a script called run_line_magic() directly.
2998 # e.g. if a script called run_line_magic() directly.
3002 pass
2999 pass
3003 else:
3000 else:
3004 ns.update(frame.f_locals)
3001 ns.update(frame.f_locals)
3005
3002
3006 try:
3003 try:
3007 # We have to use .vformat() here, because 'self' is a valid and common
3004 # We have to use .vformat() here, because 'self' is a valid and common
3008 # name, and expanding **ns for .format() would make it collide with
3005 # name, and expanding **ns for .format() would make it collide with
3009 # the 'self' argument of the method.
3006 # the 'self' argument of the method.
3010 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3007 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3011 except Exception:
3008 except Exception:
3012 # if formatter couldn't format, just let it go untransformed
3009 # if formatter couldn't format, just let it go untransformed
3013 pass
3010 pass
3014 return cmd
3011 return cmd
3015
3012
3016 def mktempfile(self, data=None, prefix='ipython_edit_'):
3013 def mktempfile(self, data=None, prefix='ipython_edit_'):
3017 """Make a new tempfile and return its filename.
3014 """Make a new tempfile and return its filename.
3018
3015
3019 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3016 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3020 but it registers the created filename internally so ipython cleans it up
3017 but it registers the created filename internally so ipython cleans it up
3021 at exit time.
3018 at exit time.
3022
3019
3023 Optional inputs:
3020 Optional inputs:
3024
3021
3025 - data(None): if data is given, it gets written out to the temp file
3022 - data(None): if data is given, it gets written out to the temp file
3026 immediately, and the file is closed again."""
3023 immediately, and the file is closed again."""
3027
3024
3028 dirname = tempfile.mkdtemp(prefix=prefix)
3025 dirname = tempfile.mkdtemp(prefix=prefix)
3029 self.tempdirs.append(dirname)
3026 self.tempdirs.append(dirname)
3030
3027
3031 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3028 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3032 os.close(handle) # On Windows, there can only be one open handle on a file
3029 os.close(handle) # On Windows, there can only be one open handle on a file
3033 self.tempfiles.append(filename)
3030 self.tempfiles.append(filename)
3034
3031
3035 if data:
3032 if data:
3036 tmp_file = open(filename,'w')
3033 tmp_file = open(filename,'w')
3037 tmp_file.write(data)
3034 tmp_file.write(data)
3038 tmp_file.close()
3035 tmp_file.close()
3039 return filename
3036 return filename
3040
3037
3041 @undoc
3038 @undoc
3042 def write(self,data):
3039 def write(self,data):
3043 """DEPRECATED: Write a string to the default output"""
3040 """DEPRECATED: Write a string to the default output"""
3044 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3041 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3045 DeprecationWarning, stacklevel=2)
3042 DeprecationWarning, stacklevel=2)
3046 sys.stdout.write(data)
3043 sys.stdout.write(data)
3047
3044
3048 @undoc
3045 @undoc
3049 def write_err(self,data):
3046 def write_err(self,data):
3050 """DEPRECATED: Write a string to the default error output"""
3047 """DEPRECATED: Write a string to the default error output"""
3051 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3048 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3052 DeprecationWarning, stacklevel=2)
3049 DeprecationWarning, stacklevel=2)
3053 sys.stderr.write(data)
3050 sys.stderr.write(data)
3054
3051
3055 def ask_yes_no(self, prompt, default=None, interrupt=None):
3052 def ask_yes_no(self, prompt, default=None, interrupt=None):
3056 if self.quiet:
3053 if self.quiet:
3057 return True
3054 return True
3058 return ask_yes_no(prompt,default,interrupt)
3055 return ask_yes_no(prompt,default,interrupt)
3059
3056
3060 def show_usage(self):
3057 def show_usage(self):
3061 """Show a usage message"""
3058 """Show a usage message"""
3062 page.page(IPython.core.usage.interactive_usage)
3059 page.page(IPython.core.usage.interactive_usage)
3063
3060
3064 def extract_input_lines(self, range_str, raw=False):
3061 def extract_input_lines(self, range_str, raw=False):
3065 """Return as a string a set of input history slices.
3062 """Return as a string a set of input history slices.
3066
3063
3067 Parameters
3064 Parameters
3068 ----------
3065 ----------
3069 range_str : string
3066 range_str : string
3070 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3067 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3071 since this function is for use by magic functions which get their
3068 since this function is for use by magic functions which get their
3072 arguments as strings. The number before the / is the session
3069 arguments as strings. The number before the / is the session
3073 number: ~n goes n back from the current session.
3070 number: ~n goes n back from the current session.
3074
3071
3075 raw : bool, optional
3072 raw : bool, optional
3076 By default, the processed input is used. If this is true, the raw
3073 By default, the processed input is used. If this is true, the raw
3077 input history is used instead.
3074 input history is used instead.
3078
3075
3079 Notes
3076 Notes
3080 -----
3077 -----
3081
3078
3082 Slices can be described with two notations:
3079 Slices can be described with two notations:
3083
3080
3084 * ``N:M`` -> standard python form, means including items N...(M-1).
3081 * ``N:M`` -> standard python form, means including items N...(M-1).
3085 * ``N-M`` -> include items N..M (closed endpoint).
3082 * ``N-M`` -> include items N..M (closed endpoint).
3086 """
3083 """
3087 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3084 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3088 return "\n".join(x for _, _, x in lines)
3085 return "\n".join(x for _, _, x in lines)
3089
3086
3090 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3087 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3091 """Get a code string from history, file, url, or a string or macro.
3088 """Get a code string from history, file, url, or a string or macro.
3092
3089
3093 This is mainly used by magic functions.
3090 This is mainly used by magic functions.
3094
3091
3095 Parameters
3092 Parameters
3096 ----------
3093 ----------
3097
3094
3098 target : str
3095 target : str
3099
3096
3100 A string specifying code to retrieve. This will be tried respectively
3097 A string specifying code to retrieve. This will be tried respectively
3101 as: ranges of input history (see %history for syntax), url,
3098 as: ranges of input history (see %history for syntax), url,
3102 corresponding .py file, filename, or an expression evaluating to a
3099 corresponding .py file, filename, or an expression evaluating to a
3103 string or Macro in the user namespace.
3100 string or Macro in the user namespace.
3104
3101
3105 raw : bool
3102 raw : bool
3106 If true (default), retrieve raw history. Has no effect on the other
3103 If true (default), retrieve raw history. Has no effect on the other
3107 retrieval mechanisms.
3104 retrieval mechanisms.
3108
3105
3109 py_only : bool (default False)
3106 py_only : bool (default False)
3110 Only try to fetch python code, do not try alternative methods to decode file
3107 Only try to fetch python code, do not try alternative methods to decode file
3111 if unicode fails.
3108 if unicode fails.
3112
3109
3113 Returns
3110 Returns
3114 -------
3111 -------
3115 A string of code.
3112 A string of code.
3116
3113
3117 ValueError is raised if nothing is found, and TypeError if it evaluates
3114 ValueError is raised if nothing is found, and TypeError if it evaluates
3118 to an object of another type. In each case, .args[0] is a printable
3115 to an object of another type. In each case, .args[0] is a printable
3119 message.
3116 message.
3120 """
3117 """
3121 code = self.extract_input_lines(target, raw=raw) # Grab history
3118 code = self.extract_input_lines(target, raw=raw) # Grab history
3122 if code:
3119 if code:
3123 return code
3120 return code
3124 try:
3121 try:
3125 if target.startswith(('http://', 'https://')):
3122 if target.startswith(('http://', 'https://')):
3126 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3123 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3127 except UnicodeDecodeError:
3124 except UnicodeDecodeError:
3128 if not py_only :
3125 if not py_only :
3129 # Deferred import
3126 # Deferred import
3130 try:
3127 try:
3131 from urllib.request import urlopen # Py3
3128 from urllib.request import urlopen # Py3
3132 except ImportError:
3129 except ImportError:
3133 from urllib import urlopen
3130 from urllib import urlopen
3134 response = urlopen(target)
3131 response = urlopen(target)
3135 return response.read().decode('latin1')
3132 return response.read().decode('latin1')
3136 raise ValueError(("'%s' seem to be unreadable.") % target)
3133 raise ValueError(("'%s' seem to be unreadable.") % target)
3137
3134
3138 potential_target = [target]
3135 potential_target = [target]
3139 try :
3136 try :
3140 potential_target.insert(0,get_py_filename(target))
3137 potential_target.insert(0,get_py_filename(target))
3141 except IOError:
3138 except IOError:
3142 pass
3139 pass
3143
3140
3144 for tgt in potential_target :
3141 for tgt in potential_target :
3145 if os.path.isfile(tgt): # Read file
3142 if os.path.isfile(tgt): # Read file
3146 try :
3143 try :
3147 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3144 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3148 except UnicodeDecodeError :
3145 except UnicodeDecodeError :
3149 if not py_only :
3146 if not py_only :
3150 with io_open(tgt,'r', encoding='latin1') as f :
3147 with io_open(tgt,'r', encoding='latin1') as f :
3151 return f.read()
3148 return f.read()
3152 raise ValueError(("'%s' seem to be unreadable.") % target)
3149 raise ValueError(("'%s' seem to be unreadable.") % target)
3153 elif os.path.isdir(os.path.expanduser(tgt)):
3150 elif os.path.isdir(os.path.expanduser(tgt)):
3154 raise ValueError("'%s' is a directory, not a regular file." % target)
3151 raise ValueError("'%s' is a directory, not a regular file." % target)
3155
3152
3156 if search_ns:
3153 if search_ns:
3157 # Inspect namespace to load object source
3154 # Inspect namespace to load object source
3158 object_info = self.object_inspect(target, detail_level=1)
3155 object_info = self.object_inspect(target, detail_level=1)
3159 if object_info['found'] and object_info['source']:
3156 if object_info['found'] and object_info['source']:
3160 return object_info['source']
3157 return object_info['source']
3161
3158
3162 try: # User namespace
3159 try: # User namespace
3163 codeobj = eval(target, self.user_ns)
3160 codeobj = eval(target, self.user_ns)
3164 except Exception:
3161 except Exception:
3165 raise ValueError(("'%s' was not found in history, as a file, url, "
3162 raise ValueError(("'%s' was not found in history, as a file, url, "
3166 "nor in the user namespace.") % target)
3163 "nor in the user namespace.") % target)
3167
3164
3168 if isinstance(codeobj, string_types):
3165 if isinstance(codeobj, str):
3169 return codeobj
3166 return codeobj
3170 elif isinstance(codeobj, Macro):
3167 elif isinstance(codeobj, Macro):
3171 return codeobj.value
3168 return codeobj.value
3172
3169
3173 raise TypeError("%s is neither a string nor a macro." % target,
3170 raise TypeError("%s is neither a string nor a macro." % target,
3174 codeobj)
3171 codeobj)
3175
3172
3176 #-------------------------------------------------------------------------
3173 #-------------------------------------------------------------------------
3177 # Things related to IPython exiting
3174 # Things related to IPython exiting
3178 #-------------------------------------------------------------------------
3175 #-------------------------------------------------------------------------
3179 def atexit_operations(self):
3176 def atexit_operations(self):
3180 """This will be executed at the time of exit.
3177 """This will be executed at the time of exit.
3181
3178
3182 Cleanup operations and saving of persistent data that is done
3179 Cleanup operations and saving of persistent data that is done
3183 unconditionally by IPython should be performed here.
3180 unconditionally by IPython should be performed here.
3184
3181
3185 For things that may depend on startup flags or platform specifics (such
3182 For things that may depend on startup flags or platform specifics (such
3186 as having readline or not), register a separate atexit function in the
3183 as having readline or not), register a separate atexit function in the
3187 code that has the appropriate information, rather than trying to
3184 code that has the appropriate information, rather than trying to
3188 clutter
3185 clutter
3189 """
3186 """
3190 # Close the history session (this stores the end time and line count)
3187 # Close the history session (this stores the end time and line count)
3191 # this must be *before* the tempfile cleanup, in case of temporary
3188 # this must be *before* the tempfile cleanup, in case of temporary
3192 # history db
3189 # history db
3193 self.history_manager.end_session()
3190 self.history_manager.end_session()
3194
3191
3195 # Cleanup all tempfiles and folders left around
3192 # Cleanup all tempfiles and folders left around
3196 for tfile in self.tempfiles:
3193 for tfile in self.tempfiles:
3197 try:
3194 try:
3198 os.unlink(tfile)
3195 os.unlink(tfile)
3199 except OSError:
3196 except OSError:
3200 pass
3197 pass
3201
3198
3202 for tdir in self.tempdirs:
3199 for tdir in self.tempdirs:
3203 try:
3200 try:
3204 os.rmdir(tdir)
3201 os.rmdir(tdir)
3205 except OSError:
3202 except OSError:
3206 pass
3203 pass
3207
3204
3208 # Clear all user namespaces to release all references cleanly.
3205 # Clear all user namespaces to release all references cleanly.
3209 self.reset(new_session=False)
3206 self.reset(new_session=False)
3210
3207
3211 # Run user hooks
3208 # Run user hooks
3212 self.hooks.shutdown_hook()
3209 self.hooks.shutdown_hook()
3213
3210
3214 def cleanup(self):
3211 def cleanup(self):
3215 self.restore_sys_module_state()
3212 self.restore_sys_module_state()
3216
3213
3217
3214
3218 # Overridden in terminal subclass to change prompts
3215 # Overridden in terminal subclass to change prompts
3219 def switch_doctest_mode(self, mode):
3216 def switch_doctest_mode(self, mode):
3220 pass
3217 pass
3221
3218
3222
3219
3223 class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
3220 class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
3224 """An abstract base class for InteractiveShell."""
3221 """An abstract base class for InteractiveShell."""
3225
3222
3226 InteractiveShellABC.register(InteractiveShell)
3223 InteractiveShellABC.register(InteractiveShell)
@@ -1,220 +1,218 b''
1 """Logger class for IPython's logging facilities.
1 """Logger class for IPython's logging facilities.
2 """
2 """
3
3
4 #*****************************************************************************
4 #*****************************************************************************
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
6 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
6 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
7 #
7 #
8 # Distributed under the terms of the BSD License. The full license is in
8 # Distributed under the terms of the BSD License. The full license is in
9 # the file COPYING, distributed as part of this software.
9 # the file COPYING, distributed as part of this software.
10 #*****************************************************************************
10 #*****************************************************************************
11
11
12 #****************************************************************************
12 #****************************************************************************
13 # Modules and globals
13 # Modules and globals
14
14
15 # Python standard modules
15 # Python standard modules
16 import glob
16 import glob
17 import io
17 import io
18 import os
18 import os
19 import time
19 import time
20
20
21 from IPython.utils.py3compat import str_to_unicode
22
21
23 #****************************************************************************
22 #****************************************************************************
24 # FIXME: This class isn't a mixin anymore, but it still needs attributes from
23 # FIXME: This class isn't a mixin anymore, but it still needs attributes from
25 # ipython and does input cache management. Finish cleanup later...
24 # ipython and does input cache management. Finish cleanup later...
26
25
27 class Logger(object):
26 class Logger(object):
28 """A Logfile class with different policies for file creation"""
27 """A Logfile class with different policies for file creation"""
29
28
30 def __init__(self, home_dir, logfname='Logger.log', loghead=u'',
29 def __init__(self, home_dir, logfname='Logger.log', loghead=u'',
31 logmode='over'):
30 logmode='over'):
32
31
33 # this is the full ipython instance, we need some attributes from it
32 # this is the full ipython instance, we need some attributes from it
34 # which won't exist until later. What a mess, clean up later...
33 # which won't exist until later. What a mess, clean up later...
35 self.home_dir = home_dir
34 self.home_dir = home_dir
36
35
37 self.logfname = logfname
36 self.logfname = logfname
38 self.loghead = loghead
37 self.loghead = loghead
39 self.logmode = logmode
38 self.logmode = logmode
40 self.logfile = None
39 self.logfile = None
41
40
42 # Whether to log raw or processed input
41 # Whether to log raw or processed input
43 self.log_raw_input = False
42 self.log_raw_input = False
44
43
45 # whether to also log output
44 # whether to also log output
46 self.log_output = False
45 self.log_output = False
47
46
48 # whether to put timestamps before each log entry
47 # whether to put timestamps before each log entry
49 self.timestamp = False
48 self.timestamp = False
50
49
51 # activity control flags
50 # activity control flags
52 self.log_active = False
51 self.log_active = False
53
52
54 # logmode is a validated property
53 # logmode is a validated property
55 def _set_mode(self,mode):
54 def _set_mode(self,mode):
56 if mode not in ['append','backup','global','over','rotate']:
55 if mode not in ['append','backup','global','over','rotate']:
57 raise ValueError('invalid log mode %s given' % mode)
56 raise ValueError('invalid log mode %s given' % mode)
58 self._logmode = mode
57 self._logmode = mode
59
58
60 def _get_mode(self):
59 def _get_mode(self):
61 return self._logmode
60 return self._logmode
62
61
63 logmode = property(_get_mode,_set_mode)
62 logmode = property(_get_mode,_set_mode)
64
63
65 def logstart(self, logfname=None, loghead=None, logmode=None,
64 def logstart(self, logfname=None, loghead=None, logmode=None,
66 log_output=False, timestamp=False, log_raw_input=False):
65 log_output=False, timestamp=False, log_raw_input=False):
67 """Generate a new log-file with a default header.
66 """Generate a new log-file with a default header.
68
67
69 Raises RuntimeError if the log has already been started"""
68 Raises RuntimeError if the log has already been started"""
70
69
71 if self.logfile is not None:
70 if self.logfile is not None:
72 raise RuntimeError('Log file is already active: %s' %
71 raise RuntimeError('Log file is already active: %s' %
73 self.logfname)
72 self.logfname)
74
73
75 # The parameters can override constructor defaults
74 # The parameters can override constructor defaults
76 if logfname is not None: self.logfname = logfname
75 if logfname is not None: self.logfname = logfname
77 if loghead is not None: self.loghead = loghead
76 if loghead is not None: self.loghead = loghead
78 if logmode is not None: self.logmode = logmode
77 if logmode is not None: self.logmode = logmode
79
78
80 # Parameters not part of the constructor
79 # Parameters not part of the constructor
81 self.timestamp = timestamp
80 self.timestamp = timestamp
82 self.log_output = log_output
81 self.log_output = log_output
83 self.log_raw_input = log_raw_input
82 self.log_raw_input = log_raw_input
84
83
85 # init depending on the log mode requested
84 # init depending on the log mode requested
86 isfile = os.path.isfile
85 isfile = os.path.isfile
87 logmode = self.logmode
86 logmode = self.logmode
88
87
89 if logmode == 'append':
88 if logmode == 'append':
90 self.logfile = io.open(self.logfname, 'a', encoding='utf-8')
89 self.logfile = io.open(self.logfname, 'a', encoding='utf-8')
91
90
92 elif logmode == 'backup':
91 elif logmode == 'backup':
93 if isfile(self.logfname):
92 if isfile(self.logfname):
94 backup_logname = self.logfname+'~'
93 backup_logname = self.logfname+'~'
95 # Manually remove any old backup, since os.rename may fail
94 # Manually remove any old backup, since os.rename may fail
96 # under Windows.
95 # under Windows.
97 if isfile(backup_logname):
96 if isfile(backup_logname):
98 os.remove(backup_logname)
97 os.remove(backup_logname)
99 os.rename(self.logfname,backup_logname)
98 os.rename(self.logfname,backup_logname)
100 self.logfile = io.open(self.logfname, 'w', encoding='utf-8')
99 self.logfile = io.open(self.logfname, 'w', encoding='utf-8')
101
100
102 elif logmode == 'global':
101 elif logmode == 'global':
103 self.logfname = os.path.join(self.home_dir,self.logfname)
102 self.logfname = os.path.join(self.home_dir,self.logfname)
104 self.logfile = io.open(self.logfname, 'a', encoding='utf-8')
103 self.logfile = io.open(self.logfname, 'a', encoding='utf-8')
105
104
106 elif logmode == 'over':
105 elif logmode == 'over':
107 if isfile(self.logfname):
106 if isfile(self.logfname):
108 os.remove(self.logfname)
107 os.remove(self.logfname)
109 self.logfile = io.open(self.logfname,'w', encoding='utf-8')
108 self.logfile = io.open(self.logfname,'w', encoding='utf-8')
110
109
111 elif logmode == 'rotate':
110 elif logmode == 'rotate':
112 if isfile(self.logfname):
111 if isfile(self.logfname):
113 if isfile(self.logfname+'.001~'):
112 if isfile(self.logfname+'.001~'):
114 old = glob.glob(self.logfname+'.*~')
113 old = glob.glob(self.logfname+'.*~')
115 old.sort()
114 old.sort()
116 old.reverse()
115 old.reverse()
117 for f in old:
116 for f in old:
118 root, ext = os.path.splitext(f)
117 root, ext = os.path.splitext(f)
119 num = int(ext[1:-1])+1
118 num = int(ext[1:-1])+1
120 os.rename(f, root+'.'+repr(num).zfill(3)+'~')
119 os.rename(f, root+'.'+repr(num).zfill(3)+'~')
121 os.rename(self.logfname, self.logfname+'.001~')
120 os.rename(self.logfname, self.logfname+'.001~')
122 self.logfile = io.open(self.logfname, 'w', encoding='utf-8')
121 self.logfile = io.open(self.logfname, 'w', encoding='utf-8')
123
122
124 if logmode != 'append':
123 if logmode != 'append':
125 self.logfile.write(self.loghead)
124 self.logfile.write(self.loghead)
126
125
127 self.logfile.flush()
126 self.logfile.flush()
128 self.log_active = True
127 self.log_active = True
129
128
130 def switch_log(self,val):
129 def switch_log(self,val):
131 """Switch logging on/off. val should be ONLY a boolean."""
130 """Switch logging on/off. val should be ONLY a boolean."""
132
131
133 if val not in [False,True,0,1]:
132 if val not in [False,True,0,1]:
134 raise ValueError('Call switch_log ONLY with a boolean argument, '
133 raise ValueError('Call switch_log ONLY with a boolean argument, '
135 'not with: %s' % val)
134 'not with: %s' % val)
136
135
137 label = {0:'OFF',1:'ON',False:'OFF',True:'ON'}
136 label = {0:'OFF',1:'ON',False:'OFF',True:'ON'}
138
137
139 if self.logfile is None:
138 if self.logfile is None:
140 print("""
139 print("""
141 Logging hasn't been started yet (use logstart for that).
140 Logging hasn't been started yet (use logstart for that).
142
141
143 %logon/%logoff are for temporarily starting and stopping logging for a logfile
142 %logon/%logoff are for temporarily starting and stopping logging for a logfile
144 which already exists. But you must first start the logging process with
143 which already exists. But you must first start the logging process with
145 %logstart (optionally giving a logfile name).""")
144 %logstart (optionally giving a logfile name).""")
146
145
147 else:
146 else:
148 if self.log_active == val:
147 if self.log_active == val:
149 print('Logging is already',label[val])
148 print('Logging is already',label[val])
150 else:
149 else:
151 print('Switching logging',label[val])
150 print('Switching logging',label[val])
152 self.log_active = not self.log_active
151 self.log_active = not self.log_active
153 self.log_active_out = self.log_active
152 self.log_active_out = self.log_active
154
153
155 def logstate(self):
154 def logstate(self):
156 """Print a status message about the logger."""
155 """Print a status message about the logger."""
157 if self.logfile is None:
156 if self.logfile is None:
158 print('Logging has not been activated.')
157 print('Logging has not been activated.')
159 else:
158 else:
160 state = self.log_active and 'active' or 'temporarily suspended'
159 state = self.log_active and 'active' or 'temporarily suspended'
161 print('Filename :', self.logfname)
160 print('Filename :', self.logfname)
162 print('Mode :', self.logmode)
161 print('Mode :', self.logmode)
163 print('Output logging :', self.log_output)
162 print('Output logging :', self.log_output)
164 print('Raw input log :', self.log_raw_input)
163 print('Raw input log :', self.log_raw_input)
165 print('Timestamping :', self.timestamp)
164 print('Timestamping :', self.timestamp)
166 print('State :', state)
165 print('State :', state)
167
166
168 def log(self, line_mod, line_ori):
167 def log(self, line_mod, line_ori):
169 """Write the sources to a log.
168 """Write the sources to a log.
170
169
171 Inputs:
170 Inputs:
172
171
173 - line_mod: possibly modified input, such as the transformations made
172 - line_mod: possibly modified input, such as the transformations made
174 by input prefilters or input handlers of various kinds. This should
173 by input prefilters or input handlers of various kinds. This should
175 always be valid Python.
174 always be valid Python.
176
175
177 - line_ori: unmodified input line from the user. This is not
176 - line_ori: unmodified input line from the user. This is not
178 necessarily valid Python.
177 necessarily valid Python.
179 """
178 """
180
179
181 # Write the log line, but decide which one according to the
180 # Write the log line, but decide which one according to the
182 # log_raw_input flag, set when the log is started.
181 # log_raw_input flag, set when the log is started.
183 if self.log_raw_input:
182 if self.log_raw_input:
184 self.log_write(line_ori)
183 self.log_write(line_ori)
185 else:
184 else:
186 self.log_write(line_mod)
185 self.log_write(line_mod)
187
186
188 def log_write(self, data, kind='input'):
187 def log_write(self, data, kind='input'):
189 """Write data to the log file, if active"""
188 """Write data to the log file, if active"""
190
189
191 #print 'data: %r' % data # dbg
190 #print 'data: %r' % data # dbg
192 if self.log_active and data:
191 if self.log_active and data:
193 write = self.logfile.write
192 write = self.logfile.write
194 if kind=='input':
193 if kind=='input':
195 if self.timestamp:
194 if self.timestamp:
196 write(str_to_unicode(time.strftime('# %a, %d %b %Y %H:%M:%S\n',
195 write(time.strftime('# %a, %d %b %Y %H:%M:%S\n', time.localtime()))
197 time.localtime())))
198 write(data)
196 write(data)
199 elif kind=='output' and self.log_output:
197 elif kind=='output' and self.log_output:
200 odata = u'\n'.join([u'#[Out]# %s' % s
198 odata = u'\n'.join([u'#[Out]# %s' % s
201 for s in data.splitlines()])
199 for s in data.splitlines()])
202 write(u'%s\n' % odata)
200 write(u'%s\n' % odata)
203 self.logfile.flush()
201 self.logfile.flush()
204
202
205 def logstop(self):
203 def logstop(self):
206 """Fully stop logging and close log file.
204 """Fully stop logging and close log file.
207
205
208 In order to start logging again, a new logstart() call needs to be
206 In order to start logging again, a new logstart() call needs to be
209 made, possibly (though not necessarily) with a new filename, mode and
207 made, possibly (though not necessarily) with a new filename, mode and
210 other options."""
208 other options."""
211
209
212 if self.logfile is not None:
210 if self.logfile is not None:
213 self.logfile.close()
211 self.logfile.close()
214 self.logfile = None
212 self.logfile = None
215 else:
213 else:
216 print("Logging hadn't been started.")
214 print("Logging hadn't been started.")
217 self.log_active = False
215 self.log_active = False
218
216
219 # For backwards compatibility, in case anyone was using this.
217 # For backwards compatibility, in case anyone was using this.
220 close_log = logstop
218 close_log = logstop
@@ -1,57 +1,57 b''
1 """Support for interactive macros in IPython"""
1 """Support for interactive macros in IPython"""
2
2
3 #*****************************************************************************
3 #*****************************************************************************
4 # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
4 # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
5 #
5 #
6 # Distributed under the terms of the BSD License. The full license is in
6 # Distributed under the terms of the BSD License. The full license is in
7 # the file COPYING, distributed as part of this software.
7 # the file COPYING, distributed as part of this software.
8 #*****************************************************************************
8 #*****************************************************************************
9
9
10 import re
10 import re
11
11
12 from IPython.utils import py3compat
12 from IPython.utils import py3compat
13 from IPython.utils.encoding import DEFAULT_ENCODING
13 from IPython.utils.encoding import DEFAULT_ENCODING
14
14
15 coding_declaration = re.compile(r"#\s*coding[:=]\s*([-\w.]+)")
15 coding_declaration = re.compile(r"#\s*coding[:=]\s*([-\w.]+)")
16
16
17 class Macro(object):
17 class Macro(object):
18 """Simple class to store the value of macros as strings.
18 """Simple class to store the value of macros as strings.
19
19
20 Macro is just a callable that executes a string of IPython
20 Macro is just a callable that executes a string of IPython
21 input when called.
21 input when called.
22 """
22 """
23
23
24 def __init__(self,code):
24 def __init__(self,code):
25 """store the macro value, as a single string which can be executed"""
25 """store the macro value, as a single string which can be executed"""
26 lines = []
26 lines = []
27 enc = None
27 enc = None
28 for line in code.splitlines():
28 for line in code.splitlines():
29 coding_match = coding_declaration.match(line)
29 coding_match = coding_declaration.match(line)
30 if coding_match:
30 if coding_match:
31 enc = coding_match.group(1)
31 enc = coding_match.group(1)
32 else:
32 else:
33 lines.append(line)
33 lines.append(line)
34 code = "\n".join(lines)
34 code = "\n".join(lines)
35 if isinstance(code, bytes):
35 if isinstance(code, bytes):
36 code = code.decode(enc or DEFAULT_ENCODING)
36 code = code.decode(enc or DEFAULT_ENCODING)
37 self.value = code + '\n'
37 self.value = code + '\n'
38
38
39 def __str__(self):
39 def __str__(self):
40 return py3compat.unicode_to_str(self.value)
40 return self.value
41
41
42 def __unicode__(self):
42 def __unicode__(self):
43 return self.value
43 return self.value
44
44
45 def __repr__(self):
45 def __repr__(self):
46 return 'IPython.macro.Macro(%s)' % repr(self.value)
46 return 'IPython.macro.Macro(%s)' % repr(self.value)
47
47
48 def __getstate__(self):
48 def __getstate__(self):
49 """ needed for safe pickling via %store """
49 """ needed for safe pickling via %store """
50 return {'value': self.value}
50 return {'value': self.value}
51
51
52 def __add__(self, other):
52 def __add__(self, other):
53 if isinstance(other, Macro):
53 if isinstance(other, Macro):
54 return Macro(self.value + other.value)
54 return Macro(self.value + other.value)
55 elif isinstance(other, py3compat.string_types):
55 elif isinstance(other, str):
56 return Macro(self.value + other)
56 return Macro(self.value + other)
57 raise TypeError
57 raise TypeError
@@ -1,679 +1,678 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3 """
3 """
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2008 The IPython Development Team
8 # Copyright (C) 2008 The IPython Development Team
9
9
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 import os
14 import os
15 import re
15 import re
16 import sys
16 import sys
17 import types
17 import types
18 from getopt import getopt, GetoptError
18 from getopt import getopt, GetoptError
19
19
20 from traitlets.config.configurable import Configurable
20 from traitlets.config.configurable import Configurable
21 from IPython.core import oinspect
21 from IPython.core import oinspect
22 from IPython.core.error import UsageError
22 from IPython.core.error import UsageError
23 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
23 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
24 from decorator import decorator
24 from decorator import decorator
25 from IPython.utils.ipstruct import Struct
25 from IPython.utils.ipstruct import Struct
26 from IPython.utils.process import arg_split
26 from IPython.utils.process import arg_split
27 from IPython.utils.py3compat import string_types, iteritems
28 from IPython.utils.text import dedent
27 from IPython.utils.text import dedent
29 from traitlets import Bool, Dict, Instance, observe
28 from traitlets import Bool, Dict, Instance, observe
30 from logging import error
29 from logging import error
31
30
32 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
33 # Globals
32 # Globals
34 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
35
34
36 # A dict we'll use for each class that has magics, used as temporary storage to
35 # A dict we'll use for each class that has magics, used as temporary storage to
37 # pass information between the @line/cell_magic method decorators and the
36 # pass information between the @line/cell_magic method decorators and the
38 # @magics_class class decorator, because the method decorators have no
37 # @magics_class class decorator, because the method decorators have no
39 # access to the class when they run. See for more details:
38 # access to the class when they run. See for more details:
40 # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class
39 # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class
41
40
42 magics = dict(line={}, cell={})
41 magics = dict(line={}, cell={})
43
42
44 magic_kinds = ('line', 'cell')
43 magic_kinds = ('line', 'cell')
45 magic_spec = ('line', 'cell', 'line_cell')
44 magic_spec = ('line', 'cell', 'line_cell')
46 magic_escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC2)
45 magic_escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC2)
47
46
48 #-----------------------------------------------------------------------------
47 #-----------------------------------------------------------------------------
49 # Utility classes and functions
48 # Utility classes and functions
50 #-----------------------------------------------------------------------------
49 #-----------------------------------------------------------------------------
51
50
52 class Bunch: pass
51 class Bunch: pass
53
52
54
53
55 def on_off(tag):
54 def on_off(tag):
56 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
55 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
57 return ['OFF','ON'][tag]
56 return ['OFF','ON'][tag]
58
57
59
58
60 def compress_dhist(dh):
59 def compress_dhist(dh):
61 """Compress a directory history into a new one with at most 20 entries.
60 """Compress a directory history into a new one with at most 20 entries.
62
61
63 Return a new list made from the first and last 10 elements of dhist after
62 Return a new list made from the first and last 10 elements of dhist after
64 removal of duplicates.
63 removal of duplicates.
65 """
64 """
66 head, tail = dh[:-10], dh[-10:]
65 head, tail = dh[:-10], dh[-10:]
67
66
68 newhead = []
67 newhead = []
69 done = set()
68 done = set()
70 for h in head:
69 for h in head:
71 if h in done:
70 if h in done:
72 continue
71 continue
73 newhead.append(h)
72 newhead.append(h)
74 done.add(h)
73 done.add(h)
75
74
76 return newhead + tail
75 return newhead + tail
77
76
78
77
79 def needs_local_scope(func):
78 def needs_local_scope(func):
80 """Decorator to mark magic functions which need to local scope to run."""
79 """Decorator to mark magic functions which need to local scope to run."""
81 func.needs_local_scope = True
80 func.needs_local_scope = True
82 return func
81 return func
83
82
84 #-----------------------------------------------------------------------------
83 #-----------------------------------------------------------------------------
85 # Class and method decorators for registering magics
84 # Class and method decorators for registering magics
86 #-----------------------------------------------------------------------------
85 #-----------------------------------------------------------------------------
87
86
88 def magics_class(cls):
87 def magics_class(cls):
89 """Class decorator for all subclasses of the main Magics class.
88 """Class decorator for all subclasses of the main Magics class.
90
89
91 Any class that subclasses Magics *must* also apply this decorator, to
90 Any class that subclasses Magics *must* also apply this decorator, to
92 ensure that all the methods that have been decorated as line/cell magics
91 ensure that all the methods that have been decorated as line/cell magics
93 get correctly registered in the class instance. This is necessary because
92 get correctly registered in the class instance. This is necessary because
94 when method decorators run, the class does not exist yet, so they
93 when method decorators run, the class does not exist yet, so they
95 temporarily store their information into a module global. Application of
94 temporarily store their information into a module global. Application of
96 this class decorator copies that global data to the class instance and
95 this class decorator copies that global data to the class instance and
97 clears the global.
96 clears the global.
98
97
99 Obviously, this mechanism is not thread-safe, which means that the
98 Obviously, this mechanism is not thread-safe, which means that the
100 *creation* of subclasses of Magic should only be done in a single-thread
99 *creation* of subclasses of Magic should only be done in a single-thread
101 context. Instantiation of the classes has no restrictions. Given that
100 context. Instantiation of the classes has no restrictions. Given that
102 these classes are typically created at IPython startup time and before user
101 these classes are typically created at IPython startup time and before user
103 application code becomes active, in practice this should not pose any
102 application code becomes active, in practice this should not pose any
104 problems.
103 problems.
105 """
104 """
106 cls.registered = True
105 cls.registered = True
107 cls.magics = dict(line = magics['line'],
106 cls.magics = dict(line = magics['line'],
108 cell = magics['cell'])
107 cell = magics['cell'])
109 magics['line'] = {}
108 magics['line'] = {}
110 magics['cell'] = {}
109 magics['cell'] = {}
111 return cls
110 return cls
112
111
113
112
114 def record_magic(dct, magic_kind, magic_name, func):
113 def record_magic(dct, magic_kind, magic_name, func):
115 """Utility function to store a function as a magic of a specific kind.
114 """Utility function to store a function as a magic of a specific kind.
116
115
117 Parameters
116 Parameters
118 ----------
117 ----------
119 dct : dict
118 dct : dict
120 A dictionary with 'line' and 'cell' subdicts.
119 A dictionary with 'line' and 'cell' subdicts.
121
120
122 magic_kind : str
121 magic_kind : str
123 Kind of magic to be stored.
122 Kind of magic to be stored.
124
123
125 magic_name : str
124 magic_name : str
126 Key to store the magic as.
125 Key to store the magic as.
127
126
128 func : function
127 func : function
129 Callable object to store.
128 Callable object to store.
130 """
129 """
131 if magic_kind == 'line_cell':
130 if magic_kind == 'line_cell':
132 dct['line'][magic_name] = dct['cell'][magic_name] = func
131 dct['line'][magic_name] = dct['cell'][magic_name] = func
133 else:
132 else:
134 dct[magic_kind][magic_name] = func
133 dct[magic_kind][magic_name] = func
135
134
136
135
137 def validate_type(magic_kind):
136 def validate_type(magic_kind):
138 """Ensure that the given magic_kind is valid.
137 """Ensure that the given magic_kind is valid.
139
138
140 Check that the given magic_kind is one of the accepted spec types (stored
139 Check that the given magic_kind is one of the accepted spec types (stored
141 in the global `magic_spec`), raise ValueError otherwise.
140 in the global `magic_spec`), raise ValueError otherwise.
142 """
141 """
143 if magic_kind not in magic_spec:
142 if magic_kind not in magic_spec:
144 raise ValueError('magic_kind must be one of %s, %s given' %
143 raise ValueError('magic_kind must be one of %s, %s given' %
145 magic_kinds, magic_kind)
144 magic_kinds, magic_kind)
146
145
147
146
148 # The docstrings for the decorator below will be fairly similar for the two
147 # The docstrings for the decorator below will be fairly similar for the two
149 # types (method and function), so we generate them here once and reuse the
148 # types (method and function), so we generate them here once and reuse the
150 # templates below.
149 # templates below.
151 _docstring_template = \
150 _docstring_template = \
152 """Decorate the given {0} as {1} magic.
151 """Decorate the given {0} as {1} magic.
153
152
154 The decorator can be used with or without arguments, as follows.
153 The decorator can be used with or without arguments, as follows.
155
154
156 i) without arguments: it will create a {1} magic named as the {0} being
155 i) without arguments: it will create a {1} magic named as the {0} being
157 decorated::
156 decorated::
158
157
159 @deco
158 @deco
160 def foo(...)
159 def foo(...)
161
160
162 will create a {1} magic named `foo`.
161 will create a {1} magic named `foo`.
163
162
164 ii) with one string argument: which will be used as the actual name of the
163 ii) with one string argument: which will be used as the actual name of the
165 resulting magic::
164 resulting magic::
166
165
167 @deco('bar')
166 @deco('bar')
168 def foo(...)
167 def foo(...)
169
168
170 will create a {1} magic named `bar`.
169 will create a {1} magic named `bar`.
171 """
170 """
172
171
173 # These two are decorator factories. While they are conceptually very similar,
172 # These two are decorator factories. While they are conceptually very similar,
174 # there are enough differences in the details that it's simpler to have them
173 # there are enough differences in the details that it's simpler to have them
175 # written as completely standalone functions rather than trying to share code
174 # written as completely standalone functions rather than trying to share code
176 # and make a single one with convoluted logic.
175 # and make a single one with convoluted logic.
177
176
178 def _method_magic_marker(magic_kind):
177 def _method_magic_marker(magic_kind):
179 """Decorator factory for methods in Magics subclasses.
178 """Decorator factory for methods in Magics subclasses.
180 """
179 """
181
180
182 validate_type(magic_kind)
181 validate_type(magic_kind)
183
182
184 # This is a closure to capture the magic_kind. We could also use a class,
183 # This is a closure to capture the magic_kind. We could also use a class,
185 # but it's overkill for just that one bit of state.
184 # but it's overkill for just that one bit of state.
186 def magic_deco(arg):
185 def magic_deco(arg):
187 call = lambda f, *a, **k: f(*a, **k)
186 call = lambda f, *a, **k: f(*a, **k)
188
187
189 if callable(arg):
188 if callable(arg):
190 # "Naked" decorator call (just @foo, no args)
189 # "Naked" decorator call (just @foo, no args)
191 func = arg
190 func = arg
192 name = func.__name__
191 name = func.__name__
193 retval = decorator(call, func)
192 retval = decorator(call, func)
194 record_magic(magics, magic_kind, name, name)
193 record_magic(magics, magic_kind, name, name)
195 elif isinstance(arg, string_types):
194 elif isinstance(arg, str):
196 # Decorator called with arguments (@foo('bar'))
195 # Decorator called with arguments (@foo('bar'))
197 name = arg
196 name = arg
198 def mark(func, *a, **kw):
197 def mark(func, *a, **kw):
199 record_magic(magics, magic_kind, name, func.__name__)
198 record_magic(magics, magic_kind, name, func.__name__)
200 return decorator(call, func)
199 return decorator(call, func)
201 retval = mark
200 retval = mark
202 else:
201 else:
203 raise TypeError("Decorator can only be called with "
202 raise TypeError("Decorator can only be called with "
204 "string or function")
203 "string or function")
205 return retval
204 return retval
206
205
207 # Ensure the resulting decorator has a usable docstring
206 # Ensure the resulting decorator has a usable docstring
208 magic_deco.__doc__ = _docstring_template.format('method', magic_kind)
207 magic_deco.__doc__ = _docstring_template.format('method', magic_kind)
209 return magic_deco
208 return magic_deco
210
209
211
210
212 def _function_magic_marker(magic_kind):
211 def _function_magic_marker(magic_kind):
213 """Decorator factory for standalone functions.
212 """Decorator factory for standalone functions.
214 """
213 """
215 validate_type(magic_kind)
214 validate_type(magic_kind)
216
215
217 # This is a closure to capture the magic_kind. We could also use a class,
216 # This is a closure to capture the magic_kind. We could also use a class,
218 # but it's overkill for just that one bit of state.
217 # but it's overkill for just that one bit of state.
219 def magic_deco(arg):
218 def magic_deco(arg):
220 call = lambda f, *a, **k: f(*a, **k)
219 call = lambda f, *a, **k: f(*a, **k)
221
220
222 # Find get_ipython() in the caller's namespace
221 # Find get_ipython() in the caller's namespace
223 caller = sys._getframe(1)
222 caller = sys._getframe(1)
224 for ns in ['f_locals', 'f_globals', 'f_builtins']:
223 for ns in ['f_locals', 'f_globals', 'f_builtins']:
225 get_ipython = getattr(caller, ns).get('get_ipython')
224 get_ipython = getattr(caller, ns).get('get_ipython')
226 if get_ipython is not None:
225 if get_ipython is not None:
227 break
226 break
228 else:
227 else:
229 raise NameError('Decorator can only run in context where '
228 raise NameError('Decorator can only run in context where '
230 '`get_ipython` exists')
229 '`get_ipython` exists')
231
230
232 ip = get_ipython()
231 ip = get_ipython()
233
232
234 if callable(arg):
233 if callable(arg):
235 # "Naked" decorator call (just @foo, no args)
234 # "Naked" decorator call (just @foo, no args)
236 func = arg
235 func = arg
237 name = func.__name__
236 name = func.__name__
238 ip.register_magic_function(func, magic_kind, name)
237 ip.register_magic_function(func, magic_kind, name)
239 retval = decorator(call, func)
238 retval = decorator(call, func)
240 elif isinstance(arg, string_types):
239 elif isinstance(arg, str):
241 # Decorator called with arguments (@foo('bar'))
240 # Decorator called with arguments (@foo('bar'))
242 name = arg
241 name = arg
243 def mark(func, *a, **kw):
242 def mark(func, *a, **kw):
244 ip.register_magic_function(func, magic_kind, name)
243 ip.register_magic_function(func, magic_kind, name)
245 return decorator(call, func)
244 return decorator(call, func)
246 retval = mark
245 retval = mark
247 else:
246 else:
248 raise TypeError("Decorator can only be called with "
247 raise TypeError("Decorator can only be called with "
249 "string or function")
248 "string or function")
250 return retval
249 return retval
251
250
252 # Ensure the resulting decorator has a usable docstring
251 # Ensure the resulting decorator has a usable docstring
253 ds = _docstring_template.format('function', magic_kind)
252 ds = _docstring_template.format('function', magic_kind)
254
253
255 ds += dedent("""
254 ds += dedent("""
256 Note: this decorator can only be used in a context where IPython is already
255 Note: this decorator can only be used in a context where IPython is already
257 active, so that the `get_ipython()` call succeeds. You can therefore use
256 active, so that the `get_ipython()` call succeeds. You can therefore use
258 it in your startup files loaded after IPython initializes, but *not* in the
257 it in your startup files loaded after IPython initializes, but *not* in the
259 IPython configuration file itself, which is executed before IPython is
258 IPython configuration file itself, which is executed before IPython is
260 fully up and running. Any file located in the `startup` subdirectory of
259 fully up and running. Any file located in the `startup` subdirectory of
261 your configuration profile will be OK in this sense.
260 your configuration profile will be OK in this sense.
262 """)
261 """)
263
262
264 magic_deco.__doc__ = ds
263 magic_deco.__doc__ = ds
265 return magic_deco
264 return magic_deco
266
265
267
266
268 # Create the actual decorators for public use
267 # Create the actual decorators for public use
269
268
270 # These three are used to decorate methods in class definitions
269 # These three are used to decorate methods in class definitions
271 line_magic = _method_magic_marker('line')
270 line_magic = _method_magic_marker('line')
272 cell_magic = _method_magic_marker('cell')
271 cell_magic = _method_magic_marker('cell')
273 line_cell_magic = _method_magic_marker('line_cell')
272 line_cell_magic = _method_magic_marker('line_cell')
274
273
275 # These three decorate standalone functions and perform the decoration
274 # These three decorate standalone functions and perform the decoration
276 # immediately. They can only run where get_ipython() works
275 # immediately. They can only run where get_ipython() works
277 register_line_magic = _function_magic_marker('line')
276 register_line_magic = _function_magic_marker('line')
278 register_cell_magic = _function_magic_marker('cell')
277 register_cell_magic = _function_magic_marker('cell')
279 register_line_cell_magic = _function_magic_marker('line_cell')
278 register_line_cell_magic = _function_magic_marker('line_cell')
280
279
281 #-----------------------------------------------------------------------------
280 #-----------------------------------------------------------------------------
282 # Core Magic classes
281 # Core Magic classes
283 #-----------------------------------------------------------------------------
282 #-----------------------------------------------------------------------------
284
283
285 class MagicsManager(Configurable):
284 class MagicsManager(Configurable):
286 """Object that handles all magic-related functionality for IPython.
285 """Object that handles all magic-related functionality for IPython.
287 """
286 """
288 # Non-configurable class attributes
287 # Non-configurable class attributes
289
288
290 # A two-level dict, first keyed by magic type, then by magic function, and
289 # A two-level dict, first keyed by magic type, then by magic function, and
291 # holding the actual callable object as value. This is the dict used for
290 # holding the actual callable object as value. This is the dict used for
292 # magic function dispatch
291 # magic function dispatch
293 magics = Dict()
292 magics = Dict()
294
293
295 # A registry of the original objects that we've been given holding magics.
294 # A registry of the original objects that we've been given holding magics.
296 registry = Dict()
295 registry = Dict()
297
296
298 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
297 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
299
298
300 auto_magic = Bool(True, help=
299 auto_magic = Bool(True, help=
301 "Automatically call line magics without requiring explicit % prefix"
300 "Automatically call line magics without requiring explicit % prefix"
302 ).tag(config=True)
301 ).tag(config=True)
303 @observe('auto_magic')
302 @observe('auto_magic')
304 def _auto_magic_changed(self, change):
303 def _auto_magic_changed(self, change):
305 self.shell.automagic = change['new']
304 self.shell.automagic = change['new']
306
305
307 _auto_status = [
306 _auto_status = [
308 'Automagic is OFF, % prefix IS needed for line magics.',
307 'Automagic is OFF, % prefix IS needed for line magics.',
309 'Automagic is ON, % prefix IS NOT needed for line magics.']
308 'Automagic is ON, % prefix IS NOT needed for line magics.']
310
309
311 user_magics = Instance('IPython.core.magics.UserMagics', allow_none=True)
310 user_magics = Instance('IPython.core.magics.UserMagics', allow_none=True)
312
311
313 def __init__(self, shell=None, config=None, user_magics=None, **traits):
312 def __init__(self, shell=None, config=None, user_magics=None, **traits):
314
313
315 super(MagicsManager, self).__init__(shell=shell, config=config,
314 super(MagicsManager, self).__init__(shell=shell, config=config,
316 user_magics=user_magics, **traits)
315 user_magics=user_magics, **traits)
317 self.magics = dict(line={}, cell={})
316 self.magics = dict(line={}, cell={})
318 # Let's add the user_magics to the registry for uniformity, so *all*
317 # Let's add the user_magics to the registry for uniformity, so *all*
319 # registered magic containers can be found there.
318 # registered magic containers can be found there.
320 self.registry[user_magics.__class__.__name__] = user_magics
319 self.registry[user_magics.__class__.__name__] = user_magics
321
320
322 def auto_status(self):
321 def auto_status(self):
323 """Return descriptive string with automagic status."""
322 """Return descriptive string with automagic status."""
324 return self._auto_status[self.auto_magic]
323 return self._auto_status[self.auto_magic]
325
324
326 def lsmagic(self):
325 def lsmagic(self):
327 """Return a dict of currently available magic functions.
326 """Return a dict of currently available magic functions.
328
327
329 The return dict has the keys 'line' and 'cell', corresponding to the
328 The return dict has the keys 'line' and 'cell', corresponding to the
330 two types of magics we support. Each value is a list of names.
329 two types of magics we support. Each value is a list of names.
331 """
330 """
332 return self.magics
331 return self.magics
333
332
334 def lsmagic_docs(self, brief=False, missing=''):
333 def lsmagic_docs(self, brief=False, missing=''):
335 """Return dict of documentation of magic functions.
334 """Return dict of documentation of magic functions.
336
335
337 The return dict has the keys 'line' and 'cell', corresponding to the
336 The return dict has the keys 'line' and 'cell', corresponding to the
338 two types of magics we support. Each value is a dict keyed by magic
337 two types of magics we support. Each value is a dict keyed by magic
339 name whose value is the function docstring. If a docstring is
338 name whose value is the function docstring. If a docstring is
340 unavailable, the value of `missing` is used instead.
339 unavailable, the value of `missing` is used instead.
341
340
342 If brief is True, only the first line of each docstring will be returned.
341 If brief is True, only the first line of each docstring will be returned.
343 """
342 """
344 docs = {}
343 docs = {}
345 for m_type in self.magics:
344 for m_type in self.magics:
346 m_docs = {}
345 m_docs = {}
347 for m_name, m_func in iteritems(self.magics[m_type]):
346 for m_name, m_func in self.magics[m_type].items():
348 if m_func.__doc__:
347 if m_func.__doc__:
349 if brief:
348 if brief:
350 m_docs[m_name] = m_func.__doc__.split('\n', 1)[0]
349 m_docs[m_name] = m_func.__doc__.split('\n', 1)[0]
351 else:
350 else:
352 m_docs[m_name] = m_func.__doc__.rstrip()
351 m_docs[m_name] = m_func.__doc__.rstrip()
353 else:
352 else:
354 m_docs[m_name] = missing
353 m_docs[m_name] = missing
355 docs[m_type] = m_docs
354 docs[m_type] = m_docs
356 return docs
355 return docs
357
356
358 def register(self, *magic_objects):
357 def register(self, *magic_objects):
359 """Register one or more instances of Magics.
358 """Register one or more instances of Magics.
360
359
361 Take one or more classes or instances of classes that subclass the main
360 Take one or more classes or instances of classes that subclass the main
362 `core.Magic` class, and register them with IPython to use the magic
361 `core.Magic` class, and register them with IPython to use the magic
363 functions they provide. The registration process will then ensure that
362 functions they provide. The registration process will then ensure that
364 any methods that have decorated to provide line and/or cell magics will
363 any methods that have decorated to provide line and/or cell magics will
365 be recognized with the `%x`/`%%x` syntax as a line/cell magic
364 be recognized with the `%x`/`%%x` syntax as a line/cell magic
366 respectively.
365 respectively.
367
366
368 If classes are given, they will be instantiated with the default
367 If classes are given, they will be instantiated with the default
369 constructor. If your classes need a custom constructor, you should
368 constructor. If your classes need a custom constructor, you should
370 instanitate them first and pass the instance.
369 instanitate them first and pass the instance.
371
370
372 The provided arguments can be an arbitrary mix of classes and instances.
371 The provided arguments can be an arbitrary mix of classes and instances.
373
372
374 Parameters
373 Parameters
375 ----------
374 ----------
376 magic_objects : one or more classes or instances
375 magic_objects : one or more classes or instances
377 """
376 """
378 # Start by validating them to ensure they have all had their magic
377 # Start by validating them to ensure they have all had their magic
379 # methods registered at the instance level
378 # methods registered at the instance level
380 for m in magic_objects:
379 for m in magic_objects:
381 if not m.registered:
380 if not m.registered:
382 raise ValueError("Class of magics %r was constructed without "
381 raise ValueError("Class of magics %r was constructed without "
383 "the @register_magics class decorator")
382 "the @register_magics class decorator")
384 if isinstance(m, type):
383 if isinstance(m, type):
385 # If we're given an uninstantiated class
384 # If we're given an uninstantiated class
386 m = m(shell=self.shell)
385 m = m(shell=self.shell)
387
386
388 # Now that we have an instance, we can register it and update the
387 # Now that we have an instance, we can register it and update the
389 # table of callables
388 # table of callables
390 self.registry[m.__class__.__name__] = m
389 self.registry[m.__class__.__name__] = m
391 for mtype in magic_kinds:
390 for mtype in magic_kinds:
392 self.magics[mtype].update(m.magics[mtype])
391 self.magics[mtype].update(m.magics[mtype])
393
392
394 def register_function(self, func, magic_kind='line', magic_name=None):
393 def register_function(self, func, magic_kind='line', magic_name=None):
395 """Expose a standalone function as magic function for IPython.
394 """Expose a standalone function as magic function for IPython.
396
395
397 This will create an IPython magic (line, cell or both) from a
396 This will create an IPython magic (line, cell or both) from a
398 standalone function. The functions should have the following
397 standalone function. The functions should have the following
399 signatures:
398 signatures:
400
399
401 * For line magics: `def f(line)`
400 * For line magics: `def f(line)`
402 * For cell magics: `def f(line, cell)`
401 * For cell magics: `def f(line, cell)`
403 * For a function that does both: `def f(line, cell=None)`
402 * For a function that does both: `def f(line, cell=None)`
404
403
405 In the latter case, the function will be called with `cell==None` when
404 In the latter case, the function will be called with `cell==None` when
406 invoked as `%f`, and with cell as a string when invoked as `%%f`.
405 invoked as `%f`, and with cell as a string when invoked as `%%f`.
407
406
408 Parameters
407 Parameters
409 ----------
408 ----------
410 func : callable
409 func : callable
411 Function to be registered as a magic.
410 Function to be registered as a magic.
412
411
413 magic_kind : str
412 magic_kind : str
414 Kind of magic, one of 'line', 'cell' or 'line_cell'
413 Kind of magic, one of 'line', 'cell' or 'line_cell'
415
414
416 magic_name : optional str
415 magic_name : optional str
417 If given, the name the magic will have in the IPython namespace. By
416 If given, the name the magic will have in the IPython namespace. By
418 default, the name of the function itself is used.
417 default, the name of the function itself is used.
419 """
418 """
420
419
421 # Create the new method in the user_magics and register it in the
420 # Create the new method in the user_magics and register it in the
422 # global table
421 # global table
423 validate_type(magic_kind)
422 validate_type(magic_kind)
424 magic_name = func.__name__ if magic_name is None else magic_name
423 magic_name = func.__name__ if magic_name is None else magic_name
425 setattr(self.user_magics, magic_name, func)
424 setattr(self.user_magics, magic_name, func)
426 record_magic(self.magics, magic_kind, magic_name, func)
425 record_magic(self.magics, magic_kind, magic_name, func)
427
426
428 def register_alias(self, alias_name, magic_name, magic_kind='line'):
427 def register_alias(self, alias_name, magic_name, magic_kind='line'):
429 """Register an alias to a magic function.
428 """Register an alias to a magic function.
430
429
431 The alias is an instance of :class:`MagicAlias`, which holds the
430 The alias is an instance of :class:`MagicAlias`, which holds the
432 name and kind of the magic it should call. Binding is done at
431 name and kind of the magic it should call. Binding is done at
433 call time, so if the underlying magic function is changed the alias
432 call time, so if the underlying magic function is changed the alias
434 will call the new function.
433 will call the new function.
435
434
436 Parameters
435 Parameters
437 ----------
436 ----------
438 alias_name : str
437 alias_name : str
439 The name of the magic to be registered.
438 The name of the magic to be registered.
440
439
441 magic_name : str
440 magic_name : str
442 The name of an existing magic.
441 The name of an existing magic.
443
442
444 magic_kind : str
443 magic_kind : str
445 Kind of magic, one of 'line' or 'cell'
444 Kind of magic, one of 'line' or 'cell'
446 """
445 """
447
446
448 # `validate_type` is too permissive, as it allows 'line_cell'
447 # `validate_type` is too permissive, as it allows 'line_cell'
449 # which we do not handle.
448 # which we do not handle.
450 if magic_kind not in magic_kinds:
449 if magic_kind not in magic_kinds:
451 raise ValueError('magic_kind must be one of %s, %s given' %
450 raise ValueError('magic_kind must be one of %s, %s given' %
452 magic_kinds, magic_kind)
451 magic_kinds, magic_kind)
453
452
454 alias = MagicAlias(self.shell, magic_name, magic_kind)
453 alias = MagicAlias(self.shell, magic_name, magic_kind)
455 setattr(self.user_magics, alias_name, alias)
454 setattr(self.user_magics, alias_name, alias)
456 record_magic(self.magics, magic_kind, alias_name, alias)
455 record_magic(self.magics, magic_kind, alias_name, alias)
457
456
458 # Key base class that provides the central functionality for magics.
457 # Key base class that provides the central functionality for magics.
459
458
460
459
461 class Magics(Configurable):
460 class Magics(Configurable):
462 """Base class for implementing magic functions.
461 """Base class for implementing magic functions.
463
462
464 Shell functions which can be reached as %function_name. All magic
463 Shell functions which can be reached as %function_name. All magic
465 functions should accept a string, which they can parse for their own
464 functions should accept a string, which they can parse for their own
466 needs. This can make some functions easier to type, eg `%cd ../`
465 needs. This can make some functions easier to type, eg `%cd ../`
467 vs. `%cd("../")`
466 vs. `%cd("../")`
468
467
469 Classes providing magic functions need to subclass this class, and they
468 Classes providing magic functions need to subclass this class, and they
470 MUST:
469 MUST:
471
470
472 - Use the method decorators `@line_magic` and `@cell_magic` to decorate
471 - Use the method decorators `@line_magic` and `@cell_magic` to decorate
473 individual methods as magic functions, AND
472 individual methods as magic functions, AND
474
473
475 - Use the class decorator `@magics_class` to ensure that the magic
474 - Use the class decorator `@magics_class` to ensure that the magic
476 methods are properly registered at the instance level upon instance
475 methods are properly registered at the instance level upon instance
477 initialization.
476 initialization.
478
477
479 See :mod:`magic_functions` for examples of actual implementation classes.
478 See :mod:`magic_functions` for examples of actual implementation classes.
480 """
479 """
481 # Dict holding all command-line options for each magic.
480 # Dict holding all command-line options for each magic.
482 options_table = None
481 options_table = None
483 # Dict for the mapping of magic names to methods, set by class decorator
482 # Dict for the mapping of magic names to methods, set by class decorator
484 magics = None
483 magics = None
485 # Flag to check that the class decorator was properly applied
484 # Flag to check that the class decorator was properly applied
486 registered = False
485 registered = False
487 # Instance of IPython shell
486 # Instance of IPython shell
488 shell = None
487 shell = None
489
488
490 def __init__(self, shell=None, **kwargs):
489 def __init__(self, shell=None, **kwargs):
491 if not(self.__class__.registered):
490 if not(self.__class__.registered):
492 raise ValueError('Magics subclass without registration - '
491 raise ValueError('Magics subclass without registration - '
493 'did you forget to apply @magics_class?')
492 'did you forget to apply @magics_class?')
494 if shell is not None:
493 if shell is not None:
495 if hasattr(shell, 'configurables'):
494 if hasattr(shell, 'configurables'):
496 shell.configurables.append(self)
495 shell.configurables.append(self)
497 if hasattr(shell, 'config'):
496 if hasattr(shell, 'config'):
498 kwargs.setdefault('parent', shell)
497 kwargs.setdefault('parent', shell)
499
498
500 self.shell = shell
499 self.shell = shell
501 self.options_table = {}
500 self.options_table = {}
502 # The method decorators are run when the instance doesn't exist yet, so
501 # The method decorators are run when the instance doesn't exist yet, so
503 # they can only record the names of the methods they are supposed to
502 # they can only record the names of the methods they are supposed to
504 # grab. Only now, that the instance exists, can we create the proper
503 # grab. Only now, that the instance exists, can we create the proper
505 # mapping to bound methods. So we read the info off the original names
504 # mapping to bound methods. So we read the info off the original names
506 # table and replace each method name by the actual bound method.
505 # table and replace each method name by the actual bound method.
507 # But we mustn't clobber the *class* mapping, in case of multiple instances.
506 # But we mustn't clobber the *class* mapping, in case of multiple instances.
508 class_magics = self.magics
507 class_magics = self.magics
509 self.magics = {}
508 self.magics = {}
510 for mtype in magic_kinds:
509 for mtype in magic_kinds:
511 tab = self.magics[mtype] = {}
510 tab = self.magics[mtype] = {}
512 cls_tab = class_magics[mtype]
511 cls_tab = class_magics[mtype]
513 for magic_name, meth_name in iteritems(cls_tab):
512 for magic_name, meth_name in cls_tab.items():
514 if isinstance(meth_name, string_types):
513 if isinstance(meth_name, str):
515 # it's a method name, grab it
514 # it's a method name, grab it
516 tab[magic_name] = getattr(self, meth_name)
515 tab[magic_name] = getattr(self, meth_name)
517 else:
516 else:
518 # it's the real thing
517 # it's the real thing
519 tab[magic_name] = meth_name
518 tab[magic_name] = meth_name
520 # Configurable **needs** to be initiated at the end or the config
519 # Configurable **needs** to be initiated at the end or the config
521 # magics get screwed up.
520 # magics get screwed up.
522 super(Magics, self).__init__(**kwargs)
521 super(Magics, self).__init__(**kwargs)
523
522
524 def arg_err(self,func):
523 def arg_err(self,func):
525 """Print docstring if incorrect arguments were passed"""
524 """Print docstring if incorrect arguments were passed"""
526 print('Error in arguments:')
525 print('Error in arguments:')
527 print(oinspect.getdoc(func))
526 print(oinspect.getdoc(func))
528
527
529 def format_latex(self, strng):
528 def format_latex(self, strng):
530 """Format a string for latex inclusion."""
529 """Format a string for latex inclusion."""
531
530
532 # Characters that need to be escaped for latex:
531 # Characters that need to be escaped for latex:
533 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
532 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
534 # Magic command names as headers:
533 # Magic command names as headers:
535 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
534 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
536 re.MULTILINE)
535 re.MULTILINE)
537 # Magic commands
536 # Magic commands
538 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
537 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
539 re.MULTILINE)
538 re.MULTILINE)
540 # Paragraph continue
539 # Paragraph continue
541 par_re = re.compile(r'\\$',re.MULTILINE)
540 par_re = re.compile(r'\\$',re.MULTILINE)
542
541
543 # The "\n" symbol
542 # The "\n" symbol
544 newline_re = re.compile(r'\\n')
543 newline_re = re.compile(r'\\n')
545
544
546 # Now build the string for output:
545 # Now build the string for output:
547 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
546 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
548 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
547 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
549 strng)
548 strng)
550 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
549 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
551 strng = par_re.sub(r'\\\\',strng)
550 strng = par_re.sub(r'\\\\',strng)
552 strng = escape_re.sub(r'\\\1',strng)
551 strng = escape_re.sub(r'\\\1',strng)
553 strng = newline_re.sub(r'\\textbackslash{}n',strng)
552 strng = newline_re.sub(r'\\textbackslash{}n',strng)
554 return strng
553 return strng
555
554
556 def parse_options(self, arg_str, opt_str, *long_opts, **kw):
555 def parse_options(self, arg_str, opt_str, *long_opts, **kw):
557 """Parse options passed to an argument string.
556 """Parse options passed to an argument string.
558
557
559 The interface is similar to that of :func:`getopt.getopt`, but it
558 The interface is similar to that of :func:`getopt.getopt`, but it
560 returns a :class:`~IPython.utils.struct.Struct` with the options as keys
559 returns a :class:`~IPython.utils.struct.Struct` with the options as keys
561 and the stripped argument string still as a string.
560 and the stripped argument string still as a string.
562
561
563 arg_str is quoted as a true sys.argv vector by using shlex.split.
562 arg_str is quoted as a true sys.argv vector by using shlex.split.
564 This allows us to easily expand variables, glob files, quote
563 This allows us to easily expand variables, glob files, quote
565 arguments, etc.
564 arguments, etc.
566
565
567 Parameters
566 Parameters
568 ----------
567 ----------
569
568
570 arg_str : str
569 arg_str : str
571 The arguments to parse.
570 The arguments to parse.
572
571
573 opt_str : str
572 opt_str : str
574 The options specification.
573 The options specification.
575
574
576 mode : str, default 'string'
575 mode : str, default 'string'
577 If given as 'list', the argument string is returned as a list (split
576 If given as 'list', the argument string is returned as a list (split
578 on whitespace) instead of a string.
577 on whitespace) instead of a string.
579
578
580 list_all : bool, default False
579 list_all : bool, default False
581 Put all option values in lists. Normally only options
580 Put all option values in lists. Normally only options
582 appearing more than once are put in a list.
581 appearing more than once are put in a list.
583
582
584 posix : bool, default True
583 posix : bool, default True
585 Whether to split the input line in POSIX mode or not, as per the
584 Whether to split the input line in POSIX mode or not, as per the
586 conventions outlined in the :mod:`shlex` module from the standard
585 conventions outlined in the :mod:`shlex` module from the standard
587 library.
586 library.
588 """
587 """
589
588
590 # inject default options at the beginning of the input line
589 # inject default options at the beginning of the input line
591 caller = sys._getframe(1).f_code.co_name
590 caller = sys._getframe(1).f_code.co_name
592 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
591 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
593
592
594 mode = kw.get('mode','string')
593 mode = kw.get('mode','string')
595 if mode not in ['string','list']:
594 if mode not in ['string','list']:
596 raise ValueError('incorrect mode given: %s' % mode)
595 raise ValueError('incorrect mode given: %s' % mode)
597 # Get options
596 # Get options
598 list_all = kw.get('list_all',0)
597 list_all = kw.get('list_all',0)
599 posix = kw.get('posix', os.name == 'posix')
598 posix = kw.get('posix', os.name == 'posix')
600 strict = kw.get('strict', True)
599 strict = kw.get('strict', True)
601
600
602 # Check if we have more than one argument to warrant extra processing:
601 # Check if we have more than one argument to warrant extra processing:
603 odict = {} # Dictionary with options
602 odict = {} # Dictionary with options
604 args = arg_str.split()
603 args = arg_str.split()
605 if len(args) >= 1:
604 if len(args) >= 1:
606 # If the list of inputs only has 0 or 1 thing in it, there's no
605 # If the list of inputs only has 0 or 1 thing in it, there's no
607 # need to look for options
606 # need to look for options
608 argv = arg_split(arg_str, posix, strict)
607 argv = arg_split(arg_str, posix, strict)
609 # Do regular option processing
608 # Do regular option processing
610 try:
609 try:
611 opts,args = getopt(argv, opt_str, long_opts)
610 opts,args = getopt(argv, opt_str, long_opts)
612 except GetoptError as e:
611 except GetoptError as e:
613 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
612 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
614 " ".join(long_opts)))
613 " ".join(long_opts)))
615 for o,a in opts:
614 for o,a in opts:
616 if o.startswith('--'):
615 if o.startswith('--'):
617 o = o[2:]
616 o = o[2:]
618 else:
617 else:
619 o = o[1:]
618 o = o[1:]
620 try:
619 try:
621 odict[o].append(a)
620 odict[o].append(a)
622 except AttributeError:
621 except AttributeError:
623 odict[o] = [odict[o],a]
622 odict[o] = [odict[o],a]
624 except KeyError:
623 except KeyError:
625 if list_all:
624 if list_all:
626 odict[o] = [a]
625 odict[o] = [a]
627 else:
626 else:
628 odict[o] = a
627 odict[o] = a
629
628
630 # Prepare opts,args for return
629 # Prepare opts,args for return
631 opts = Struct(odict)
630 opts = Struct(odict)
632 if mode == 'string':
631 if mode == 'string':
633 args = ' '.join(args)
632 args = ' '.join(args)
634
633
635 return opts,args
634 return opts,args
636
635
637 def default_option(self, fn, optstr):
636 def default_option(self, fn, optstr):
638 """Make an entry in the options_table for fn, with value optstr"""
637 """Make an entry in the options_table for fn, with value optstr"""
639
638
640 if fn not in self.lsmagic():
639 if fn not in self.lsmagic():
641 error("%s is not a magic function" % fn)
640 error("%s is not a magic function" % fn)
642 self.options_table[fn] = optstr
641 self.options_table[fn] = optstr
643
642
644
643
645 class MagicAlias(object):
644 class MagicAlias(object):
646 """An alias to another magic function.
645 """An alias to another magic function.
647
646
648 An alias is determined by its magic name and magic kind. Lookup
647 An alias is determined by its magic name and magic kind. Lookup
649 is done at call time, so if the underlying magic changes the alias
648 is done at call time, so if the underlying magic changes the alias
650 will call the new function.
649 will call the new function.
651
650
652 Use the :meth:`MagicsManager.register_alias` method or the
651 Use the :meth:`MagicsManager.register_alias` method or the
653 `%alias_magic` magic function to create and register a new alias.
652 `%alias_magic` magic function to create and register a new alias.
654 """
653 """
655 def __init__(self, shell, magic_name, magic_kind):
654 def __init__(self, shell, magic_name, magic_kind):
656 self.shell = shell
655 self.shell = shell
657 self.magic_name = magic_name
656 self.magic_name = magic_name
658 self.magic_kind = magic_kind
657 self.magic_kind = magic_kind
659
658
660 self.pretty_target = '%s%s' % (magic_escapes[self.magic_kind], self.magic_name)
659 self.pretty_target = '%s%s' % (magic_escapes[self.magic_kind], self.magic_name)
661 self.__doc__ = "Alias for `%s`." % self.pretty_target
660 self.__doc__ = "Alias for `%s`." % self.pretty_target
662
661
663 self._in_call = False
662 self._in_call = False
664
663
665 def __call__(self, *args, **kwargs):
664 def __call__(self, *args, **kwargs):
666 """Call the magic alias."""
665 """Call the magic alias."""
667 fn = self.shell.find_magic(self.magic_name, self.magic_kind)
666 fn = self.shell.find_magic(self.magic_name, self.magic_kind)
668 if fn is None:
667 if fn is None:
669 raise UsageError("Magic `%s` not found." % self.pretty_target)
668 raise UsageError("Magic `%s` not found." % self.pretty_target)
670
669
671 # Protect against infinite recursion.
670 # Protect against infinite recursion.
672 if self._in_call:
671 if self._in_call:
673 raise UsageError("Infinite recursion detected; "
672 raise UsageError("Infinite recursion detected; "
674 "magic aliases cannot call themselves.")
673 "magic aliases cannot call themselves.")
675 self._in_call = True
674 self._in_call = True
676 try:
675 try:
677 return fn(*args, **kwargs)
676 return fn(*args, **kwargs)
678 finally:
677 finally:
679 self._in_call = False
678 self._in_call = False
@@ -1,581 +1,580 b''
1 """Implementation of basic magic functions."""
1 """Implementation of basic magic functions."""
2
2
3
3
4 import argparse
4 import argparse
5 import io
5 import io
6 import sys
6 import sys
7 from pprint import pformat
7 from pprint import pformat
8
8
9 from IPython.core import magic_arguments, page
9 from IPython.core import magic_arguments, page
10 from IPython.core.error import UsageError
10 from IPython.core.error import UsageError
11 from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes
11 from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes
12 from IPython.utils.text import format_screen, dedent, indent
12 from IPython.utils.text import format_screen, dedent, indent
13 from IPython.testing.skipdoctest import skip_doctest
13 from IPython.testing.skipdoctest import skip_doctest
14 from IPython.utils.ipstruct import Struct
14 from IPython.utils.ipstruct import Struct
15 from IPython.utils.py3compat import unicode_type
16 from warnings import warn
15 from warnings import warn
17 from logging import error
16 from logging import error
18
17
19
18
20 class MagicsDisplay(object):
19 class MagicsDisplay(object):
21 def __init__(self, magics_manager):
20 def __init__(self, magics_manager):
22 self.magics_manager = magics_manager
21 self.magics_manager = magics_manager
23
22
24 def _lsmagic(self):
23 def _lsmagic(self):
25 """The main implementation of the %lsmagic"""
24 """The main implementation of the %lsmagic"""
26 mesc = magic_escapes['line']
25 mesc = magic_escapes['line']
27 cesc = magic_escapes['cell']
26 cesc = magic_escapes['cell']
28 mman = self.magics_manager
27 mman = self.magics_manager
29 magics = mman.lsmagic()
28 magics = mman.lsmagic()
30 out = ['Available line magics:',
29 out = ['Available line magics:',
31 mesc + (' '+mesc).join(sorted(magics['line'])),
30 mesc + (' '+mesc).join(sorted(magics['line'])),
32 '',
31 '',
33 'Available cell magics:',
32 'Available cell magics:',
34 cesc + (' '+cesc).join(sorted(magics['cell'])),
33 cesc + (' '+cesc).join(sorted(magics['cell'])),
35 '',
34 '',
36 mman.auto_status()]
35 mman.auto_status()]
37 return '\n'.join(out)
36 return '\n'.join(out)
38
37
39 def _repr_pretty_(self, p, cycle):
38 def _repr_pretty_(self, p, cycle):
40 p.text(self._lsmagic())
39 p.text(self._lsmagic())
41
40
42 def __str__(self):
41 def __str__(self):
43 return self._lsmagic()
42 return self._lsmagic()
44
43
45 def _jsonable(self):
44 def _jsonable(self):
46 """turn magics dict into jsonable dict of the same structure
45 """turn magics dict into jsonable dict of the same structure
47
46
48 replaces object instances with their class names as strings
47 replaces object instances with their class names as strings
49 """
48 """
50 magic_dict = {}
49 magic_dict = {}
51 mman = self.magics_manager
50 mman = self.magics_manager
52 magics = mman.lsmagic()
51 magics = mman.lsmagic()
53 for key, subdict in magics.items():
52 for key, subdict in magics.items():
54 d = {}
53 d = {}
55 magic_dict[key] = d
54 magic_dict[key] = d
56 for name, obj in subdict.items():
55 for name, obj in subdict.items():
57 try:
56 try:
58 classname = obj.__self__.__class__.__name__
57 classname = obj.__self__.__class__.__name__
59 except AttributeError:
58 except AttributeError:
60 classname = 'Other'
59 classname = 'Other'
61
60
62 d[name] = classname
61 d[name] = classname
63 return magic_dict
62 return magic_dict
64
63
65 def _repr_json_(self):
64 def _repr_json_(self):
66 return self._jsonable()
65 return self._jsonable()
67
66
68
67
69 @magics_class
68 @magics_class
70 class BasicMagics(Magics):
69 class BasicMagics(Magics):
71 """Magics that provide central IPython functionality.
70 """Magics that provide central IPython functionality.
72
71
73 These are various magics that don't fit into specific categories but that
72 These are various magics that don't fit into specific categories but that
74 are all part of the base 'IPython experience'."""
73 are all part of the base 'IPython experience'."""
75
74
76 @magic_arguments.magic_arguments()
75 @magic_arguments.magic_arguments()
77 @magic_arguments.argument(
76 @magic_arguments.argument(
78 '-l', '--line', action='store_true',
77 '-l', '--line', action='store_true',
79 help="""Create a line magic alias."""
78 help="""Create a line magic alias."""
80 )
79 )
81 @magic_arguments.argument(
80 @magic_arguments.argument(
82 '-c', '--cell', action='store_true',
81 '-c', '--cell', action='store_true',
83 help="""Create a cell magic alias."""
82 help="""Create a cell magic alias."""
84 )
83 )
85 @magic_arguments.argument(
84 @magic_arguments.argument(
86 'name',
85 'name',
87 help="""Name of the magic to be created."""
86 help="""Name of the magic to be created."""
88 )
87 )
89 @magic_arguments.argument(
88 @magic_arguments.argument(
90 'target',
89 'target',
91 help="""Name of the existing line or cell magic."""
90 help="""Name of the existing line or cell magic."""
92 )
91 )
93 @line_magic
92 @line_magic
94 def alias_magic(self, line=''):
93 def alias_magic(self, line=''):
95 """Create an alias for an existing line or cell magic.
94 """Create an alias for an existing line or cell magic.
96
95
97 Examples
96 Examples
98 --------
97 --------
99 ::
98 ::
100
99
101 In [1]: %alias_magic t timeit
100 In [1]: %alias_magic t timeit
102 Created `%t` as an alias for `%timeit`.
101 Created `%t` as an alias for `%timeit`.
103 Created `%%t` as an alias for `%%timeit`.
102 Created `%%t` as an alias for `%%timeit`.
104
103
105 In [2]: %t -n1 pass
104 In [2]: %t -n1 pass
106 1 loops, best of 3: 954 ns per loop
105 1 loops, best of 3: 954 ns per loop
107
106
108 In [3]: %%t -n1
107 In [3]: %%t -n1
109 ...: pass
108 ...: pass
110 ...:
109 ...:
111 1 loops, best of 3: 954 ns per loop
110 1 loops, best of 3: 954 ns per loop
112
111
113 In [4]: %alias_magic --cell whereami pwd
112 In [4]: %alias_magic --cell whereami pwd
114 UsageError: Cell magic function `%%pwd` not found.
113 UsageError: Cell magic function `%%pwd` not found.
115 In [5]: %alias_magic --line whereami pwd
114 In [5]: %alias_magic --line whereami pwd
116 Created `%whereami` as an alias for `%pwd`.
115 Created `%whereami` as an alias for `%pwd`.
117
116
118 In [6]: %whereami
117 In [6]: %whereami
119 Out[6]: u'/home/testuser'
118 Out[6]: u'/home/testuser'
120 """
119 """
121 args = magic_arguments.parse_argstring(self.alias_magic, line)
120 args = magic_arguments.parse_argstring(self.alias_magic, line)
122 shell = self.shell
121 shell = self.shell
123 mman = self.shell.magics_manager
122 mman = self.shell.magics_manager
124 escs = ''.join(magic_escapes.values())
123 escs = ''.join(magic_escapes.values())
125
124
126 target = args.target.lstrip(escs)
125 target = args.target.lstrip(escs)
127 name = args.name.lstrip(escs)
126 name = args.name.lstrip(escs)
128
127
129 # Find the requested magics.
128 # Find the requested magics.
130 m_line = shell.find_magic(target, 'line')
129 m_line = shell.find_magic(target, 'line')
131 m_cell = shell.find_magic(target, 'cell')
130 m_cell = shell.find_magic(target, 'cell')
132 if args.line and m_line is None:
131 if args.line and m_line is None:
133 raise UsageError('Line magic function `%s%s` not found.' %
132 raise UsageError('Line magic function `%s%s` not found.' %
134 (magic_escapes['line'], target))
133 (magic_escapes['line'], target))
135 if args.cell and m_cell is None:
134 if args.cell and m_cell is None:
136 raise UsageError('Cell magic function `%s%s` not found.' %
135 raise UsageError('Cell magic function `%s%s` not found.' %
137 (magic_escapes['cell'], target))
136 (magic_escapes['cell'], target))
138
137
139 # If --line and --cell are not specified, default to the ones
138 # If --line and --cell are not specified, default to the ones
140 # that are available.
139 # that are available.
141 if not args.line and not args.cell:
140 if not args.line and not args.cell:
142 if not m_line and not m_cell:
141 if not m_line and not m_cell:
143 raise UsageError(
142 raise UsageError(
144 'No line or cell magic with name `%s` found.' % target
143 'No line or cell magic with name `%s` found.' % target
145 )
144 )
146 args.line = bool(m_line)
145 args.line = bool(m_line)
147 args.cell = bool(m_cell)
146 args.cell = bool(m_cell)
148
147
149 if args.line:
148 if args.line:
150 mman.register_alias(name, target, 'line')
149 mman.register_alias(name, target, 'line')
151 print('Created `%s%s` as an alias for `%s%s`.' % (
150 print('Created `%s%s` as an alias for `%s%s`.' % (
152 magic_escapes['line'], name,
151 magic_escapes['line'], name,
153 magic_escapes['line'], target))
152 magic_escapes['line'], target))
154
153
155 if args.cell:
154 if args.cell:
156 mman.register_alias(name, target, 'cell')
155 mman.register_alias(name, target, 'cell')
157 print('Created `%s%s` as an alias for `%s%s`.' % (
156 print('Created `%s%s` as an alias for `%s%s`.' % (
158 magic_escapes['cell'], name,
157 magic_escapes['cell'], name,
159 magic_escapes['cell'], target))
158 magic_escapes['cell'], target))
160
159
161 @line_magic
160 @line_magic
162 def lsmagic(self, parameter_s=''):
161 def lsmagic(self, parameter_s=''):
163 """List currently available magic functions."""
162 """List currently available magic functions."""
164 return MagicsDisplay(self.shell.magics_manager)
163 return MagicsDisplay(self.shell.magics_manager)
165
164
166 def _magic_docs(self, brief=False, rest=False):
165 def _magic_docs(self, brief=False, rest=False):
167 """Return docstrings from magic functions."""
166 """Return docstrings from magic functions."""
168 mman = self.shell.magics_manager
167 mman = self.shell.magics_manager
169 docs = mman.lsmagic_docs(brief, missing='No documentation')
168 docs = mman.lsmagic_docs(brief, missing='No documentation')
170
169
171 if rest:
170 if rest:
172 format_string = '**%s%s**::\n\n%s\n\n'
171 format_string = '**%s%s**::\n\n%s\n\n'
173 else:
172 else:
174 format_string = '%s%s:\n%s\n'
173 format_string = '%s%s:\n%s\n'
175
174
176 return ''.join(
175 return ''.join(
177 [format_string % (magic_escapes['line'], fname,
176 [format_string % (magic_escapes['line'], fname,
178 indent(dedent(fndoc)))
177 indent(dedent(fndoc)))
179 for fname, fndoc in sorted(docs['line'].items())]
178 for fname, fndoc in sorted(docs['line'].items())]
180 +
179 +
181 [format_string % (magic_escapes['cell'], fname,
180 [format_string % (magic_escapes['cell'], fname,
182 indent(dedent(fndoc)))
181 indent(dedent(fndoc)))
183 for fname, fndoc in sorted(docs['cell'].items())]
182 for fname, fndoc in sorted(docs['cell'].items())]
184 )
183 )
185
184
186 @line_magic
185 @line_magic
187 def magic(self, parameter_s=''):
186 def magic(self, parameter_s=''):
188 """Print information about the magic function system.
187 """Print information about the magic function system.
189
188
190 Supported formats: -latex, -brief, -rest
189 Supported formats: -latex, -brief, -rest
191 """
190 """
192
191
193 mode = ''
192 mode = ''
194 try:
193 try:
195 mode = parameter_s.split()[0][1:]
194 mode = parameter_s.split()[0][1:]
196 except IndexError:
195 except IndexError:
197 pass
196 pass
198
197
199 brief = (mode == 'brief')
198 brief = (mode == 'brief')
200 rest = (mode == 'rest')
199 rest = (mode == 'rest')
201 magic_docs = self._magic_docs(brief, rest)
200 magic_docs = self._magic_docs(brief, rest)
202
201
203 if mode == 'latex':
202 if mode == 'latex':
204 print(self.format_latex(magic_docs))
203 print(self.format_latex(magic_docs))
205 return
204 return
206 else:
205 else:
207 magic_docs = format_screen(magic_docs)
206 magic_docs = format_screen(magic_docs)
208
207
209 out = ["""
208 out = ["""
210 IPython's 'magic' functions
209 IPython's 'magic' functions
211 ===========================
210 ===========================
212
211
213 The magic function system provides a series of functions which allow you to
212 The magic function system provides a series of functions which allow you to
214 control the behavior of IPython itself, plus a lot of system-type
213 control the behavior of IPython itself, plus a lot of system-type
215 features. There are two kinds of magics, line-oriented and cell-oriented.
214 features. There are two kinds of magics, line-oriented and cell-oriented.
216
215
217 Line magics are prefixed with the % character and work much like OS
216 Line magics are prefixed with the % character and work much like OS
218 command-line calls: they get as an argument the rest of the line, where
217 command-line calls: they get as an argument the rest of the line, where
219 arguments are passed without parentheses or quotes. For example, this will
218 arguments are passed without parentheses or quotes. For example, this will
220 time the given statement::
219 time the given statement::
221
220
222 %timeit range(1000)
221 %timeit range(1000)
223
222
224 Cell magics are prefixed with a double %%, and they are functions that get as
223 Cell magics are prefixed with a double %%, and they are functions that get as
225 an argument not only the rest of the line, but also the lines below it in a
224 an argument not only the rest of the line, but also the lines below it in a
226 separate argument. These magics are called with two arguments: the rest of the
225 separate argument. These magics are called with two arguments: the rest of the
227 call line and the body of the cell, consisting of the lines below the first.
226 call line and the body of the cell, consisting of the lines below the first.
228 For example::
227 For example::
229
228
230 %%timeit x = numpy.random.randn((100, 100))
229 %%timeit x = numpy.random.randn((100, 100))
231 numpy.linalg.svd(x)
230 numpy.linalg.svd(x)
232
231
233 will time the execution of the numpy svd routine, running the assignment of x
232 will time the execution of the numpy svd routine, running the assignment of x
234 as part of the setup phase, which is not timed.
233 as part of the setup phase, which is not timed.
235
234
236 In a line-oriented client (the terminal or Qt console IPython), starting a new
235 In a line-oriented client (the terminal or Qt console IPython), starting a new
237 input with %% will automatically enter cell mode, and IPython will continue
236 input with %% will automatically enter cell mode, and IPython will continue
238 reading input until a blank line is given. In the notebook, simply type the
237 reading input until a blank line is given. In the notebook, simply type the
239 whole cell as one entity, but keep in mind that the %% escape can only be at
238 whole cell as one entity, but keep in mind that the %% escape can only be at
240 the very start of the cell.
239 the very start of the cell.
241
240
242 NOTE: If you have 'automagic' enabled (via the command line option or with the
241 NOTE: If you have 'automagic' enabled (via the command line option or with the
243 %automagic function), you don't need to type in the % explicitly for line
242 %automagic function), you don't need to type in the % explicitly for line
244 magics; cell magics always require an explicit '%%' escape. By default,
243 magics; cell magics always require an explicit '%%' escape. By default,
245 IPython ships with automagic on, so you should only rarely need the % escape.
244 IPython ships with automagic on, so you should only rarely need the % escape.
246
245
247 Example: typing '%cd mydir' (without the quotes) changes your working directory
246 Example: typing '%cd mydir' (without the quotes) changes your working directory
248 to 'mydir', if it exists.
247 to 'mydir', if it exists.
249
248
250 For a list of the available magic functions, use %lsmagic. For a description
249 For a list of the available magic functions, use %lsmagic. For a description
251 of any of them, type %magic_name?, e.g. '%cd?'.
250 of any of them, type %magic_name?, e.g. '%cd?'.
252
251
253 Currently the magic system has the following functions:""",
252 Currently the magic system has the following functions:""",
254 magic_docs,
253 magic_docs,
255 "Summary of magic functions (from %slsmagic):" % magic_escapes['line'],
254 "Summary of magic functions (from %slsmagic):" % magic_escapes['line'],
256 str(self.lsmagic()),
255 str(self.lsmagic()),
257 ]
256 ]
258 page.page('\n'.join(out))
257 page.page('\n'.join(out))
259
258
260
259
261 @line_magic
260 @line_magic
262 def page(self, parameter_s=''):
261 def page(self, parameter_s=''):
263 """Pretty print the object and display it through a pager.
262 """Pretty print the object and display it through a pager.
264
263
265 %page [options] OBJECT
264 %page [options] OBJECT
266
265
267 If no object is given, use _ (last output).
266 If no object is given, use _ (last output).
268
267
269 Options:
268 Options:
270
269
271 -r: page str(object), don't pretty-print it."""
270 -r: page str(object), don't pretty-print it."""
272
271
273 # After a function contributed by Olivier Aubert, slightly modified.
272 # After a function contributed by Olivier Aubert, slightly modified.
274
273
275 # Process options/args
274 # Process options/args
276 opts, args = self.parse_options(parameter_s, 'r')
275 opts, args = self.parse_options(parameter_s, 'r')
277 raw = 'r' in opts
276 raw = 'r' in opts
278
277
279 oname = args and args or '_'
278 oname = args and args or '_'
280 info = self.shell._ofind(oname)
279 info = self.shell._ofind(oname)
281 if info['found']:
280 if info['found']:
282 txt = (raw and str or pformat)( info['obj'] )
281 txt = (raw and str or pformat)( info['obj'] )
283 page.page(txt)
282 page.page(txt)
284 else:
283 else:
285 print('Object `%s` not found' % oname)
284 print('Object `%s` not found' % oname)
286
285
287 @line_magic
286 @line_magic
288 def profile(self, parameter_s=''):
287 def profile(self, parameter_s=''):
289 """Print your currently active IPython profile.
288 """Print your currently active IPython profile.
290
289
291 See Also
290 See Also
292 --------
291 --------
293 prun : run code using the Python profiler
292 prun : run code using the Python profiler
294 (:meth:`~IPython.core.magics.execution.ExecutionMagics.prun`)
293 (:meth:`~IPython.core.magics.execution.ExecutionMagics.prun`)
295 """
294 """
296 warn("%profile is now deprecated. Please use get_ipython().profile instead.")
295 warn("%profile is now deprecated. Please use get_ipython().profile instead.")
297 from IPython.core.application import BaseIPythonApplication
296 from IPython.core.application import BaseIPythonApplication
298 if BaseIPythonApplication.initialized():
297 if BaseIPythonApplication.initialized():
299 print(BaseIPythonApplication.instance().profile)
298 print(BaseIPythonApplication.instance().profile)
300 else:
299 else:
301 error("profile is an application-level value, but you don't appear to be in an IPython application")
300 error("profile is an application-level value, but you don't appear to be in an IPython application")
302
301
303 @line_magic
302 @line_magic
304 def pprint(self, parameter_s=''):
303 def pprint(self, parameter_s=''):
305 """Toggle pretty printing on/off."""
304 """Toggle pretty printing on/off."""
306 ptformatter = self.shell.display_formatter.formatters['text/plain']
305 ptformatter = self.shell.display_formatter.formatters['text/plain']
307 ptformatter.pprint = bool(1 - ptformatter.pprint)
306 ptformatter.pprint = bool(1 - ptformatter.pprint)
308 print('Pretty printing has been turned',
307 print('Pretty printing has been turned',
309 ['OFF','ON'][ptformatter.pprint])
308 ['OFF','ON'][ptformatter.pprint])
310
309
311 @line_magic
310 @line_magic
312 def colors(self, parameter_s=''):
311 def colors(self, parameter_s=''):
313 """Switch color scheme for prompts, info system and exception handlers.
312 """Switch color scheme for prompts, info system and exception handlers.
314
313
315 Currently implemented schemes: NoColor, Linux, LightBG.
314 Currently implemented schemes: NoColor, Linux, LightBG.
316
315
317 Color scheme names are not case-sensitive.
316 Color scheme names are not case-sensitive.
318
317
319 Examples
318 Examples
320 --------
319 --------
321 To get a plain black and white terminal::
320 To get a plain black and white terminal::
322
321
323 %colors nocolor
322 %colors nocolor
324 """
323 """
325 def color_switch_err(name):
324 def color_switch_err(name):
326 warn('Error changing %s color schemes.\n%s' %
325 warn('Error changing %s color schemes.\n%s' %
327 (name, sys.exc_info()[1]), stacklevel=2)
326 (name, sys.exc_info()[1]), stacklevel=2)
328
327
329
328
330 new_scheme = parameter_s.strip()
329 new_scheme = parameter_s.strip()
331 if not new_scheme:
330 if not new_scheme:
332 raise UsageError(
331 raise UsageError(
333 "%colors: you must specify a color scheme. See '%colors?'")
332 "%colors: you must specify a color scheme. See '%colors?'")
334 # local shortcut
333 # local shortcut
335 shell = self.shell
334 shell = self.shell
336
335
337 # Set shell colour scheme
336 # Set shell colour scheme
338 try:
337 try:
339 shell.colors = new_scheme
338 shell.colors = new_scheme
340 shell.refresh_style()
339 shell.refresh_style()
341 except:
340 except:
342 color_switch_err('shell')
341 color_switch_err('shell')
343
342
344 # Set exception colors
343 # Set exception colors
345 try:
344 try:
346 shell.InteractiveTB.set_colors(scheme = new_scheme)
345 shell.InteractiveTB.set_colors(scheme = new_scheme)
347 shell.SyntaxTB.set_colors(scheme = new_scheme)
346 shell.SyntaxTB.set_colors(scheme = new_scheme)
348 except:
347 except:
349 color_switch_err('exception')
348 color_switch_err('exception')
350
349
351 # Set info (for 'object?') colors
350 # Set info (for 'object?') colors
352 if shell.color_info:
351 if shell.color_info:
353 try:
352 try:
354 shell.inspector.set_active_scheme(new_scheme)
353 shell.inspector.set_active_scheme(new_scheme)
355 except:
354 except:
356 color_switch_err('object inspector')
355 color_switch_err('object inspector')
357 else:
356 else:
358 shell.inspector.set_active_scheme('NoColor')
357 shell.inspector.set_active_scheme('NoColor')
359
358
360 @line_magic
359 @line_magic
361 def xmode(self, parameter_s=''):
360 def xmode(self, parameter_s=''):
362 """Switch modes for the exception handlers.
361 """Switch modes for the exception handlers.
363
362
364 Valid modes: Plain, Context and Verbose.
363 Valid modes: Plain, Context and Verbose.
365
364
366 If called without arguments, acts as a toggle."""
365 If called without arguments, acts as a toggle."""
367
366
368 def xmode_switch_err(name):
367 def xmode_switch_err(name):
369 warn('Error changing %s exception modes.\n%s' %
368 warn('Error changing %s exception modes.\n%s' %
370 (name,sys.exc_info()[1]))
369 (name,sys.exc_info()[1]))
371
370
372 shell = self.shell
371 shell = self.shell
373 new_mode = parameter_s.strip().capitalize()
372 new_mode = parameter_s.strip().capitalize()
374 try:
373 try:
375 shell.InteractiveTB.set_mode(mode=new_mode)
374 shell.InteractiveTB.set_mode(mode=new_mode)
376 print('Exception reporting mode:',shell.InteractiveTB.mode)
375 print('Exception reporting mode:',shell.InteractiveTB.mode)
377 except:
376 except:
378 xmode_switch_err('user')
377 xmode_switch_err('user')
379
378
380 @line_magic
379 @line_magic
381 def quickref(self,arg):
380 def quickref(self,arg):
382 """ Show a quick reference sheet """
381 """ Show a quick reference sheet """
383 from IPython.core.usage import quick_reference
382 from IPython.core.usage import quick_reference
384 qr = quick_reference + self._magic_docs(brief=True)
383 qr = quick_reference + self._magic_docs(brief=True)
385 page.page(qr)
384 page.page(qr)
386
385
387 @line_magic
386 @line_magic
388 def doctest_mode(self, parameter_s=''):
387 def doctest_mode(self, parameter_s=''):
389 """Toggle doctest mode on and off.
388 """Toggle doctest mode on and off.
390
389
391 This mode is intended to make IPython behave as much as possible like a
390 This mode is intended to make IPython behave as much as possible like a
392 plain Python shell, from the perspective of how its prompts, exceptions
391 plain Python shell, from the perspective of how its prompts, exceptions
393 and output look. This makes it easy to copy and paste parts of a
392 and output look. This makes it easy to copy and paste parts of a
394 session into doctests. It does so by:
393 session into doctests. It does so by:
395
394
396 - Changing the prompts to the classic ``>>>`` ones.
395 - Changing the prompts to the classic ``>>>`` ones.
397 - Changing the exception reporting mode to 'Plain'.
396 - Changing the exception reporting mode to 'Plain'.
398 - Disabling pretty-printing of output.
397 - Disabling pretty-printing of output.
399
398
400 Note that IPython also supports the pasting of code snippets that have
399 Note that IPython also supports the pasting of code snippets that have
401 leading '>>>' and '...' prompts in them. This means that you can paste
400 leading '>>>' and '...' prompts in them. This means that you can paste
402 doctests from files or docstrings (even if they have leading
401 doctests from files or docstrings (even if they have leading
403 whitespace), and the code will execute correctly. You can then use
402 whitespace), and the code will execute correctly. You can then use
404 '%history -t' to see the translated history; this will give you the
403 '%history -t' to see the translated history; this will give you the
405 input after removal of all the leading prompts and whitespace, which
404 input after removal of all the leading prompts and whitespace, which
406 can be pasted back into an editor.
405 can be pasted back into an editor.
407
406
408 With these features, you can switch into this mode easily whenever you
407 With these features, you can switch into this mode easily whenever you
409 need to do testing and changes to doctests, without having to leave
408 need to do testing and changes to doctests, without having to leave
410 your existing IPython session.
409 your existing IPython session.
411 """
410 """
412
411
413 # Shorthands
412 # Shorthands
414 shell = self.shell
413 shell = self.shell
415 meta = shell.meta
414 meta = shell.meta
416 disp_formatter = self.shell.display_formatter
415 disp_formatter = self.shell.display_formatter
417 ptformatter = disp_formatter.formatters['text/plain']
416 ptformatter = disp_formatter.formatters['text/plain']
418 # dstore is a data store kept in the instance metadata bag to track any
417 # dstore is a data store kept in the instance metadata bag to track any
419 # changes we make, so we can undo them later.
418 # changes we make, so we can undo them later.
420 dstore = meta.setdefault('doctest_mode',Struct())
419 dstore = meta.setdefault('doctest_mode',Struct())
421 save_dstore = dstore.setdefault
420 save_dstore = dstore.setdefault
422
421
423 # save a few values we'll need to recover later
422 # save a few values we'll need to recover later
424 mode = save_dstore('mode',False)
423 mode = save_dstore('mode',False)
425 save_dstore('rc_pprint',ptformatter.pprint)
424 save_dstore('rc_pprint',ptformatter.pprint)
426 save_dstore('xmode',shell.InteractiveTB.mode)
425 save_dstore('xmode',shell.InteractiveTB.mode)
427 save_dstore('rc_separate_out',shell.separate_out)
426 save_dstore('rc_separate_out',shell.separate_out)
428 save_dstore('rc_separate_out2',shell.separate_out2)
427 save_dstore('rc_separate_out2',shell.separate_out2)
429 save_dstore('rc_separate_in',shell.separate_in)
428 save_dstore('rc_separate_in',shell.separate_in)
430 save_dstore('rc_active_types',disp_formatter.active_types)
429 save_dstore('rc_active_types',disp_formatter.active_types)
431
430
432 if not mode:
431 if not mode:
433 # turn on
432 # turn on
434
433
435 # Prompt separators like plain python
434 # Prompt separators like plain python
436 shell.separate_in = ''
435 shell.separate_in = ''
437 shell.separate_out = ''
436 shell.separate_out = ''
438 shell.separate_out2 = ''
437 shell.separate_out2 = ''
439
438
440
439
441 ptformatter.pprint = False
440 ptformatter.pprint = False
442 disp_formatter.active_types = ['text/plain']
441 disp_formatter.active_types = ['text/plain']
443
442
444 shell.magic('xmode Plain')
443 shell.magic('xmode Plain')
445 else:
444 else:
446 # turn off
445 # turn off
447 shell.separate_in = dstore.rc_separate_in
446 shell.separate_in = dstore.rc_separate_in
448
447
449 shell.separate_out = dstore.rc_separate_out
448 shell.separate_out = dstore.rc_separate_out
450 shell.separate_out2 = dstore.rc_separate_out2
449 shell.separate_out2 = dstore.rc_separate_out2
451
450
452 ptformatter.pprint = dstore.rc_pprint
451 ptformatter.pprint = dstore.rc_pprint
453 disp_formatter.active_types = dstore.rc_active_types
452 disp_formatter.active_types = dstore.rc_active_types
454
453
455 shell.magic('xmode ' + dstore.xmode)
454 shell.magic('xmode ' + dstore.xmode)
456
455
457 # mode here is the state before we switch; switch_doctest_mode takes
456 # mode here is the state before we switch; switch_doctest_mode takes
458 # the mode we're switching to.
457 # the mode we're switching to.
459 shell.switch_doctest_mode(not mode)
458 shell.switch_doctest_mode(not mode)
460
459
461 # Store new mode and inform
460 # Store new mode and inform
462 dstore.mode = bool(not mode)
461 dstore.mode = bool(not mode)
463 mode_label = ['OFF','ON'][dstore.mode]
462 mode_label = ['OFF','ON'][dstore.mode]
464 print('Doctest mode is:', mode_label)
463 print('Doctest mode is:', mode_label)
465
464
466 @line_magic
465 @line_magic
467 def gui(self, parameter_s=''):
466 def gui(self, parameter_s=''):
468 """Enable or disable IPython GUI event loop integration.
467 """Enable or disable IPython GUI event loop integration.
469
468
470 %gui [GUINAME]
469 %gui [GUINAME]
471
470
472 This magic replaces IPython's threaded shells that were activated
471 This magic replaces IPython's threaded shells that were activated
473 using the (pylab/wthread/etc.) command line flags. GUI toolkits
472 using the (pylab/wthread/etc.) command line flags. GUI toolkits
474 can now be enabled at runtime and keyboard
473 can now be enabled at runtime and keyboard
475 interrupts should work without any problems. The following toolkits
474 interrupts should work without any problems. The following toolkits
476 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
475 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
477
476
478 %gui wx # enable wxPython event loop integration
477 %gui wx # enable wxPython event loop integration
479 %gui qt4|qt # enable PyQt4 event loop integration
478 %gui qt4|qt # enable PyQt4 event loop integration
480 %gui qt5 # enable PyQt5 event loop integration
479 %gui qt5 # enable PyQt5 event loop integration
481 %gui gtk # enable PyGTK event loop integration
480 %gui gtk # enable PyGTK event loop integration
482 %gui gtk3 # enable Gtk3 event loop integration
481 %gui gtk3 # enable Gtk3 event loop integration
483 %gui tk # enable Tk event loop integration
482 %gui tk # enable Tk event loop integration
484 %gui osx # enable Cocoa event loop integration
483 %gui osx # enable Cocoa event loop integration
485 # (requires %matplotlib 1.1)
484 # (requires %matplotlib 1.1)
486 %gui # disable all event loop integration
485 %gui # disable all event loop integration
487
486
488 WARNING: after any of these has been called you can simply create
487 WARNING: after any of these has been called you can simply create
489 an application object, but DO NOT start the event loop yourself, as
488 an application object, but DO NOT start the event loop yourself, as
490 we have already handled that.
489 we have already handled that.
491 """
490 """
492 opts, arg = self.parse_options(parameter_s, '')
491 opts, arg = self.parse_options(parameter_s, '')
493 if arg=='': arg = None
492 if arg=='': arg = None
494 try:
493 try:
495 return self.shell.enable_gui(arg)
494 return self.shell.enable_gui(arg)
496 except Exception as e:
495 except Exception as e:
497 # print simple error message, rather than traceback if we can't
496 # print simple error message, rather than traceback if we can't
498 # hook up the GUI
497 # hook up the GUI
499 error(str(e))
498 error(str(e))
500
499
501 @skip_doctest
500 @skip_doctest
502 @line_magic
501 @line_magic
503 def precision(self, s=''):
502 def precision(self, s=''):
504 """Set floating point precision for pretty printing.
503 """Set floating point precision for pretty printing.
505
504
506 Can set either integer precision or a format string.
505 Can set either integer precision or a format string.
507
506
508 If numpy has been imported and precision is an int,
507 If numpy has been imported and precision is an int,
509 numpy display precision will also be set, via ``numpy.set_printoptions``.
508 numpy display precision will also be set, via ``numpy.set_printoptions``.
510
509
511 If no argument is given, defaults will be restored.
510 If no argument is given, defaults will be restored.
512
511
513 Examples
512 Examples
514 --------
513 --------
515 ::
514 ::
516
515
517 In [1]: from math import pi
516 In [1]: from math import pi
518
517
519 In [2]: %precision 3
518 In [2]: %precision 3
520 Out[2]: u'%.3f'
519 Out[2]: u'%.3f'
521
520
522 In [3]: pi
521 In [3]: pi
523 Out[3]: 3.142
522 Out[3]: 3.142
524
523
525 In [4]: %precision %i
524 In [4]: %precision %i
526 Out[4]: u'%i'
525 Out[4]: u'%i'
527
526
528 In [5]: pi
527 In [5]: pi
529 Out[5]: 3
528 Out[5]: 3
530
529
531 In [6]: %precision %e
530 In [6]: %precision %e
532 Out[6]: u'%e'
531 Out[6]: u'%e'
533
532
534 In [7]: pi**10
533 In [7]: pi**10
535 Out[7]: 9.364805e+04
534 Out[7]: 9.364805e+04
536
535
537 In [8]: %precision
536 In [8]: %precision
538 Out[8]: u'%r'
537 Out[8]: u'%r'
539
538
540 In [9]: pi**10
539 In [9]: pi**10
541 Out[9]: 93648.047476082982
540 Out[9]: 93648.047476082982
542 """
541 """
543 ptformatter = self.shell.display_formatter.formatters['text/plain']
542 ptformatter = self.shell.display_formatter.formatters['text/plain']
544 ptformatter.float_precision = s
543 ptformatter.float_precision = s
545 return ptformatter.float_format
544 return ptformatter.float_format
546
545
547 @magic_arguments.magic_arguments()
546 @magic_arguments.magic_arguments()
548 @magic_arguments.argument(
547 @magic_arguments.argument(
549 '-e', '--export', action='store_true', default=False,
548 '-e', '--export', action='store_true', default=False,
550 help=argparse.SUPPRESS
549 help=argparse.SUPPRESS
551 )
550 )
552 @magic_arguments.argument(
551 @magic_arguments.argument(
553 'filename', type=unicode_type,
552 'filename', type=str,
554 help='Notebook name or filename'
553 help='Notebook name or filename'
555 )
554 )
556 @line_magic
555 @line_magic
557 def notebook(self, s):
556 def notebook(self, s):
558 """Export and convert IPython notebooks.
557 """Export and convert IPython notebooks.
559
558
560 This function can export the current IPython history to a notebook file.
559 This function can export the current IPython history to a notebook file.
561 For example, to export the history to "foo.ipynb" do "%notebook foo.ipynb".
560 For example, to export the history to "foo.ipynb" do "%notebook foo.ipynb".
562
561
563 The -e or --export flag is deprecated in IPython 5.2, and will be
562 The -e or --export flag is deprecated in IPython 5.2, and will be
564 removed in the future.
563 removed in the future.
565 """
564 """
566 args = magic_arguments.parse_argstring(self.notebook, s)
565 args = magic_arguments.parse_argstring(self.notebook, s)
567
566
568 from nbformat import write, v4
567 from nbformat import write, v4
569
568
570 cells = []
569 cells = []
571 hist = list(self.shell.history_manager.get_range())
570 hist = list(self.shell.history_manager.get_range())
572 if(len(hist)<=1):
571 if(len(hist)<=1):
573 raise ValueError('History is empty, cannot export')
572 raise ValueError('History is empty, cannot export')
574 for session, execution_count, source in hist[:-1]:
573 for session, execution_count, source in hist[:-1]:
575 cells.append(v4.new_code_cell(
574 cells.append(v4.new_code_cell(
576 execution_count=execution_count,
575 execution_count=execution_count,
577 source=source
576 source=source
578 ))
577 ))
579 nb = v4.new_notebook(cells=cells)
578 nb = v4.new_notebook(cells=cells)
580 with io.open(args.filename, 'w', encoding='utf-8') as f:
579 with io.open(args.filename, 'w', encoding='utf-8') as f:
581 write(nb, f, version=4)
580 write(nb, f, version=4)
@@ -1,744 +1,743 b''
1 """Implementation of code management magic functions.
1 """Implementation of code management magic functions.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Copyright (c) 2012 The IPython Development Team.
4 # Copyright (c) 2012 The IPython Development Team.
5 #
5 #
6 # Distributed under the terms of the Modified BSD License.
6 # Distributed under the terms of the Modified BSD License.
7 #
7 #
8 # The full license is in the file COPYING.txt, distributed with this software.
8 # The full license is in the file COPYING.txt, distributed with this software.
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Imports
12 # Imports
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 # Stdlib
15 # Stdlib
16 import inspect
16 import inspect
17 import io
17 import io
18 import os
18 import os
19 import re
19 import re
20 import sys
20 import sys
21 import ast
21 import ast
22 from itertools import chain
22 from itertools import chain
23
23
24 # Our own packages
24 # Our own packages
25 from IPython.core.error import TryNext, StdinNotImplementedError, UsageError
25 from IPython.core.error import TryNext, StdinNotImplementedError, UsageError
26 from IPython.core.macro import Macro
26 from IPython.core.macro import Macro
27 from IPython.core.magic import Magics, magics_class, line_magic
27 from IPython.core.magic import Magics, magics_class, line_magic
28 from IPython.core.oinspect import find_file, find_source_lines
28 from IPython.core.oinspect import find_file, find_source_lines
29 from IPython.testing.skipdoctest import skip_doctest
29 from IPython.testing.skipdoctest import skip_doctest
30 from IPython.utils import py3compat
30 from IPython.utils import py3compat
31 from IPython.utils.py3compat import string_types
32 from IPython.utils.contexts import preserve_keys
31 from IPython.utils.contexts import preserve_keys
33 from IPython.utils.path import get_py_filename
32 from IPython.utils.path import get_py_filename
34 from warnings import warn
33 from warnings import warn
35 from logging import error
34 from logging import error
36 from IPython.utils.text import get_text_list
35 from IPython.utils.text import get_text_list
37
36
38 #-----------------------------------------------------------------------------
37 #-----------------------------------------------------------------------------
39 # Magic implementation classes
38 # Magic implementation classes
40 #-----------------------------------------------------------------------------
39 #-----------------------------------------------------------------------------
41
40
42 # Used for exception handling in magic_edit
41 # Used for exception handling in magic_edit
43 class MacroToEdit(ValueError): pass
42 class MacroToEdit(ValueError): pass
44
43
45 ipython_input_pat = re.compile(r"<ipython\-input\-(\d+)-[a-z\d]+>$")
44 ipython_input_pat = re.compile(r"<ipython\-input\-(\d+)-[a-z\d]+>$")
46
45
47 # To match, e.g. 8-10 1:5 :10 3-
46 # To match, e.g. 8-10 1:5 :10 3-
48 range_re = re.compile(r"""
47 range_re = re.compile(r"""
49 (?P<start>\d+)?
48 (?P<start>\d+)?
50 ((?P<sep>[\-:])
49 ((?P<sep>[\-:])
51 (?P<end>\d+)?)?
50 (?P<end>\d+)?)?
52 $""", re.VERBOSE)
51 $""", re.VERBOSE)
53
52
54
53
55 def extract_code_ranges(ranges_str):
54 def extract_code_ranges(ranges_str):
56 """Turn a string of range for %%load into 2-tuples of (start, stop)
55 """Turn a string of range for %%load into 2-tuples of (start, stop)
57 ready to use as a slice of the content splitted by lines.
56 ready to use as a slice of the content splitted by lines.
58
57
59 Examples
58 Examples
60 --------
59 --------
61 list(extract_input_ranges("5-10 2"))
60 list(extract_input_ranges("5-10 2"))
62 [(4, 10), (1, 2)]
61 [(4, 10), (1, 2)]
63 """
62 """
64 for range_str in ranges_str.split():
63 for range_str in ranges_str.split():
65 rmatch = range_re.match(range_str)
64 rmatch = range_re.match(range_str)
66 if not rmatch:
65 if not rmatch:
67 continue
66 continue
68 sep = rmatch.group("sep")
67 sep = rmatch.group("sep")
69 start = rmatch.group("start")
68 start = rmatch.group("start")
70 end = rmatch.group("end")
69 end = rmatch.group("end")
71
70
72 if sep == '-':
71 if sep == '-':
73 start = int(start) - 1 if start else None
72 start = int(start) - 1 if start else None
74 end = int(end) if end else None
73 end = int(end) if end else None
75 elif sep == ':':
74 elif sep == ':':
76 start = int(start) - 1 if start else None
75 start = int(start) - 1 if start else None
77 end = int(end) - 1 if end else None
76 end = int(end) - 1 if end else None
78 else:
77 else:
79 end = int(start)
78 end = int(start)
80 start = int(start) - 1
79 start = int(start) - 1
81 yield (start, end)
80 yield (start, end)
82
81
83
82
84 @skip_doctest
83 @skip_doctest
85 def extract_symbols(code, symbols):
84 def extract_symbols(code, symbols):
86 """
85 """
87 Return a tuple (blocks, not_found)
86 Return a tuple (blocks, not_found)
88 where ``blocks`` is a list of code fragments
87 where ``blocks`` is a list of code fragments
89 for each symbol parsed from code, and ``not_found`` are
88 for each symbol parsed from code, and ``not_found`` are
90 symbols not found in the code.
89 symbols not found in the code.
91
90
92 For example::
91 For example::
93
92
94 >>> code = '''a = 10
93 >>> code = '''a = 10
95
94
96 def b(): return 42
95 def b(): return 42
97
96
98 class A: pass'''
97 class A: pass'''
99
98
100 >>> extract_symbols(code, 'A,b,z')
99 >>> extract_symbols(code, 'A,b,z')
101 (["class A: pass", "def b(): return 42"], ['z'])
100 (["class A: pass", "def b(): return 42"], ['z'])
102 """
101 """
103 symbols = symbols.split(',')
102 symbols = symbols.split(',')
104
103
105 # this will raise SyntaxError if code isn't valid Python
104 # this will raise SyntaxError if code isn't valid Python
106 py_code = ast.parse(code)
105 py_code = ast.parse(code)
107
106
108 marks = [(getattr(s, 'name', None), s.lineno) for s in py_code.body]
107 marks = [(getattr(s, 'name', None), s.lineno) for s in py_code.body]
109 code = code.split('\n')
108 code = code.split('\n')
110
109
111 symbols_lines = {}
110 symbols_lines = {}
112
111
113 # we already know the start_lineno of each symbol (marks).
112 # we already know the start_lineno of each symbol (marks).
114 # To find each end_lineno, we traverse in reverse order until each
113 # To find each end_lineno, we traverse in reverse order until each
115 # non-blank line
114 # non-blank line
116 end = len(code)
115 end = len(code)
117 for name, start in reversed(marks):
116 for name, start in reversed(marks):
118 while not code[end - 1].strip():
117 while not code[end - 1].strip():
119 end -= 1
118 end -= 1
120 if name:
119 if name:
121 symbols_lines[name] = (start - 1, end)
120 symbols_lines[name] = (start - 1, end)
122 end = start - 1
121 end = start - 1
123
122
124 # Now symbols_lines is a map
123 # Now symbols_lines is a map
125 # {'symbol_name': (start_lineno, end_lineno), ...}
124 # {'symbol_name': (start_lineno, end_lineno), ...}
126
125
127 # fill a list with chunks of codes for each requested symbol
126 # fill a list with chunks of codes for each requested symbol
128 blocks = []
127 blocks = []
129 not_found = []
128 not_found = []
130 for symbol in symbols:
129 for symbol in symbols:
131 if symbol in symbols_lines:
130 if symbol in symbols_lines:
132 start, end = symbols_lines[symbol]
131 start, end = symbols_lines[symbol]
133 blocks.append('\n'.join(code[start:end]) + '\n')
132 blocks.append('\n'.join(code[start:end]) + '\n')
134 else:
133 else:
135 not_found.append(symbol)
134 not_found.append(symbol)
136
135
137 return blocks, not_found
136 return blocks, not_found
138
137
139 def strip_initial_indent(lines):
138 def strip_initial_indent(lines):
140 """For %load, strip indent from lines until finding an unindented line.
139 """For %load, strip indent from lines until finding an unindented line.
141
140
142 https://github.com/ipython/ipython/issues/9775
141 https://github.com/ipython/ipython/issues/9775
143 """
142 """
144 indent_re = re.compile(r'\s+')
143 indent_re = re.compile(r'\s+')
145
144
146 it = iter(lines)
145 it = iter(lines)
147 first_line = next(it)
146 first_line = next(it)
148 indent_match = indent_re.match(first_line)
147 indent_match = indent_re.match(first_line)
149
148
150 if indent_match:
149 if indent_match:
151 # First line was indented
150 # First line was indented
152 indent = indent_match.group()
151 indent = indent_match.group()
153 yield first_line[len(indent):]
152 yield first_line[len(indent):]
154
153
155 for line in it:
154 for line in it:
156 if line.startswith(indent):
155 if line.startswith(indent):
157 yield line[len(indent):]
156 yield line[len(indent):]
158 else:
157 else:
159 # Less indented than the first line - stop dedenting
158 # Less indented than the first line - stop dedenting
160 yield line
159 yield line
161 break
160 break
162 else:
161 else:
163 yield first_line
162 yield first_line
164
163
165 # Pass the remaining lines through without dedenting
164 # Pass the remaining lines through without dedenting
166 for line in it:
165 for line in it:
167 yield line
166 yield line
168
167
169
168
170 class InteractivelyDefined(Exception):
169 class InteractivelyDefined(Exception):
171 """Exception for interactively defined variable in magic_edit"""
170 """Exception for interactively defined variable in magic_edit"""
172 def __init__(self, index):
171 def __init__(self, index):
173 self.index = index
172 self.index = index
174
173
175
174
176 @magics_class
175 @magics_class
177 class CodeMagics(Magics):
176 class CodeMagics(Magics):
178 """Magics related to code management (loading, saving, editing, ...)."""
177 """Magics related to code management (loading, saving, editing, ...)."""
179
178
180 def __init__(self, *args, **kwargs):
179 def __init__(self, *args, **kwargs):
181 self._knowntemps = set()
180 self._knowntemps = set()
182 super(CodeMagics, self).__init__(*args, **kwargs)
181 super(CodeMagics, self).__init__(*args, **kwargs)
183
182
184 @line_magic
183 @line_magic
185 def save(self, parameter_s=''):
184 def save(self, parameter_s=''):
186 """Save a set of lines or a macro to a given filename.
185 """Save a set of lines or a macro to a given filename.
187
186
188 Usage:\\
187 Usage:\\
189 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
188 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
190
189
191 Options:
190 Options:
192
191
193 -r: use 'raw' input. By default, the 'processed' history is used,
192 -r: use 'raw' input. By default, the 'processed' history is used,
194 so that magics are loaded in their transformed version to valid
193 so that magics are loaded in their transformed version to valid
195 Python. If this option is given, the raw input as typed as the
194 Python. If this option is given, the raw input as typed as the
196 command line is used instead.
195 command line is used instead.
197
196
198 -f: force overwrite. If file exists, %save will prompt for overwrite
197 -f: force overwrite. If file exists, %save will prompt for overwrite
199 unless -f is given.
198 unless -f is given.
200
199
201 -a: append to the file instead of overwriting it.
200 -a: append to the file instead of overwriting it.
202
201
203 This function uses the same syntax as %history for input ranges,
202 This function uses the same syntax as %history for input ranges,
204 then saves the lines to the filename you specify.
203 then saves the lines to the filename you specify.
205
204
206 It adds a '.py' extension to the file if you don't do so yourself, and
205 It adds a '.py' extension to the file if you don't do so yourself, and
207 it asks for confirmation before overwriting existing files.
206 it asks for confirmation before overwriting existing files.
208
207
209 If `-r` option is used, the default extension is `.ipy`.
208 If `-r` option is used, the default extension is `.ipy`.
210 """
209 """
211
210
212 opts,args = self.parse_options(parameter_s,'fra',mode='list')
211 opts,args = self.parse_options(parameter_s,'fra',mode='list')
213 if not args:
212 if not args:
214 raise UsageError('Missing filename.')
213 raise UsageError('Missing filename.')
215 raw = 'r' in opts
214 raw = 'r' in opts
216 force = 'f' in opts
215 force = 'f' in opts
217 append = 'a' in opts
216 append = 'a' in opts
218 mode = 'a' if append else 'w'
217 mode = 'a' if append else 'w'
219 ext = u'.ipy' if raw else u'.py'
218 ext = u'.ipy' if raw else u'.py'
220 fname, codefrom = args[0], " ".join(args[1:])
219 fname, codefrom = args[0], " ".join(args[1:])
221 if not fname.endswith((u'.py',u'.ipy')):
220 if not fname.endswith((u'.py',u'.ipy')):
222 fname += ext
221 fname += ext
223 file_exists = os.path.isfile(fname)
222 file_exists = os.path.isfile(fname)
224 if file_exists and not force and not append:
223 if file_exists and not force and not append:
225 try:
224 try:
226 overwrite = self.shell.ask_yes_no('File `%s` exists. Overwrite (y/[N])? ' % fname, default='n')
225 overwrite = self.shell.ask_yes_no('File `%s` exists. Overwrite (y/[N])? ' % fname, default='n')
227 except StdinNotImplementedError:
226 except StdinNotImplementedError:
228 print("File `%s` exists. Use `%%save -f %s` to force overwrite" % (fname, parameter_s))
227 print("File `%s` exists. Use `%%save -f %s` to force overwrite" % (fname, parameter_s))
229 return
228 return
230 if not overwrite :
229 if not overwrite :
231 print('Operation cancelled.')
230 print('Operation cancelled.')
232 return
231 return
233 try:
232 try:
234 cmds = self.shell.find_user_code(codefrom,raw)
233 cmds = self.shell.find_user_code(codefrom,raw)
235 except (TypeError, ValueError) as e:
234 except (TypeError, ValueError) as e:
236 print(e.args[0])
235 print(e.args[0])
237 return
236 return
238 out = py3compat.cast_unicode(cmds)
237 out = py3compat.cast_unicode(cmds)
239 with io.open(fname, mode, encoding="utf-8") as f:
238 with io.open(fname, mode, encoding="utf-8") as f:
240 if not file_exists or not append:
239 if not file_exists or not append:
241 f.write(u"# coding: utf-8\n")
240 f.write(u"# coding: utf-8\n")
242 f.write(out)
241 f.write(out)
243 # make sure we end on a newline
242 # make sure we end on a newline
244 if not out.endswith(u'\n'):
243 if not out.endswith(u'\n'):
245 f.write(u'\n')
244 f.write(u'\n')
246 print('The following commands were written to file `%s`:' % fname)
245 print('The following commands were written to file `%s`:' % fname)
247 print(cmds)
246 print(cmds)
248
247
249 @line_magic
248 @line_magic
250 def pastebin(self, parameter_s=''):
249 def pastebin(self, parameter_s=''):
251 """Upload code to Github's Gist paste bin, returning the URL.
250 """Upload code to Github's Gist paste bin, returning the URL.
252
251
253 Usage:\\
252 Usage:\\
254 %pastebin [-d "Custom description"] 1-7
253 %pastebin [-d "Custom description"] 1-7
255
254
256 The argument can be an input history range, a filename, or the name of a
255 The argument can be an input history range, a filename, or the name of a
257 string or macro.
256 string or macro.
258
257
259 Options:
258 Options:
260
259
261 -d: Pass a custom description for the gist. The default will say
260 -d: Pass a custom description for the gist. The default will say
262 "Pasted from IPython".
261 "Pasted from IPython".
263 """
262 """
264 opts, args = self.parse_options(parameter_s, 'd:')
263 opts, args = self.parse_options(parameter_s, 'd:')
265
264
266 try:
265 try:
267 code = self.shell.find_user_code(args)
266 code = self.shell.find_user_code(args)
268 except (ValueError, TypeError) as e:
267 except (ValueError, TypeError) as e:
269 print(e.args[0])
268 print(e.args[0])
270 return
269 return
271
270
272 # Deferred import
271 # Deferred import
273 try:
272 try:
274 from urllib.request import urlopen # Py 3
273 from urllib.request import urlopen # Py 3
275 except ImportError:
274 except ImportError:
276 from urllib2 import urlopen
275 from urllib2 import urlopen
277 import json
276 import json
278 post_data = json.dumps({
277 post_data = json.dumps({
279 "description": opts.get('d', "Pasted from IPython"),
278 "description": opts.get('d', "Pasted from IPython"),
280 "public": True,
279 "public": True,
281 "files": {
280 "files": {
282 "file1.py": {
281 "file1.py": {
283 "content": code
282 "content": code
284 }
283 }
285 }
284 }
286 }).encode('utf-8')
285 }).encode('utf-8')
287
286
288 response = urlopen("https://api.github.com/gists", post_data)
287 response = urlopen("https://api.github.com/gists", post_data)
289 response_data = json.loads(response.read().decode('utf-8'))
288 response_data = json.loads(response.read().decode('utf-8'))
290 return response_data['html_url']
289 return response_data['html_url']
291
290
292 @line_magic
291 @line_magic
293 def loadpy(self, arg_s):
292 def loadpy(self, arg_s):
294 """Alias of `%load`
293 """Alias of `%load`
295
294
296 `%loadpy` has gained some flexibility and dropped the requirement of a `.py`
295 `%loadpy` has gained some flexibility and dropped the requirement of a `.py`
297 extension. So it has been renamed simply into %load. You can look at
296 extension. So it has been renamed simply into %load. You can look at
298 `%load`'s docstring for more info.
297 `%load`'s docstring for more info.
299 """
298 """
300 self.load(arg_s)
299 self.load(arg_s)
301
300
302 @line_magic
301 @line_magic
303 def load(self, arg_s):
302 def load(self, arg_s):
304 """Load code into the current frontend.
303 """Load code into the current frontend.
305
304
306 Usage:\\
305 Usage:\\
307 %load [options] source
306 %load [options] source
308
307
309 where source can be a filename, URL, input history range, macro, or
308 where source can be a filename, URL, input history range, macro, or
310 element in the user namespace
309 element in the user namespace
311
310
312 Options:
311 Options:
313
312
314 -r <lines>: Specify lines or ranges of lines to load from the source.
313 -r <lines>: Specify lines or ranges of lines to load from the source.
315 Ranges could be specified as x-y (x..y) or in python-style x:y
314 Ranges could be specified as x-y (x..y) or in python-style x:y
316 (x..(y-1)). Both limits x and y can be left blank (meaning the
315 (x..(y-1)). Both limits x and y can be left blank (meaning the
317 beginning and end of the file, respectively).
316 beginning and end of the file, respectively).
318
317
319 -s <symbols>: Specify function or classes to load from python source.
318 -s <symbols>: Specify function or classes to load from python source.
320
319
321 -y : Don't ask confirmation for loading source above 200 000 characters.
320 -y : Don't ask confirmation for loading source above 200 000 characters.
322
321
323 -n : Include the user's namespace when searching for source code.
322 -n : Include the user's namespace when searching for source code.
324
323
325 This magic command can either take a local filename, a URL, an history
324 This magic command can either take a local filename, a URL, an history
326 range (see %history) or a macro as argument, it will prompt for
325 range (see %history) or a macro as argument, it will prompt for
327 confirmation before loading source with more than 200 000 characters, unless
326 confirmation before loading source with more than 200 000 characters, unless
328 -y flag is passed or if the frontend does not support raw_input::
327 -y flag is passed or if the frontend does not support raw_input::
329
328
330 %load myscript.py
329 %load myscript.py
331 %load 7-27
330 %load 7-27
332 %load myMacro
331 %load myMacro
333 %load http://www.example.com/myscript.py
332 %load http://www.example.com/myscript.py
334 %load -r 5-10 myscript.py
333 %load -r 5-10 myscript.py
335 %load -r 10-20,30,40: foo.py
334 %load -r 10-20,30,40: foo.py
336 %load -s MyClass,wonder_function myscript.py
335 %load -s MyClass,wonder_function myscript.py
337 %load -n MyClass
336 %load -n MyClass
338 %load -n my_module.wonder_function
337 %load -n my_module.wonder_function
339 """
338 """
340 opts,args = self.parse_options(arg_s,'yns:r:')
339 opts,args = self.parse_options(arg_s,'yns:r:')
341
340
342 if not args:
341 if not args:
343 raise UsageError('Missing filename, URL, input history range, '
342 raise UsageError('Missing filename, URL, input history range, '
344 'macro, or element in the user namespace.')
343 'macro, or element in the user namespace.')
345
344
346 search_ns = 'n' in opts
345 search_ns = 'n' in opts
347
346
348 contents = self.shell.find_user_code(args, search_ns=search_ns)
347 contents = self.shell.find_user_code(args, search_ns=search_ns)
349
348
350 if 's' in opts:
349 if 's' in opts:
351 try:
350 try:
352 blocks, not_found = extract_symbols(contents, opts['s'])
351 blocks, not_found = extract_symbols(contents, opts['s'])
353 except SyntaxError:
352 except SyntaxError:
354 # non python code
353 # non python code
355 error("Unable to parse the input as valid Python code")
354 error("Unable to parse the input as valid Python code")
356 return
355 return
357
356
358 if len(not_found) == 1:
357 if len(not_found) == 1:
359 warn('The symbol `%s` was not found' % not_found[0])
358 warn('The symbol `%s` was not found' % not_found[0])
360 elif len(not_found) > 1:
359 elif len(not_found) > 1:
361 warn('The symbols %s were not found' % get_text_list(not_found,
360 warn('The symbols %s were not found' % get_text_list(not_found,
362 wrap_item_with='`')
361 wrap_item_with='`')
363 )
362 )
364
363
365 contents = '\n'.join(blocks)
364 contents = '\n'.join(blocks)
366
365
367 if 'r' in opts:
366 if 'r' in opts:
368 ranges = opts['r'].replace(',', ' ')
367 ranges = opts['r'].replace(',', ' ')
369 lines = contents.split('\n')
368 lines = contents.split('\n')
370 slices = extract_code_ranges(ranges)
369 slices = extract_code_ranges(ranges)
371 contents = [lines[slice(*slc)] for slc in slices]
370 contents = [lines[slice(*slc)] for slc in slices]
372 contents = '\n'.join(strip_initial_indent(chain.from_iterable(contents)))
371 contents = '\n'.join(strip_initial_indent(chain.from_iterable(contents)))
373
372
374 l = len(contents)
373 l = len(contents)
375
374
376 # 200 000 is ~ 2500 full 80 caracter lines
375 # 200 000 is ~ 2500 full 80 caracter lines
377 # so in average, more than 5000 lines
376 # so in average, more than 5000 lines
378 if l > 200000 and 'y' not in opts:
377 if l > 200000 and 'y' not in opts:
379 try:
378 try:
380 ans = self.shell.ask_yes_no(("The text you're trying to load seems pretty big"\
379 ans = self.shell.ask_yes_no(("The text you're trying to load seems pretty big"\
381 " (%d characters). Continue (y/[N]) ?" % l), default='n' )
380 " (%d characters). Continue (y/[N]) ?" % l), default='n' )
382 except StdinNotImplementedError:
381 except StdinNotImplementedError:
383 #asume yes if raw input not implemented
382 #asume yes if raw input not implemented
384 ans = True
383 ans = True
385
384
386 if ans is False :
385 if ans is False :
387 print('Operation cancelled.')
386 print('Operation cancelled.')
388 return
387 return
389
388
390 contents = "# %load {}\n".format(arg_s) + contents
389 contents = "# %load {}\n".format(arg_s) + contents
391
390
392 self.shell.set_next_input(contents, replace=True)
391 self.shell.set_next_input(contents, replace=True)
393
392
394 @staticmethod
393 @staticmethod
395 def _find_edit_target(shell, args, opts, last_call):
394 def _find_edit_target(shell, args, opts, last_call):
396 """Utility method used by magic_edit to find what to edit."""
395 """Utility method used by magic_edit to find what to edit."""
397
396
398 def make_filename(arg):
397 def make_filename(arg):
399 "Make a filename from the given args"
398 "Make a filename from the given args"
400 try:
399 try:
401 filename = get_py_filename(arg)
400 filename = get_py_filename(arg)
402 except IOError:
401 except IOError:
403 # If it ends with .py but doesn't already exist, assume we want
402 # If it ends with .py but doesn't already exist, assume we want
404 # a new file.
403 # a new file.
405 if arg.endswith('.py'):
404 if arg.endswith('.py'):
406 filename = arg
405 filename = arg
407 else:
406 else:
408 filename = None
407 filename = None
409 return filename
408 return filename
410
409
411 # Set a few locals from the options for convenience:
410 # Set a few locals from the options for convenience:
412 opts_prev = 'p' in opts
411 opts_prev = 'p' in opts
413 opts_raw = 'r' in opts
412 opts_raw = 'r' in opts
414
413
415 # custom exceptions
414 # custom exceptions
416 class DataIsObject(Exception): pass
415 class DataIsObject(Exception): pass
417
416
418 # Default line number value
417 # Default line number value
419 lineno = opts.get('n',None)
418 lineno = opts.get('n',None)
420
419
421 if opts_prev:
420 if opts_prev:
422 args = '_%s' % last_call[0]
421 args = '_%s' % last_call[0]
423 if args not in shell.user_ns:
422 if args not in shell.user_ns:
424 args = last_call[1]
423 args = last_call[1]
425
424
426 # by default this is done with temp files, except when the given
425 # by default this is done with temp files, except when the given
427 # arg is a filename
426 # arg is a filename
428 use_temp = True
427 use_temp = True
429
428
430 data = ''
429 data = ''
431
430
432 # First, see if the arguments should be a filename.
431 # First, see if the arguments should be a filename.
433 filename = make_filename(args)
432 filename = make_filename(args)
434 if filename:
433 if filename:
435 use_temp = False
434 use_temp = False
436 elif args:
435 elif args:
437 # Mode where user specifies ranges of lines, like in %macro.
436 # Mode where user specifies ranges of lines, like in %macro.
438 data = shell.extract_input_lines(args, opts_raw)
437 data = shell.extract_input_lines(args, opts_raw)
439 if not data:
438 if not data:
440 try:
439 try:
441 # Load the parameter given as a variable. If not a string,
440 # Load the parameter given as a variable. If not a string,
442 # process it as an object instead (below)
441 # process it as an object instead (below)
443
442
444 #print '*** args',args,'type',type(args) # dbg
443 #print '*** args',args,'type',type(args) # dbg
445 data = eval(args, shell.user_ns)
444 data = eval(args, shell.user_ns)
446 if not isinstance(data, string_types):
445 if not isinstance(data, str):
447 raise DataIsObject
446 raise DataIsObject
448
447
449 except (NameError,SyntaxError):
448 except (NameError,SyntaxError):
450 # given argument is not a variable, try as a filename
449 # given argument is not a variable, try as a filename
451 filename = make_filename(args)
450 filename = make_filename(args)
452 if filename is None:
451 if filename is None:
453 warn("Argument given (%s) can't be found as a variable "
452 warn("Argument given (%s) can't be found as a variable "
454 "or as a filename." % args)
453 "or as a filename." % args)
455 return (None, None, None)
454 return (None, None, None)
456 use_temp = False
455 use_temp = False
457
456
458 except DataIsObject:
457 except DataIsObject:
459 # macros have a special edit function
458 # macros have a special edit function
460 if isinstance(data, Macro):
459 if isinstance(data, Macro):
461 raise MacroToEdit(data)
460 raise MacroToEdit(data)
462
461
463 # For objects, try to edit the file where they are defined
462 # For objects, try to edit the file where they are defined
464 filename = find_file(data)
463 filename = find_file(data)
465 if filename:
464 if filename:
466 if 'fakemodule' in filename.lower() and \
465 if 'fakemodule' in filename.lower() and \
467 inspect.isclass(data):
466 inspect.isclass(data):
468 # class created by %edit? Try to find source
467 # class created by %edit? Try to find source
469 # by looking for method definitions instead, the
468 # by looking for method definitions instead, the
470 # __module__ in those classes is FakeModule.
469 # __module__ in those classes is FakeModule.
471 attrs = [getattr(data, aname) for aname in dir(data)]
470 attrs = [getattr(data, aname) for aname in dir(data)]
472 for attr in attrs:
471 for attr in attrs:
473 if not inspect.ismethod(attr):
472 if not inspect.ismethod(attr):
474 continue
473 continue
475 filename = find_file(attr)
474 filename = find_file(attr)
476 if filename and \
475 if filename and \
477 'fakemodule' not in filename.lower():
476 'fakemodule' not in filename.lower():
478 # change the attribute to be the edit
477 # change the attribute to be the edit
479 # target instead
478 # target instead
480 data = attr
479 data = attr
481 break
480 break
482
481
483 m = ipython_input_pat.match(os.path.basename(filename))
482 m = ipython_input_pat.match(os.path.basename(filename))
484 if m:
483 if m:
485 raise InteractivelyDefined(int(m.groups()[0]))
484 raise InteractivelyDefined(int(m.groups()[0]))
486
485
487 datafile = 1
486 datafile = 1
488 if filename is None:
487 if filename is None:
489 filename = make_filename(args)
488 filename = make_filename(args)
490 datafile = 1
489 datafile = 1
491 if filename is not None:
490 if filename is not None:
492 # only warn about this if we get a real name
491 # only warn about this if we get a real name
493 warn('Could not find file where `%s` is defined.\n'
492 warn('Could not find file where `%s` is defined.\n'
494 'Opening a file named `%s`' % (args, filename))
493 'Opening a file named `%s`' % (args, filename))
495 # Now, make sure we can actually read the source (if it was
494 # Now, make sure we can actually read the source (if it was
496 # in a temp file it's gone by now).
495 # in a temp file it's gone by now).
497 if datafile:
496 if datafile:
498 if lineno is None:
497 if lineno is None:
499 lineno = find_source_lines(data)
498 lineno = find_source_lines(data)
500 if lineno is None:
499 if lineno is None:
501 filename = make_filename(args)
500 filename = make_filename(args)
502 if filename is None:
501 if filename is None:
503 warn('The file where `%s` was defined '
502 warn('The file where `%s` was defined '
504 'cannot be read or found.' % data)
503 'cannot be read or found.' % data)
505 return (None, None, None)
504 return (None, None, None)
506 use_temp = False
505 use_temp = False
507
506
508 if use_temp:
507 if use_temp:
509 filename = shell.mktempfile(data)
508 filename = shell.mktempfile(data)
510 print('IPython will make a temporary file named:',filename)
509 print('IPython will make a temporary file named:',filename)
511
510
512 # use last_call to remember the state of the previous call, but don't
511 # use last_call to remember the state of the previous call, but don't
513 # let it be clobbered by successive '-p' calls.
512 # let it be clobbered by successive '-p' calls.
514 try:
513 try:
515 last_call[0] = shell.displayhook.prompt_count
514 last_call[0] = shell.displayhook.prompt_count
516 if not opts_prev:
515 if not opts_prev:
517 last_call[1] = args
516 last_call[1] = args
518 except:
517 except:
519 pass
518 pass
520
519
521
520
522 return filename, lineno, use_temp
521 return filename, lineno, use_temp
523
522
524 def _edit_macro(self,mname,macro):
523 def _edit_macro(self,mname,macro):
525 """open an editor with the macro data in a file"""
524 """open an editor with the macro data in a file"""
526 filename = self.shell.mktempfile(macro.value)
525 filename = self.shell.mktempfile(macro.value)
527 self.shell.hooks.editor(filename)
526 self.shell.hooks.editor(filename)
528
527
529 # and make a new macro object, to replace the old one
528 # and make a new macro object, to replace the old one
530 with open(filename) as mfile:
529 with open(filename) as mfile:
531 mvalue = mfile.read()
530 mvalue = mfile.read()
532 self.shell.user_ns[mname] = Macro(mvalue)
531 self.shell.user_ns[mname] = Macro(mvalue)
533
532
534 @skip_doctest
533 @skip_doctest
535 @line_magic
534 @line_magic
536 def edit(self, parameter_s='',last_call=['','']):
535 def edit(self, parameter_s='',last_call=['','']):
537 """Bring up an editor and execute the resulting code.
536 """Bring up an editor and execute the resulting code.
538
537
539 Usage:
538 Usage:
540 %edit [options] [args]
539 %edit [options] [args]
541
540
542 %edit runs IPython's editor hook. The default version of this hook is
541 %edit runs IPython's editor hook. The default version of this hook is
543 set to call the editor specified by your $EDITOR environment variable.
542 set to call the editor specified by your $EDITOR environment variable.
544 If this isn't found, it will default to vi under Linux/Unix and to
543 If this isn't found, it will default to vi under Linux/Unix and to
545 notepad under Windows. See the end of this docstring for how to change
544 notepad under Windows. See the end of this docstring for how to change
546 the editor hook.
545 the editor hook.
547
546
548 You can also set the value of this editor via the
547 You can also set the value of this editor via the
549 ``TerminalInteractiveShell.editor`` option in your configuration file.
548 ``TerminalInteractiveShell.editor`` option in your configuration file.
550 This is useful if you wish to use a different editor from your typical
549 This is useful if you wish to use a different editor from your typical
551 default with IPython (and for Windows users who typically don't set
550 default with IPython (and for Windows users who typically don't set
552 environment variables).
551 environment variables).
553
552
554 This command allows you to conveniently edit multi-line code right in
553 This command allows you to conveniently edit multi-line code right in
555 your IPython session.
554 your IPython session.
556
555
557 If called without arguments, %edit opens up an empty editor with a
556 If called without arguments, %edit opens up an empty editor with a
558 temporary file and will execute the contents of this file when you
557 temporary file and will execute the contents of this file when you
559 close it (don't forget to save it!).
558 close it (don't forget to save it!).
560
559
561
560
562 Options:
561 Options:
563
562
564 -n <number>: open the editor at a specified line number. By default,
563 -n <number>: open the editor at a specified line number. By default,
565 the IPython editor hook uses the unix syntax 'editor +N filename', but
564 the IPython editor hook uses the unix syntax 'editor +N filename', but
566 you can configure this by providing your own modified hook if your
565 you can configure this by providing your own modified hook if your
567 favorite editor supports line-number specifications with a different
566 favorite editor supports line-number specifications with a different
568 syntax.
567 syntax.
569
568
570 -p: this will call the editor with the same data as the previous time
569 -p: this will call the editor with the same data as the previous time
571 it was used, regardless of how long ago (in your current session) it
570 it was used, regardless of how long ago (in your current session) it
572 was.
571 was.
573
572
574 -r: use 'raw' input. This option only applies to input taken from the
573 -r: use 'raw' input. This option only applies to input taken from the
575 user's history. By default, the 'processed' history is used, so that
574 user's history. By default, the 'processed' history is used, so that
576 magics are loaded in their transformed version to valid Python. If
575 magics are loaded in their transformed version to valid Python. If
577 this option is given, the raw input as typed as the command line is
576 this option is given, the raw input as typed as the command line is
578 used instead. When you exit the editor, it will be executed by
577 used instead. When you exit the editor, it will be executed by
579 IPython's own processor.
578 IPython's own processor.
580
579
581 -x: do not execute the edited code immediately upon exit. This is
580 -x: do not execute the edited code immediately upon exit. This is
582 mainly useful if you are editing programs which need to be called with
581 mainly useful if you are editing programs which need to be called with
583 command line arguments, which you can then do using %run.
582 command line arguments, which you can then do using %run.
584
583
585
584
586 Arguments:
585 Arguments:
587
586
588 If arguments are given, the following possibilities exist:
587 If arguments are given, the following possibilities exist:
589
588
590 - If the argument is a filename, IPython will load that into the
589 - If the argument is a filename, IPython will load that into the
591 editor. It will execute its contents with execfile() when you exit,
590 editor. It will execute its contents with execfile() when you exit,
592 loading any code in the file into your interactive namespace.
591 loading any code in the file into your interactive namespace.
593
592
594 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
593 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
595 The syntax is the same as in the %history magic.
594 The syntax is the same as in the %history magic.
596
595
597 - If the argument is a string variable, its contents are loaded
596 - If the argument is a string variable, its contents are loaded
598 into the editor. You can thus edit any string which contains
597 into the editor. You can thus edit any string which contains
599 python code (including the result of previous edits).
598 python code (including the result of previous edits).
600
599
601 - If the argument is the name of an object (other than a string),
600 - If the argument is the name of an object (other than a string),
602 IPython will try to locate the file where it was defined and open the
601 IPython will try to locate the file where it was defined and open the
603 editor at the point where it is defined. You can use `%edit function`
602 editor at the point where it is defined. You can use `%edit function`
604 to load an editor exactly at the point where 'function' is defined,
603 to load an editor exactly at the point where 'function' is defined,
605 edit it and have the file be executed automatically.
604 edit it and have the file be executed automatically.
606
605
607 - If the object is a macro (see %macro for details), this opens up your
606 - If the object is a macro (see %macro for details), this opens up your
608 specified editor with a temporary file containing the macro's data.
607 specified editor with a temporary file containing the macro's data.
609 Upon exit, the macro is reloaded with the contents of the file.
608 Upon exit, the macro is reloaded with the contents of the file.
610
609
611 Note: opening at an exact line is only supported under Unix, and some
610 Note: opening at an exact line is only supported under Unix, and some
612 editors (like kedit and gedit up to Gnome 2.8) do not understand the
611 editors (like kedit and gedit up to Gnome 2.8) do not understand the
613 '+NUMBER' parameter necessary for this feature. Good editors like
612 '+NUMBER' parameter necessary for this feature. Good editors like
614 (X)Emacs, vi, jed, pico and joe all do.
613 (X)Emacs, vi, jed, pico and joe all do.
615
614
616 After executing your code, %edit will return as output the code you
615 After executing your code, %edit will return as output the code you
617 typed in the editor (except when it was an existing file). This way
616 typed in the editor (except when it was an existing file). This way
618 you can reload the code in further invocations of %edit as a variable,
617 you can reload the code in further invocations of %edit as a variable,
619 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
618 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
620 the output.
619 the output.
621
620
622 Note that %edit is also available through the alias %ed.
621 Note that %edit is also available through the alias %ed.
623
622
624 This is an example of creating a simple function inside the editor and
623 This is an example of creating a simple function inside the editor and
625 then modifying it. First, start up the editor::
624 then modifying it. First, start up the editor::
626
625
627 In [1]: edit
626 In [1]: edit
628 Editing... done. Executing edited code...
627 Editing... done. Executing edited code...
629 Out[1]: 'def foo():\\n print "foo() was defined in an editing
628 Out[1]: 'def foo():\\n print "foo() was defined in an editing
630 session"\\n'
629 session"\\n'
631
630
632 We can then call the function foo()::
631 We can then call the function foo()::
633
632
634 In [2]: foo()
633 In [2]: foo()
635 foo() was defined in an editing session
634 foo() was defined in an editing session
636
635
637 Now we edit foo. IPython automatically loads the editor with the
636 Now we edit foo. IPython automatically loads the editor with the
638 (temporary) file where foo() was previously defined::
637 (temporary) file where foo() was previously defined::
639
638
640 In [3]: edit foo
639 In [3]: edit foo
641 Editing... done. Executing edited code...
640 Editing... done. Executing edited code...
642
641
643 And if we call foo() again we get the modified version::
642 And if we call foo() again we get the modified version::
644
643
645 In [4]: foo()
644 In [4]: foo()
646 foo() has now been changed!
645 foo() has now been changed!
647
646
648 Here is an example of how to edit a code snippet successive
647 Here is an example of how to edit a code snippet successive
649 times. First we call the editor::
648 times. First we call the editor::
650
649
651 In [5]: edit
650 In [5]: edit
652 Editing... done. Executing edited code...
651 Editing... done. Executing edited code...
653 hello
652 hello
654 Out[5]: "print 'hello'\\n"
653 Out[5]: "print 'hello'\\n"
655
654
656 Now we call it again with the previous output (stored in _)::
655 Now we call it again with the previous output (stored in _)::
657
656
658 In [6]: edit _
657 In [6]: edit _
659 Editing... done. Executing edited code...
658 Editing... done. Executing edited code...
660 hello world
659 hello world
661 Out[6]: "print 'hello world'\\n"
660 Out[6]: "print 'hello world'\\n"
662
661
663 Now we call it with the output #8 (stored in _8, also as Out[8])::
662 Now we call it with the output #8 (stored in _8, also as Out[8])::
664
663
665 In [7]: edit _8
664 In [7]: edit _8
666 Editing... done. Executing edited code...
665 Editing... done. Executing edited code...
667 hello again
666 hello again
668 Out[7]: "print 'hello again'\\n"
667 Out[7]: "print 'hello again'\\n"
669
668
670
669
671 Changing the default editor hook:
670 Changing the default editor hook:
672
671
673 If you wish to write your own editor hook, you can put it in a
672 If you wish to write your own editor hook, you can put it in a
674 configuration file which you load at startup time. The default hook
673 configuration file which you load at startup time. The default hook
675 is defined in the IPython.core.hooks module, and you can use that as a
674 is defined in the IPython.core.hooks module, and you can use that as a
676 starting example for further modifications. That file also has
675 starting example for further modifications. That file also has
677 general instructions on how to set a new hook for use once you've
676 general instructions on how to set a new hook for use once you've
678 defined it."""
677 defined it."""
679 opts,args = self.parse_options(parameter_s,'prxn:')
678 opts,args = self.parse_options(parameter_s,'prxn:')
680
679
681 try:
680 try:
682 filename, lineno, is_temp = self._find_edit_target(self.shell,
681 filename, lineno, is_temp = self._find_edit_target(self.shell,
683 args, opts, last_call)
682 args, opts, last_call)
684 except MacroToEdit as e:
683 except MacroToEdit as e:
685 self._edit_macro(args, e.args[0])
684 self._edit_macro(args, e.args[0])
686 return
685 return
687 except InteractivelyDefined as e:
686 except InteractivelyDefined as e:
688 print("Editing In[%i]" % e.index)
687 print("Editing In[%i]" % e.index)
689 args = str(e.index)
688 args = str(e.index)
690 filename, lineno, is_temp = self._find_edit_target(self.shell,
689 filename, lineno, is_temp = self._find_edit_target(self.shell,
691 args, opts, last_call)
690 args, opts, last_call)
692 if filename is None:
691 if filename is None:
693 # nothing was found, warnings have already been issued,
692 # nothing was found, warnings have already been issued,
694 # just give up.
693 # just give up.
695 return
694 return
696
695
697 if is_temp:
696 if is_temp:
698 self._knowntemps.add(filename)
697 self._knowntemps.add(filename)
699 elif (filename in self._knowntemps):
698 elif (filename in self._knowntemps):
700 is_temp = True
699 is_temp = True
701
700
702
701
703 # do actual editing here
702 # do actual editing here
704 print('Editing...', end=' ')
703 print('Editing...', end=' ')
705 sys.stdout.flush()
704 sys.stdout.flush()
706 try:
705 try:
707 # Quote filenames that may have spaces in them
706 # Quote filenames that may have spaces in them
708 if ' ' in filename:
707 if ' ' in filename:
709 filename = "'%s'" % filename
708 filename = "'%s'" % filename
710 self.shell.hooks.editor(filename,lineno)
709 self.shell.hooks.editor(filename,lineno)
711 except TryNext:
710 except TryNext:
712 warn('Could not open editor')
711 warn('Could not open editor')
713 return
712 return
714
713
715 # XXX TODO: should this be generalized for all string vars?
714 # XXX TODO: should this be generalized for all string vars?
716 # For now, this is special-cased to blocks created by cpaste
715 # For now, this is special-cased to blocks created by cpaste
717 if args.strip() == 'pasted_block':
716 if args.strip() == 'pasted_block':
718 with open(filename, 'r') as f:
717 with open(filename, 'r') as f:
719 self.shell.user_ns['pasted_block'] = f.read()
718 self.shell.user_ns['pasted_block'] = f.read()
720
719
721 if 'x' in opts: # -x prevents actual execution
720 if 'x' in opts: # -x prevents actual execution
722 print()
721 print()
723 else:
722 else:
724 print('done. Executing edited code...')
723 print('done. Executing edited code...')
725 with preserve_keys(self.shell.user_ns, '__file__'):
724 with preserve_keys(self.shell.user_ns, '__file__'):
726 if not is_temp:
725 if not is_temp:
727 self.shell.user_ns['__file__'] = filename
726 self.shell.user_ns['__file__'] = filename
728 if 'r' in opts: # Untranslated IPython code
727 if 'r' in opts: # Untranslated IPython code
729 with open(filename, 'r') as f:
728 with open(filename, 'r') as f:
730 source = f.read()
729 source = f.read()
731 self.shell.run_cell(source, store_history=False)
730 self.shell.run_cell(source, store_history=False)
732 else:
731 else:
733 self.shell.safe_execfile(filename, self.shell.user_ns,
732 self.shell.safe_execfile(filename, self.shell.user_ns,
734 self.shell.user_ns)
733 self.shell.user_ns)
735
734
736 if is_temp:
735 if is_temp:
737 try:
736 try:
738 return open(filename).read()
737 return open(filename).read()
739 except IOError as msg:
738 except IOError as msg:
740 if msg.filename == filename:
739 if msg.filename == filename:
741 warn('File not found. Did you forget to save?')
740 warn('File not found. Did you forget to save?')
742 return
741 return
743 else:
742 else:
744 self.shell.showtraceback()
743 self.shell.showtraceback()
@@ -1,1381 +1,1380 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Implementation of execution-related magic functions."""
2 """Implementation of execution-related magic functions."""
3
3
4 # Copyright (c) IPython Development Team.
4 # Copyright (c) IPython Development Team.
5 # Distributed under the terms of the Modified BSD License.
5 # Distributed under the terms of the Modified BSD License.
6
6
7
7
8 import ast
8 import ast
9 import bdb
9 import bdb
10 import gc
10 import gc
11 import itertools
11 import itertools
12 import os
12 import os
13 import sys
13 import sys
14 import time
14 import time
15 import timeit
15 import timeit
16 import math
16 import math
17 from pdb import Restart
17 from pdb import Restart
18
18
19 # cProfile was added in Python2.5
19 # cProfile was added in Python2.5
20 try:
20 try:
21 import cProfile as profile
21 import cProfile as profile
22 import pstats
22 import pstats
23 except ImportError:
23 except ImportError:
24 # profile isn't bundled by default in Debian for license reasons
24 # profile isn't bundled by default in Debian for license reasons
25 try:
25 try:
26 import profile, pstats
26 import profile, pstats
27 except ImportError:
27 except ImportError:
28 profile = pstats = None
28 profile = pstats = None
29
29
30 from IPython.core import oinspect
30 from IPython.core import oinspect
31 from IPython.core import magic_arguments
31 from IPython.core import magic_arguments
32 from IPython.core import page
32 from IPython.core import page
33 from IPython.core.error import UsageError
33 from IPython.core.error import UsageError
34 from IPython.core.macro import Macro
34 from IPython.core.macro import Macro
35 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
35 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
36 line_cell_magic, on_off, needs_local_scope)
36 line_cell_magic, on_off, needs_local_scope)
37 from IPython.testing.skipdoctest import skip_doctest
37 from IPython.testing.skipdoctest import skip_doctest
38 from IPython.utils import py3compat
38 from IPython.utils import py3compat
39 from IPython.utils.py3compat import builtin_mod, iteritems, PY3
39 from IPython.utils.py3compat import builtin_mod, PY3
40 from IPython.utils.contexts import preserve_keys
40 from IPython.utils.contexts import preserve_keys
41 from IPython.utils.capture import capture_output
41 from IPython.utils.capture import capture_output
42 from IPython.utils.ipstruct import Struct
42 from IPython.utils.ipstruct import Struct
43 from IPython.utils.module_paths import find_mod
43 from IPython.utils.module_paths import find_mod
44 from IPython.utils.path import get_py_filename, shellglob
44 from IPython.utils.path import get_py_filename, shellglob
45 from IPython.utils.timing import clock, clock2
45 from IPython.utils.timing import clock, clock2
46 from warnings import warn
46 from warnings import warn
47 from logging import error
47 from logging import error
48
48
49 if PY3:
49 if PY3:
50 from io import StringIO
50 from io import StringIO
51 else:
51 else:
52 from StringIO import StringIO
52 from StringIO import StringIO
53
53
54 #-----------------------------------------------------------------------------
54 #-----------------------------------------------------------------------------
55 # Magic implementation classes
55 # Magic implementation classes
56 #-----------------------------------------------------------------------------
56 #-----------------------------------------------------------------------------
57
57
58
58
59 class TimeitResult(object):
59 class TimeitResult(object):
60 """
60 """
61 Object returned by the timeit magic with info about the run.
61 Object returned by the timeit magic with info about the run.
62
62
63 Contains the following attributes :
63 Contains the following attributes :
64
64
65 loops: (int) number of loops done per measurement
65 loops: (int) number of loops done per measurement
66 repeat: (int) number of times the measurement has been repeated
66 repeat: (int) number of times the measurement has been repeated
67 best: (float) best execution time / number
67 best: (float) best execution time / number
68 all_runs: (list of float) execution time of each run (in s)
68 all_runs: (list of float) execution time of each run (in s)
69 compile_time: (float) time of statement compilation (s)
69 compile_time: (float) time of statement compilation (s)
70
70
71 """
71 """
72 def __init__(self, loops, repeat, best, worst, all_runs, compile_time, precision):
72 def __init__(self, loops, repeat, best, worst, all_runs, compile_time, precision):
73 self.loops = loops
73 self.loops = loops
74 self.repeat = repeat
74 self.repeat = repeat
75 self.best = best
75 self.best = best
76 self.worst = worst
76 self.worst = worst
77 self.all_runs = all_runs
77 self.all_runs = all_runs
78 self.compile_time = compile_time
78 self.compile_time = compile_time
79 self._precision = precision
79 self._precision = precision
80 self.timings = [ dt / self.loops for dt in all_runs]
80 self.timings = [ dt / self.loops for dt in all_runs]
81
81
82 @property
82 @property
83 def average(self):
83 def average(self):
84 return math.fsum(self.timings) / len(self.timings)
84 return math.fsum(self.timings) / len(self.timings)
85
85
86 @property
86 @property
87 def stdev(self):
87 def stdev(self):
88 mean = self.average
88 mean = self.average
89 return (math.fsum([(x - mean) ** 2 for x in self.timings]) / len(self.timings)) ** 0.5
89 return (math.fsum([(x - mean) ** 2 for x in self.timings]) / len(self.timings)) ** 0.5
90
90
91 def __str__(self):
91 def __str__(self):
92 return (u"%s loop%s, average of %d: %s +- %s per loop (using standard deviation)"
92 return (u"%s loop%s, average of %d: %s +- %s per loop (using standard deviation)"
93 % (self.loops,"" if self.loops == 1 else "s", self.repeat,
93 % (self.loops,"" if self.loops == 1 else "s", self.repeat,
94 _format_time(self.average, self._precision),
94 _format_time(self.average, self._precision),
95 _format_time(self.stdev, self._precision)))
95 _format_time(self.stdev, self._precision)))
96
96
97 def _repr_pretty_(self, p , cycle):
97 def _repr_pretty_(self, p , cycle):
98 unic = self.__str__()
98 unic = self.__str__()
99 p.text(u'<TimeitResult : '+unic+u'>')
99 p.text(u'<TimeitResult : '+unic+u'>')
100
100
101
101
102
102
103 class TimeitTemplateFiller(ast.NodeTransformer):
103 class TimeitTemplateFiller(ast.NodeTransformer):
104 """Fill in the AST template for timing execution.
104 """Fill in the AST template for timing execution.
105
105
106 This is quite closely tied to the template definition, which is in
106 This is quite closely tied to the template definition, which is in
107 :meth:`ExecutionMagics.timeit`.
107 :meth:`ExecutionMagics.timeit`.
108 """
108 """
109 def __init__(self, ast_setup, ast_stmt):
109 def __init__(self, ast_setup, ast_stmt):
110 self.ast_setup = ast_setup
110 self.ast_setup = ast_setup
111 self.ast_stmt = ast_stmt
111 self.ast_stmt = ast_stmt
112
112
113 def visit_FunctionDef(self, node):
113 def visit_FunctionDef(self, node):
114 "Fill in the setup statement"
114 "Fill in the setup statement"
115 self.generic_visit(node)
115 self.generic_visit(node)
116 if node.name == "inner":
116 if node.name == "inner":
117 node.body[:1] = self.ast_setup.body
117 node.body[:1] = self.ast_setup.body
118
118
119 return node
119 return node
120
120
121 def visit_For(self, node):
121 def visit_For(self, node):
122 "Fill in the statement to be timed"
122 "Fill in the statement to be timed"
123 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
123 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
124 node.body = self.ast_stmt.body
124 node.body = self.ast_stmt.body
125 return node
125 return node
126
126
127
127
128 class Timer(timeit.Timer):
128 class Timer(timeit.Timer):
129 """Timer class that explicitly uses self.inner
129 """Timer class that explicitly uses self.inner
130
130
131 which is an undocumented implementation detail of CPython,
131 which is an undocumented implementation detail of CPython,
132 not shared by PyPy.
132 not shared by PyPy.
133 """
133 """
134 # Timer.timeit copied from CPython 3.4.2
134 # Timer.timeit copied from CPython 3.4.2
135 def timeit(self, number=timeit.default_number):
135 def timeit(self, number=timeit.default_number):
136 """Time 'number' executions of the main statement.
136 """Time 'number' executions of the main statement.
137
137
138 To be precise, this executes the setup statement once, and
138 To be precise, this executes the setup statement once, and
139 then returns the time it takes to execute the main statement
139 then returns the time it takes to execute the main statement
140 a number of times, as a float measured in seconds. The
140 a number of times, as a float measured in seconds. The
141 argument is the number of times through the loop, defaulting
141 argument is the number of times through the loop, defaulting
142 to one million. The main statement, the setup statement and
142 to one million. The main statement, the setup statement and
143 the timer function to be used are passed to the constructor.
143 the timer function to be used are passed to the constructor.
144 """
144 """
145 it = itertools.repeat(None, number)
145 it = itertools.repeat(None, number)
146 gcold = gc.isenabled()
146 gcold = gc.isenabled()
147 gc.disable()
147 gc.disable()
148 try:
148 try:
149 timing = self.inner(it, self.timer)
149 timing = self.inner(it, self.timer)
150 finally:
150 finally:
151 if gcold:
151 if gcold:
152 gc.enable()
152 gc.enable()
153 return timing
153 return timing
154
154
155
155
156 @magics_class
156 @magics_class
157 class ExecutionMagics(Magics):
157 class ExecutionMagics(Magics):
158 """Magics related to code execution, debugging, profiling, etc.
158 """Magics related to code execution, debugging, profiling, etc.
159
159
160 """
160 """
161
161
162 def __init__(self, shell):
162 def __init__(self, shell):
163 super(ExecutionMagics, self).__init__(shell)
163 super(ExecutionMagics, self).__init__(shell)
164 if profile is None:
164 if profile is None:
165 self.prun = self.profile_missing_notice
165 self.prun = self.profile_missing_notice
166 # Default execution function used to actually run user code.
166 # Default execution function used to actually run user code.
167 self.default_runner = None
167 self.default_runner = None
168
168
169 def profile_missing_notice(self, *args, **kwargs):
169 def profile_missing_notice(self, *args, **kwargs):
170 error("""\
170 error("""\
171 The profile module could not be found. It has been removed from the standard
171 The profile module could not be found. It has been removed from the standard
172 python packages because of its non-free license. To use profiling, install the
172 python packages because of its non-free license. To use profiling, install the
173 python-profiler package from non-free.""")
173 python-profiler package from non-free.""")
174
174
175 @skip_doctest
175 @skip_doctest
176 @line_cell_magic
176 @line_cell_magic
177 def prun(self, parameter_s='', cell=None):
177 def prun(self, parameter_s='', cell=None):
178
178
179 """Run a statement through the python code profiler.
179 """Run a statement through the python code profiler.
180
180
181 Usage, in line mode:
181 Usage, in line mode:
182 %prun [options] statement
182 %prun [options] statement
183
183
184 Usage, in cell mode:
184 Usage, in cell mode:
185 %%prun [options] [statement]
185 %%prun [options] [statement]
186 code...
186 code...
187 code...
187 code...
188
188
189 In cell mode, the additional code lines are appended to the (possibly
189 In cell mode, the additional code lines are appended to the (possibly
190 empty) statement in the first line. Cell mode allows you to easily
190 empty) statement in the first line. Cell mode allows you to easily
191 profile multiline blocks without having to put them in a separate
191 profile multiline blocks without having to put them in a separate
192 function.
192 function.
193
193
194 The given statement (which doesn't require quote marks) is run via the
194 The given statement (which doesn't require quote marks) is run via the
195 python profiler in a manner similar to the profile.run() function.
195 python profiler in a manner similar to the profile.run() function.
196 Namespaces are internally managed to work correctly; profile.run
196 Namespaces are internally managed to work correctly; profile.run
197 cannot be used in IPython because it makes certain assumptions about
197 cannot be used in IPython because it makes certain assumptions about
198 namespaces which do not hold under IPython.
198 namespaces which do not hold under IPython.
199
199
200 Options:
200 Options:
201
201
202 -l <limit>
202 -l <limit>
203 you can place restrictions on what or how much of the
203 you can place restrictions on what or how much of the
204 profile gets printed. The limit value can be:
204 profile gets printed. The limit value can be:
205
205
206 * A string: only information for function names containing this string
206 * A string: only information for function names containing this string
207 is printed.
207 is printed.
208
208
209 * An integer: only these many lines are printed.
209 * An integer: only these many lines are printed.
210
210
211 * A float (between 0 and 1): this fraction of the report is printed
211 * A float (between 0 and 1): this fraction of the report is printed
212 (for example, use a limit of 0.4 to see the topmost 40% only).
212 (for example, use a limit of 0.4 to see the topmost 40% only).
213
213
214 You can combine several limits with repeated use of the option. For
214 You can combine several limits with repeated use of the option. For
215 example, ``-l __init__ -l 5`` will print only the topmost 5 lines of
215 example, ``-l __init__ -l 5`` will print only the topmost 5 lines of
216 information about class constructors.
216 information about class constructors.
217
217
218 -r
218 -r
219 return the pstats.Stats object generated by the profiling. This
219 return the pstats.Stats object generated by the profiling. This
220 object has all the information about the profile in it, and you can
220 object has all the information about the profile in it, and you can
221 later use it for further analysis or in other functions.
221 later use it for further analysis or in other functions.
222
222
223 -s <key>
223 -s <key>
224 sort profile by given key. You can provide more than one key
224 sort profile by given key. You can provide more than one key
225 by using the option several times: '-s key1 -s key2 -s key3...'. The
225 by using the option several times: '-s key1 -s key2 -s key3...'. The
226 default sorting key is 'time'.
226 default sorting key is 'time'.
227
227
228 The following is copied verbatim from the profile documentation
228 The following is copied verbatim from the profile documentation
229 referenced below:
229 referenced below:
230
230
231 When more than one key is provided, additional keys are used as
231 When more than one key is provided, additional keys are used as
232 secondary criteria when the there is equality in all keys selected
232 secondary criteria when the there is equality in all keys selected
233 before them.
233 before them.
234
234
235 Abbreviations can be used for any key names, as long as the
235 Abbreviations can be used for any key names, as long as the
236 abbreviation is unambiguous. The following are the keys currently
236 abbreviation is unambiguous. The following are the keys currently
237 defined:
237 defined:
238
238
239 ============ =====================
239 ============ =====================
240 Valid Arg Meaning
240 Valid Arg Meaning
241 ============ =====================
241 ============ =====================
242 "calls" call count
242 "calls" call count
243 "cumulative" cumulative time
243 "cumulative" cumulative time
244 "file" file name
244 "file" file name
245 "module" file name
245 "module" file name
246 "pcalls" primitive call count
246 "pcalls" primitive call count
247 "line" line number
247 "line" line number
248 "name" function name
248 "name" function name
249 "nfl" name/file/line
249 "nfl" name/file/line
250 "stdname" standard name
250 "stdname" standard name
251 "time" internal time
251 "time" internal time
252 ============ =====================
252 ============ =====================
253
253
254 Note that all sorts on statistics are in descending order (placing
254 Note that all sorts on statistics are in descending order (placing
255 most time consuming items first), where as name, file, and line number
255 most time consuming items first), where as name, file, and line number
256 searches are in ascending order (i.e., alphabetical). The subtle
256 searches are in ascending order (i.e., alphabetical). The subtle
257 distinction between "nfl" and "stdname" is that the standard name is a
257 distinction between "nfl" and "stdname" is that the standard name is a
258 sort of the name as printed, which means that the embedded line
258 sort of the name as printed, which means that the embedded line
259 numbers get compared in an odd way. For example, lines 3, 20, and 40
259 numbers get compared in an odd way. For example, lines 3, 20, and 40
260 would (if the file names were the same) appear in the string order
260 would (if the file names were the same) appear in the string order
261 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
261 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
262 line numbers. In fact, sort_stats("nfl") is the same as
262 line numbers. In fact, sort_stats("nfl") is the same as
263 sort_stats("name", "file", "line").
263 sort_stats("name", "file", "line").
264
264
265 -T <filename>
265 -T <filename>
266 save profile results as shown on screen to a text
266 save profile results as shown on screen to a text
267 file. The profile is still shown on screen.
267 file. The profile is still shown on screen.
268
268
269 -D <filename>
269 -D <filename>
270 save (via dump_stats) profile statistics to given
270 save (via dump_stats) profile statistics to given
271 filename. This data is in a format understood by the pstats module, and
271 filename. This data is in a format understood by the pstats module, and
272 is generated by a call to the dump_stats() method of profile
272 is generated by a call to the dump_stats() method of profile
273 objects. The profile is still shown on screen.
273 objects. The profile is still shown on screen.
274
274
275 -q
275 -q
276 suppress output to the pager. Best used with -T and/or -D above.
276 suppress output to the pager. Best used with -T and/or -D above.
277
277
278 If you want to run complete programs under the profiler's control, use
278 If you want to run complete programs under the profiler's control, use
279 ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts
279 ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts
280 contains profiler specific options as described here.
280 contains profiler specific options as described here.
281
281
282 You can read the complete documentation for the profile module with::
282 You can read the complete documentation for the profile module with::
283
283
284 In [1]: import profile; profile.help()
284 In [1]: import profile; profile.help()
285 """
285 """
286 opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q',
286 opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q',
287 list_all=True, posix=False)
287 list_all=True, posix=False)
288 if cell is not None:
288 if cell is not None:
289 arg_str += '\n' + cell
289 arg_str += '\n' + cell
290 arg_str = self.shell.input_splitter.transform_cell(arg_str)
290 arg_str = self.shell.input_splitter.transform_cell(arg_str)
291 return self._run_with_profiler(arg_str, opts, self.shell.user_ns)
291 return self._run_with_profiler(arg_str, opts, self.shell.user_ns)
292
292
293 def _run_with_profiler(self, code, opts, namespace):
293 def _run_with_profiler(self, code, opts, namespace):
294 """
294 """
295 Run `code` with profiler. Used by ``%prun`` and ``%run -p``.
295 Run `code` with profiler. Used by ``%prun`` and ``%run -p``.
296
296
297 Parameters
297 Parameters
298 ----------
298 ----------
299 code : str
299 code : str
300 Code to be executed.
300 Code to be executed.
301 opts : Struct
301 opts : Struct
302 Options parsed by `self.parse_options`.
302 Options parsed by `self.parse_options`.
303 namespace : dict
303 namespace : dict
304 A dictionary for Python namespace (e.g., `self.shell.user_ns`).
304 A dictionary for Python namespace (e.g., `self.shell.user_ns`).
305
305
306 """
306 """
307
307
308 # Fill default values for unspecified options:
308 # Fill default values for unspecified options:
309 opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
309 opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
310
310
311 prof = profile.Profile()
311 prof = profile.Profile()
312 try:
312 try:
313 prof = prof.runctx(code, namespace, namespace)
313 prof = prof.runctx(code, namespace, namespace)
314 sys_exit = ''
314 sys_exit = ''
315 except SystemExit:
315 except SystemExit:
316 sys_exit = """*** SystemExit exception caught in code being profiled."""
316 sys_exit = """*** SystemExit exception caught in code being profiled."""
317
317
318 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
318 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
319
319
320 lims = opts.l
320 lims = opts.l
321 if lims:
321 if lims:
322 lims = [] # rebuild lims with ints/floats/strings
322 lims = [] # rebuild lims with ints/floats/strings
323 for lim in opts.l:
323 for lim in opts.l:
324 try:
324 try:
325 lims.append(int(lim))
325 lims.append(int(lim))
326 except ValueError:
326 except ValueError:
327 try:
327 try:
328 lims.append(float(lim))
328 lims.append(float(lim))
329 except ValueError:
329 except ValueError:
330 lims.append(lim)
330 lims.append(lim)
331
331
332 # Trap output.
332 # Trap output.
333 stdout_trap = StringIO()
333 stdout_trap = StringIO()
334 stats_stream = stats.stream
334 stats_stream = stats.stream
335 try:
335 try:
336 stats.stream = stdout_trap
336 stats.stream = stdout_trap
337 stats.print_stats(*lims)
337 stats.print_stats(*lims)
338 finally:
338 finally:
339 stats.stream = stats_stream
339 stats.stream = stats_stream
340
340
341 output = stdout_trap.getvalue()
341 output = stdout_trap.getvalue()
342 output = output.rstrip()
342 output = output.rstrip()
343
343
344 if 'q' not in opts:
344 if 'q' not in opts:
345 page.page(output)
345 page.page(output)
346 print(sys_exit, end=' ')
346 print(sys_exit, end=' ')
347
347
348 dump_file = opts.D[0]
348 dump_file = opts.D[0]
349 text_file = opts.T[0]
349 text_file = opts.T[0]
350 if dump_file:
350 if dump_file:
351 prof.dump_stats(dump_file)
351 prof.dump_stats(dump_file)
352 print('\n*** Profile stats marshalled to file',\
352 print('\n*** Profile stats marshalled to file',\
353 repr(dump_file)+'.',sys_exit)
353 repr(dump_file)+'.',sys_exit)
354 if text_file:
354 if text_file:
355 pfile = open(text_file,'w')
355 pfile = open(text_file,'w')
356 pfile.write(output)
356 pfile.write(output)
357 pfile.close()
357 pfile.close()
358 print('\n*** Profile printout saved to text file',\
358 print('\n*** Profile printout saved to text file',\
359 repr(text_file)+'.',sys_exit)
359 repr(text_file)+'.',sys_exit)
360
360
361 if 'r' in opts:
361 if 'r' in opts:
362 return stats
362 return stats
363 else:
363 else:
364 return None
364 return None
365
365
366 @line_magic
366 @line_magic
367 def pdb(self, parameter_s=''):
367 def pdb(self, parameter_s=''):
368 """Control the automatic calling of the pdb interactive debugger.
368 """Control the automatic calling of the pdb interactive debugger.
369
369
370 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
370 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
371 argument it works as a toggle.
371 argument it works as a toggle.
372
372
373 When an exception is triggered, IPython can optionally call the
373 When an exception is triggered, IPython can optionally call the
374 interactive pdb debugger after the traceback printout. %pdb toggles
374 interactive pdb debugger after the traceback printout. %pdb toggles
375 this feature on and off.
375 this feature on and off.
376
376
377 The initial state of this feature is set in your configuration
377 The initial state of this feature is set in your configuration
378 file (the option is ``InteractiveShell.pdb``).
378 file (the option is ``InteractiveShell.pdb``).
379
379
380 If you want to just activate the debugger AFTER an exception has fired,
380 If you want to just activate the debugger AFTER an exception has fired,
381 without having to type '%pdb on' and rerunning your code, you can use
381 without having to type '%pdb on' and rerunning your code, you can use
382 the %debug magic."""
382 the %debug magic."""
383
383
384 par = parameter_s.strip().lower()
384 par = parameter_s.strip().lower()
385
385
386 if par:
386 if par:
387 try:
387 try:
388 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
388 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
389 except KeyError:
389 except KeyError:
390 print ('Incorrect argument. Use on/1, off/0, '
390 print ('Incorrect argument. Use on/1, off/0, '
391 'or nothing for a toggle.')
391 'or nothing for a toggle.')
392 return
392 return
393 else:
393 else:
394 # toggle
394 # toggle
395 new_pdb = not self.shell.call_pdb
395 new_pdb = not self.shell.call_pdb
396
396
397 # set on the shell
397 # set on the shell
398 self.shell.call_pdb = new_pdb
398 self.shell.call_pdb = new_pdb
399 print('Automatic pdb calling has been turned',on_off(new_pdb))
399 print('Automatic pdb calling has been turned',on_off(new_pdb))
400
400
401 @skip_doctest
401 @skip_doctest
402 @magic_arguments.magic_arguments()
402 @magic_arguments.magic_arguments()
403 @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
403 @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
404 help="""
404 help="""
405 Set break point at LINE in FILE.
405 Set break point at LINE in FILE.
406 """
406 """
407 )
407 )
408 @magic_arguments.argument('statement', nargs='*',
408 @magic_arguments.argument('statement', nargs='*',
409 help="""
409 help="""
410 Code to run in debugger.
410 Code to run in debugger.
411 You can omit this in cell magic mode.
411 You can omit this in cell magic mode.
412 """
412 """
413 )
413 )
414 @line_cell_magic
414 @line_cell_magic
415 def debug(self, line='', cell=None):
415 def debug(self, line='', cell=None):
416 """Activate the interactive debugger.
416 """Activate the interactive debugger.
417
417
418 This magic command support two ways of activating debugger.
418 This magic command support two ways of activating debugger.
419 One is to activate debugger before executing code. This way, you
419 One is to activate debugger before executing code. This way, you
420 can set a break point, to step through the code from the point.
420 can set a break point, to step through the code from the point.
421 You can use this mode by giving statements to execute and optionally
421 You can use this mode by giving statements to execute and optionally
422 a breakpoint.
422 a breakpoint.
423
423
424 The other one is to activate debugger in post-mortem mode. You can
424 The other one is to activate debugger in post-mortem mode. You can
425 activate this mode simply running %debug without any argument.
425 activate this mode simply running %debug without any argument.
426 If an exception has just occurred, this lets you inspect its stack
426 If an exception has just occurred, this lets you inspect its stack
427 frames interactively. Note that this will always work only on the last
427 frames interactively. Note that this will always work only on the last
428 traceback that occurred, so you must call this quickly after an
428 traceback that occurred, so you must call this quickly after an
429 exception that you wish to inspect has fired, because if another one
429 exception that you wish to inspect has fired, because if another one
430 occurs, it clobbers the previous one.
430 occurs, it clobbers the previous one.
431
431
432 If you want IPython to automatically do this on every exception, see
432 If you want IPython to automatically do this on every exception, see
433 the %pdb magic for more details.
433 the %pdb magic for more details.
434 """
434 """
435 args = magic_arguments.parse_argstring(self.debug, line)
435 args = magic_arguments.parse_argstring(self.debug, line)
436
436
437 if not (args.breakpoint or args.statement or cell):
437 if not (args.breakpoint or args.statement or cell):
438 self._debug_post_mortem()
438 self._debug_post_mortem()
439 else:
439 else:
440 code = "\n".join(args.statement)
440 code = "\n".join(args.statement)
441 if cell:
441 if cell:
442 code += "\n" + cell
442 code += "\n" + cell
443 self._debug_exec(code, args.breakpoint)
443 self._debug_exec(code, args.breakpoint)
444
444
445 def _debug_post_mortem(self):
445 def _debug_post_mortem(self):
446 self.shell.debugger(force=True)
446 self.shell.debugger(force=True)
447
447
448 def _debug_exec(self, code, breakpoint):
448 def _debug_exec(self, code, breakpoint):
449 if breakpoint:
449 if breakpoint:
450 (filename, bp_line) = breakpoint.rsplit(':', 1)
450 (filename, bp_line) = breakpoint.rsplit(':', 1)
451 bp_line = int(bp_line)
451 bp_line = int(bp_line)
452 else:
452 else:
453 (filename, bp_line) = (None, None)
453 (filename, bp_line) = (None, None)
454 self._run_with_debugger(code, self.shell.user_ns, filename, bp_line)
454 self._run_with_debugger(code, self.shell.user_ns, filename, bp_line)
455
455
456 @line_magic
456 @line_magic
457 def tb(self, s):
457 def tb(self, s):
458 """Print the last traceback with the currently active exception mode.
458 """Print the last traceback with the currently active exception mode.
459
459
460 See %xmode for changing exception reporting modes."""
460 See %xmode for changing exception reporting modes."""
461 self.shell.showtraceback()
461 self.shell.showtraceback()
462
462
463 @skip_doctest
463 @skip_doctest
464 @line_magic
464 @line_magic
465 def run(self, parameter_s='', runner=None,
465 def run(self, parameter_s='', runner=None,
466 file_finder=get_py_filename):
466 file_finder=get_py_filename):
467 """Run the named file inside IPython as a program.
467 """Run the named file inside IPython as a program.
468
468
469 Usage::
469 Usage::
470
470
471 %run [-n -i -e -G]
471 %run [-n -i -e -G]
472 [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
472 [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
473 ( -m mod | file ) [args]
473 ( -m mod | file ) [args]
474
474
475 Parameters after the filename are passed as command-line arguments to
475 Parameters after the filename are passed as command-line arguments to
476 the program (put in sys.argv). Then, control returns to IPython's
476 the program (put in sys.argv). Then, control returns to IPython's
477 prompt.
477 prompt.
478
478
479 This is similar to running at a system prompt ``python file args``,
479 This is similar to running at a system prompt ``python file args``,
480 but with the advantage of giving you IPython's tracebacks, and of
480 but with the advantage of giving you IPython's tracebacks, and of
481 loading all variables into your interactive namespace for further use
481 loading all variables into your interactive namespace for further use
482 (unless -p is used, see below).
482 (unless -p is used, see below).
483
483
484 The file is executed in a namespace initially consisting only of
484 The file is executed in a namespace initially consisting only of
485 ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
485 ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
486 sees its environment as if it were being run as a stand-alone program
486 sees its environment as if it were being run as a stand-alone program
487 (except for sharing global objects such as previously imported
487 (except for sharing global objects such as previously imported
488 modules). But after execution, the IPython interactive namespace gets
488 modules). But after execution, the IPython interactive namespace gets
489 updated with all variables defined in the program (except for __name__
489 updated with all variables defined in the program (except for __name__
490 and sys.argv). This allows for very convenient loading of code for
490 and sys.argv). This allows for very convenient loading of code for
491 interactive work, while giving each program a 'clean sheet' to run in.
491 interactive work, while giving each program a 'clean sheet' to run in.
492
492
493 Arguments are expanded using shell-like glob match. Patterns
493 Arguments are expanded using shell-like glob match. Patterns
494 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
494 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
495 tilde '~' will be expanded into user's home directory. Unlike
495 tilde '~' will be expanded into user's home directory. Unlike
496 real shells, quotation does not suppress expansions. Use
496 real shells, quotation does not suppress expansions. Use
497 *two* back slashes (e.g. ``\\\\*``) to suppress expansions.
497 *two* back slashes (e.g. ``\\\\*``) to suppress expansions.
498 To completely disable these expansions, you can use -G flag.
498 To completely disable these expansions, you can use -G flag.
499
499
500 Options:
500 Options:
501
501
502 -n
502 -n
503 __name__ is NOT set to '__main__', but to the running file's name
503 __name__ is NOT set to '__main__', but to the running file's name
504 without extension (as python does under import). This allows running
504 without extension (as python does under import). This allows running
505 scripts and reloading the definitions in them without calling code
505 scripts and reloading the definitions in them without calling code
506 protected by an ``if __name__ == "__main__"`` clause.
506 protected by an ``if __name__ == "__main__"`` clause.
507
507
508 -i
508 -i
509 run the file in IPython's namespace instead of an empty one. This
509 run the file in IPython's namespace instead of an empty one. This
510 is useful if you are experimenting with code written in a text editor
510 is useful if you are experimenting with code written in a text editor
511 which depends on variables defined interactively.
511 which depends on variables defined interactively.
512
512
513 -e
513 -e
514 ignore sys.exit() calls or SystemExit exceptions in the script
514 ignore sys.exit() calls or SystemExit exceptions in the script
515 being run. This is particularly useful if IPython is being used to
515 being run. This is particularly useful if IPython is being used to
516 run unittests, which always exit with a sys.exit() call. In such
516 run unittests, which always exit with a sys.exit() call. In such
517 cases you are interested in the output of the test results, not in
517 cases you are interested in the output of the test results, not in
518 seeing a traceback of the unittest module.
518 seeing a traceback of the unittest module.
519
519
520 -t
520 -t
521 print timing information at the end of the run. IPython will give
521 print timing information at the end of the run. IPython will give
522 you an estimated CPU time consumption for your script, which under
522 you an estimated CPU time consumption for your script, which under
523 Unix uses the resource module to avoid the wraparound problems of
523 Unix uses the resource module to avoid the wraparound problems of
524 time.clock(). Under Unix, an estimate of time spent on system tasks
524 time.clock(). Under Unix, an estimate of time spent on system tasks
525 is also given (for Windows platforms this is reported as 0.0).
525 is also given (for Windows platforms this is reported as 0.0).
526
526
527 If -t is given, an additional ``-N<N>`` option can be given, where <N>
527 If -t is given, an additional ``-N<N>`` option can be given, where <N>
528 must be an integer indicating how many times you want the script to
528 must be an integer indicating how many times you want the script to
529 run. The final timing report will include total and per run results.
529 run. The final timing report will include total and per run results.
530
530
531 For example (testing the script uniq_stable.py)::
531 For example (testing the script uniq_stable.py)::
532
532
533 In [1]: run -t uniq_stable
533 In [1]: run -t uniq_stable
534
534
535 IPython CPU timings (estimated):
535 IPython CPU timings (estimated):
536 User : 0.19597 s.
536 User : 0.19597 s.
537 System: 0.0 s.
537 System: 0.0 s.
538
538
539 In [2]: run -t -N5 uniq_stable
539 In [2]: run -t -N5 uniq_stable
540
540
541 IPython CPU timings (estimated):
541 IPython CPU timings (estimated):
542 Total runs performed: 5
542 Total runs performed: 5
543 Times : Total Per run
543 Times : Total Per run
544 User : 0.910862 s, 0.1821724 s.
544 User : 0.910862 s, 0.1821724 s.
545 System: 0.0 s, 0.0 s.
545 System: 0.0 s, 0.0 s.
546
546
547 -d
547 -d
548 run your program under the control of pdb, the Python debugger.
548 run your program under the control of pdb, the Python debugger.
549 This allows you to execute your program step by step, watch variables,
549 This allows you to execute your program step by step, watch variables,
550 etc. Internally, what IPython does is similar to calling::
550 etc. Internally, what IPython does is similar to calling::
551
551
552 pdb.run('execfile("YOURFILENAME")')
552 pdb.run('execfile("YOURFILENAME")')
553
553
554 with a breakpoint set on line 1 of your file. You can change the line
554 with a breakpoint set on line 1 of your file. You can change the line
555 number for this automatic breakpoint to be <N> by using the -bN option
555 number for this automatic breakpoint to be <N> by using the -bN option
556 (where N must be an integer). For example::
556 (where N must be an integer). For example::
557
557
558 %run -d -b40 myscript
558 %run -d -b40 myscript
559
559
560 will set the first breakpoint at line 40 in myscript.py. Note that
560 will set the first breakpoint at line 40 in myscript.py. Note that
561 the first breakpoint must be set on a line which actually does
561 the first breakpoint must be set on a line which actually does
562 something (not a comment or docstring) for it to stop execution.
562 something (not a comment or docstring) for it to stop execution.
563
563
564 Or you can specify a breakpoint in a different file::
564 Or you can specify a breakpoint in a different file::
565
565
566 %run -d -b myotherfile.py:20 myscript
566 %run -d -b myotherfile.py:20 myscript
567
567
568 When the pdb debugger starts, you will see a (Pdb) prompt. You must
568 When the pdb debugger starts, you will see a (Pdb) prompt. You must
569 first enter 'c' (without quotes) to start execution up to the first
569 first enter 'c' (without quotes) to start execution up to the first
570 breakpoint.
570 breakpoint.
571
571
572 Entering 'help' gives information about the use of the debugger. You
572 Entering 'help' gives information about the use of the debugger. You
573 can easily see pdb's full documentation with "import pdb;pdb.help()"
573 can easily see pdb's full documentation with "import pdb;pdb.help()"
574 at a prompt.
574 at a prompt.
575
575
576 -p
576 -p
577 run program under the control of the Python profiler module (which
577 run program under the control of the Python profiler module (which
578 prints a detailed report of execution times, function calls, etc).
578 prints a detailed report of execution times, function calls, etc).
579
579
580 You can pass other options after -p which affect the behavior of the
580 You can pass other options after -p which affect the behavior of the
581 profiler itself. See the docs for %prun for details.
581 profiler itself. See the docs for %prun for details.
582
582
583 In this mode, the program's variables do NOT propagate back to the
583 In this mode, the program's variables do NOT propagate back to the
584 IPython interactive namespace (because they remain in the namespace
584 IPython interactive namespace (because they remain in the namespace
585 where the profiler executes them).
585 where the profiler executes them).
586
586
587 Internally this triggers a call to %prun, see its documentation for
587 Internally this triggers a call to %prun, see its documentation for
588 details on the options available specifically for profiling.
588 details on the options available specifically for profiling.
589
589
590 There is one special usage for which the text above doesn't apply:
590 There is one special usage for which the text above doesn't apply:
591 if the filename ends with .ipy[nb], the file is run as ipython script,
591 if the filename ends with .ipy[nb], the file is run as ipython script,
592 just as if the commands were written on IPython prompt.
592 just as if the commands were written on IPython prompt.
593
593
594 -m
594 -m
595 specify module name to load instead of script path. Similar to
595 specify module name to load instead of script path. Similar to
596 the -m option for the python interpreter. Use this option last if you
596 the -m option for the python interpreter. Use this option last if you
597 want to combine with other %run options. Unlike the python interpreter
597 want to combine with other %run options. Unlike the python interpreter
598 only source modules are allowed no .pyc or .pyo files.
598 only source modules are allowed no .pyc or .pyo files.
599 For example::
599 For example::
600
600
601 %run -m example
601 %run -m example
602
602
603 will run the example module.
603 will run the example module.
604
604
605 -G
605 -G
606 disable shell-like glob expansion of arguments.
606 disable shell-like glob expansion of arguments.
607
607
608 """
608 """
609
609
610 # get arguments and set sys.argv for program to be run.
610 # get arguments and set sys.argv for program to be run.
611 opts, arg_lst = self.parse_options(parameter_s,
611 opts, arg_lst = self.parse_options(parameter_s,
612 'nidtN:b:pD:l:rs:T:em:G',
612 'nidtN:b:pD:l:rs:T:em:G',
613 mode='list', list_all=1)
613 mode='list', list_all=1)
614 if "m" in opts:
614 if "m" in opts:
615 modulename = opts["m"][0]
615 modulename = opts["m"][0]
616 modpath = find_mod(modulename)
616 modpath = find_mod(modulename)
617 if modpath is None:
617 if modpath is None:
618 warn('%r is not a valid modulename on sys.path'%modulename)
618 warn('%r is not a valid modulename on sys.path'%modulename)
619 return
619 return
620 arg_lst = [modpath] + arg_lst
620 arg_lst = [modpath] + arg_lst
621 try:
621 try:
622 filename = file_finder(arg_lst[0])
622 filename = file_finder(arg_lst[0])
623 except IndexError:
623 except IndexError:
624 warn('you must provide at least a filename.')
624 warn('you must provide at least a filename.')
625 print('\n%run:\n', oinspect.getdoc(self.run))
625 print('\n%run:\n', oinspect.getdoc(self.run))
626 return
626 return
627 except IOError as e:
627 except IOError as e:
628 try:
628 try:
629 msg = str(e)
629 msg = str(e)
630 except UnicodeError:
630 except UnicodeError:
631 msg = e.message
631 msg = e.message
632 error(msg)
632 error(msg)
633 return
633 return
634
634
635 if filename.lower().endswith(('.ipy', '.ipynb')):
635 if filename.lower().endswith(('.ipy', '.ipynb')):
636 with preserve_keys(self.shell.user_ns, '__file__'):
636 with preserve_keys(self.shell.user_ns, '__file__'):
637 self.shell.user_ns['__file__'] = filename
637 self.shell.user_ns['__file__'] = filename
638 self.shell.safe_execfile_ipy(filename)
638 self.shell.safe_execfile_ipy(filename)
639 return
639 return
640
640
641 # Control the response to exit() calls made by the script being run
641 # Control the response to exit() calls made by the script being run
642 exit_ignore = 'e' in opts
642 exit_ignore = 'e' in opts
643
643
644 # Make sure that the running script gets a proper sys.argv as if it
644 # Make sure that the running script gets a proper sys.argv as if it
645 # were run from a system shell.
645 # were run from a system shell.
646 save_argv = sys.argv # save it for later restoring
646 save_argv = sys.argv # save it for later restoring
647
647
648 if 'G' in opts:
648 if 'G' in opts:
649 args = arg_lst[1:]
649 args = arg_lst[1:]
650 else:
650 else:
651 # tilde and glob expansion
651 # tilde and glob expansion
652 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
652 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
653
653
654 sys.argv = [filename] + args # put in the proper filename
654 sys.argv = [filename] + args # put in the proper filename
655 # protect sys.argv from potential unicode strings on Python 2:
655 # protect sys.argv from potential unicode strings on Python 2:
656 if not py3compat.PY3:
656 if not py3compat.PY3:
657 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
657 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
658
658
659 if 'i' in opts:
659 if 'i' in opts:
660 # Run in user's interactive namespace
660 # Run in user's interactive namespace
661 prog_ns = self.shell.user_ns
661 prog_ns = self.shell.user_ns
662 __name__save = self.shell.user_ns['__name__']
662 __name__save = self.shell.user_ns['__name__']
663 prog_ns['__name__'] = '__main__'
663 prog_ns['__name__'] = '__main__'
664 main_mod = self.shell.user_module
664 main_mod = self.shell.user_module
665
665
666 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
666 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
667 # set the __file__ global in the script's namespace
667 # set the __file__ global in the script's namespace
668 # TK: Is this necessary in interactive mode?
668 # TK: Is this necessary in interactive mode?
669 prog_ns['__file__'] = filename
669 prog_ns['__file__'] = filename
670 else:
670 else:
671 # Run in a fresh, empty namespace
671 # Run in a fresh, empty namespace
672 if 'n' in opts:
672 if 'n' in opts:
673 name = os.path.splitext(os.path.basename(filename))[0]
673 name = os.path.splitext(os.path.basename(filename))[0]
674 else:
674 else:
675 name = '__main__'
675 name = '__main__'
676
676
677 # The shell MUST hold a reference to prog_ns so after %run
677 # The shell MUST hold a reference to prog_ns so after %run
678 # exits, the python deletion mechanism doesn't zero it out
678 # exits, the python deletion mechanism doesn't zero it out
679 # (leaving dangling references). See interactiveshell for details
679 # (leaving dangling references). See interactiveshell for details
680 main_mod = self.shell.new_main_mod(filename, name)
680 main_mod = self.shell.new_main_mod(filename, name)
681 prog_ns = main_mod.__dict__
681 prog_ns = main_mod.__dict__
682
682
683 # pickle fix. See interactiveshell for an explanation. But we need to
683 # pickle fix. See interactiveshell for an explanation. But we need to
684 # make sure that, if we overwrite __main__, we replace it at the end
684 # make sure that, if we overwrite __main__, we replace it at the end
685 main_mod_name = prog_ns['__name__']
685 main_mod_name = prog_ns['__name__']
686
686
687 if main_mod_name == '__main__':
687 if main_mod_name == '__main__':
688 restore_main = sys.modules['__main__']
688 restore_main = sys.modules['__main__']
689 else:
689 else:
690 restore_main = False
690 restore_main = False
691
691
692 # This needs to be undone at the end to prevent holding references to
692 # This needs to be undone at the end to prevent holding references to
693 # every single object ever created.
693 # every single object ever created.
694 sys.modules[main_mod_name] = main_mod
694 sys.modules[main_mod_name] = main_mod
695
695
696 if 'p' in opts or 'd' in opts:
696 if 'p' in opts or 'd' in opts:
697 if 'm' in opts:
697 if 'm' in opts:
698 code = 'run_module(modulename, prog_ns)'
698 code = 'run_module(modulename, prog_ns)'
699 code_ns = {
699 code_ns = {
700 'run_module': self.shell.safe_run_module,
700 'run_module': self.shell.safe_run_module,
701 'prog_ns': prog_ns,
701 'prog_ns': prog_ns,
702 'modulename': modulename,
702 'modulename': modulename,
703 }
703 }
704 else:
704 else:
705 if 'd' in opts:
705 if 'd' in opts:
706 # allow exceptions to raise in debug mode
706 # allow exceptions to raise in debug mode
707 code = 'execfile(filename, prog_ns, raise_exceptions=True)'
707 code = 'execfile(filename, prog_ns, raise_exceptions=True)'
708 else:
708 else:
709 code = 'execfile(filename, prog_ns)'
709 code = 'execfile(filename, prog_ns)'
710 code_ns = {
710 code_ns = {
711 'execfile': self.shell.safe_execfile,
711 'execfile': self.shell.safe_execfile,
712 'prog_ns': prog_ns,
712 'prog_ns': prog_ns,
713 'filename': get_py_filename(filename),
713 'filename': get_py_filename(filename),
714 }
714 }
715
715
716 try:
716 try:
717 stats = None
717 stats = None
718 if 'p' in opts:
718 if 'p' in opts:
719 stats = self._run_with_profiler(code, opts, code_ns)
719 stats = self._run_with_profiler(code, opts, code_ns)
720 else:
720 else:
721 if 'd' in opts:
721 if 'd' in opts:
722 bp_file, bp_line = parse_breakpoint(
722 bp_file, bp_line = parse_breakpoint(
723 opts.get('b', ['1'])[0], filename)
723 opts.get('b', ['1'])[0], filename)
724 self._run_with_debugger(
724 self._run_with_debugger(
725 code, code_ns, filename, bp_line, bp_file)
725 code, code_ns, filename, bp_line, bp_file)
726 else:
726 else:
727 if 'm' in opts:
727 if 'm' in opts:
728 def run():
728 def run():
729 self.shell.safe_run_module(modulename, prog_ns)
729 self.shell.safe_run_module(modulename, prog_ns)
730 else:
730 else:
731 if runner is None:
731 if runner is None:
732 runner = self.default_runner
732 runner = self.default_runner
733 if runner is None:
733 if runner is None:
734 runner = self.shell.safe_execfile
734 runner = self.shell.safe_execfile
735
735
736 def run():
736 def run():
737 runner(filename, prog_ns, prog_ns,
737 runner(filename, prog_ns, prog_ns,
738 exit_ignore=exit_ignore)
738 exit_ignore=exit_ignore)
739
739
740 if 't' in opts:
740 if 't' in opts:
741 # timed execution
741 # timed execution
742 try:
742 try:
743 nruns = int(opts['N'][0])
743 nruns = int(opts['N'][0])
744 if nruns < 1:
744 if nruns < 1:
745 error('Number of runs must be >=1')
745 error('Number of runs must be >=1')
746 return
746 return
747 except (KeyError):
747 except (KeyError):
748 nruns = 1
748 nruns = 1
749 self._run_with_timing(run, nruns)
749 self._run_with_timing(run, nruns)
750 else:
750 else:
751 # regular execution
751 # regular execution
752 run()
752 run()
753
753
754 if 'i' in opts:
754 if 'i' in opts:
755 self.shell.user_ns['__name__'] = __name__save
755 self.shell.user_ns['__name__'] = __name__save
756 else:
756 else:
757 # update IPython interactive namespace
757 # update IPython interactive namespace
758
758
759 # Some forms of read errors on the file may mean the
759 # Some forms of read errors on the file may mean the
760 # __name__ key was never set; using pop we don't have to
760 # __name__ key was never set; using pop we don't have to
761 # worry about a possible KeyError.
761 # worry about a possible KeyError.
762 prog_ns.pop('__name__', None)
762 prog_ns.pop('__name__', None)
763
763
764 with preserve_keys(self.shell.user_ns, '__file__'):
764 with preserve_keys(self.shell.user_ns, '__file__'):
765 self.shell.user_ns.update(prog_ns)
765 self.shell.user_ns.update(prog_ns)
766 finally:
766 finally:
767 # It's a bit of a mystery why, but __builtins__ can change from
767 # It's a bit of a mystery why, but __builtins__ can change from
768 # being a module to becoming a dict missing some key data after
768 # being a module to becoming a dict missing some key data after
769 # %run. As best I can see, this is NOT something IPython is doing
769 # %run. As best I can see, this is NOT something IPython is doing
770 # at all, and similar problems have been reported before:
770 # at all, and similar problems have been reported before:
771 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
771 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
772 # Since this seems to be done by the interpreter itself, the best
772 # Since this seems to be done by the interpreter itself, the best
773 # we can do is to at least restore __builtins__ for the user on
773 # we can do is to at least restore __builtins__ for the user on
774 # exit.
774 # exit.
775 self.shell.user_ns['__builtins__'] = builtin_mod
775 self.shell.user_ns['__builtins__'] = builtin_mod
776
776
777 # Ensure key global structures are restored
777 # Ensure key global structures are restored
778 sys.argv = save_argv
778 sys.argv = save_argv
779 if restore_main:
779 if restore_main:
780 sys.modules['__main__'] = restore_main
780 sys.modules['__main__'] = restore_main
781 else:
781 else:
782 # Remove from sys.modules the reference to main_mod we'd
782 # Remove from sys.modules the reference to main_mod we'd
783 # added. Otherwise it will trap references to objects
783 # added. Otherwise it will trap references to objects
784 # contained therein.
784 # contained therein.
785 del sys.modules[main_mod_name]
785 del sys.modules[main_mod_name]
786
786
787 return stats
787 return stats
788
788
789 def _run_with_debugger(self, code, code_ns, filename=None,
789 def _run_with_debugger(self, code, code_ns, filename=None,
790 bp_line=None, bp_file=None):
790 bp_line=None, bp_file=None):
791 """
791 """
792 Run `code` in debugger with a break point.
792 Run `code` in debugger with a break point.
793
793
794 Parameters
794 Parameters
795 ----------
795 ----------
796 code : str
796 code : str
797 Code to execute.
797 Code to execute.
798 code_ns : dict
798 code_ns : dict
799 A namespace in which `code` is executed.
799 A namespace in which `code` is executed.
800 filename : str
800 filename : str
801 `code` is ran as if it is in `filename`.
801 `code` is ran as if it is in `filename`.
802 bp_line : int, optional
802 bp_line : int, optional
803 Line number of the break point.
803 Line number of the break point.
804 bp_file : str, optional
804 bp_file : str, optional
805 Path to the file in which break point is specified.
805 Path to the file in which break point is specified.
806 `filename` is used if not given.
806 `filename` is used if not given.
807
807
808 Raises
808 Raises
809 ------
809 ------
810 UsageError
810 UsageError
811 If the break point given by `bp_line` is not valid.
811 If the break point given by `bp_line` is not valid.
812
812
813 """
813 """
814 deb = self.shell.InteractiveTB.pdb
814 deb = self.shell.InteractiveTB.pdb
815 if not deb:
815 if not deb:
816 self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls()
816 self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls()
817 deb = self.shell.InteractiveTB.pdb
817 deb = self.shell.InteractiveTB.pdb
818
818
819 # deb.checkline() fails if deb.curframe exists but is None; it can
819 # deb.checkline() fails if deb.curframe exists but is None; it can
820 # handle it not existing. https://github.com/ipython/ipython/issues/10028
820 # handle it not existing. https://github.com/ipython/ipython/issues/10028
821 if hasattr(deb, 'curframe'):
821 if hasattr(deb, 'curframe'):
822 del deb.curframe
822 del deb.curframe
823
823
824 # reset Breakpoint state, which is moronically kept
824 # reset Breakpoint state, which is moronically kept
825 # in a class
825 # in a class
826 bdb.Breakpoint.next = 1
826 bdb.Breakpoint.next = 1
827 bdb.Breakpoint.bplist = {}
827 bdb.Breakpoint.bplist = {}
828 bdb.Breakpoint.bpbynumber = [None]
828 bdb.Breakpoint.bpbynumber = [None]
829 if bp_line is not None:
829 if bp_line is not None:
830 # Set an initial breakpoint to stop execution
830 # Set an initial breakpoint to stop execution
831 maxtries = 10
831 maxtries = 10
832 bp_file = bp_file or filename
832 bp_file = bp_file or filename
833 checkline = deb.checkline(bp_file, bp_line)
833 checkline = deb.checkline(bp_file, bp_line)
834 if not checkline:
834 if not checkline:
835 for bp in range(bp_line + 1, bp_line + maxtries + 1):
835 for bp in range(bp_line + 1, bp_line + maxtries + 1):
836 if deb.checkline(bp_file, bp):
836 if deb.checkline(bp_file, bp):
837 break
837 break
838 else:
838 else:
839 msg = ("\nI failed to find a valid line to set "
839 msg = ("\nI failed to find a valid line to set "
840 "a breakpoint\n"
840 "a breakpoint\n"
841 "after trying up to line: %s.\n"
841 "after trying up to line: %s.\n"
842 "Please set a valid breakpoint manually "
842 "Please set a valid breakpoint manually "
843 "with the -b option." % bp)
843 "with the -b option." % bp)
844 raise UsageError(msg)
844 raise UsageError(msg)
845 # if we find a good linenumber, set the breakpoint
845 # if we find a good linenumber, set the breakpoint
846 deb.do_break('%s:%s' % (bp_file, bp_line))
846 deb.do_break('%s:%s' % (bp_file, bp_line))
847
847
848 if filename:
848 if filename:
849 # Mimic Pdb._runscript(...)
849 # Mimic Pdb._runscript(...)
850 deb._wait_for_mainpyfile = True
850 deb._wait_for_mainpyfile = True
851 deb.mainpyfile = deb.canonic(filename)
851 deb.mainpyfile = deb.canonic(filename)
852
852
853 # Start file run
853 # Start file run
854 print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
854 print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
855 try:
855 try:
856 if filename:
856 if filename:
857 # save filename so it can be used by methods on the deb object
857 # save filename so it can be used by methods on the deb object
858 deb._exec_filename = filename
858 deb._exec_filename = filename
859 while True:
859 while True:
860 try:
860 try:
861 deb.run(code, code_ns)
861 deb.run(code, code_ns)
862 except Restart:
862 except Restart:
863 print("Restarting")
863 print("Restarting")
864 if filename:
864 if filename:
865 deb._wait_for_mainpyfile = True
865 deb._wait_for_mainpyfile = True
866 deb.mainpyfile = deb.canonic(filename)
866 deb.mainpyfile = deb.canonic(filename)
867 continue
867 continue
868 else:
868 else:
869 break
869 break
870
870
871
871
872 except:
872 except:
873 etype, value, tb = sys.exc_info()
873 etype, value, tb = sys.exc_info()
874 # Skip three frames in the traceback: the %run one,
874 # Skip three frames in the traceback: the %run one,
875 # one inside bdb.py, and the command-line typed by the
875 # one inside bdb.py, and the command-line typed by the
876 # user (run by exec in pdb itself).
876 # user (run by exec in pdb itself).
877 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
877 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
878
878
879 @staticmethod
879 @staticmethod
880 def _run_with_timing(run, nruns):
880 def _run_with_timing(run, nruns):
881 """
881 """
882 Run function `run` and print timing information.
882 Run function `run` and print timing information.
883
883
884 Parameters
884 Parameters
885 ----------
885 ----------
886 run : callable
886 run : callable
887 Any callable object which takes no argument.
887 Any callable object which takes no argument.
888 nruns : int
888 nruns : int
889 Number of times to execute `run`.
889 Number of times to execute `run`.
890
890
891 """
891 """
892 twall0 = time.time()
892 twall0 = time.time()
893 if nruns == 1:
893 if nruns == 1:
894 t0 = clock2()
894 t0 = clock2()
895 run()
895 run()
896 t1 = clock2()
896 t1 = clock2()
897 t_usr = t1[0] - t0[0]
897 t_usr = t1[0] - t0[0]
898 t_sys = t1[1] - t0[1]
898 t_sys = t1[1] - t0[1]
899 print("\nIPython CPU timings (estimated):")
899 print("\nIPython CPU timings (estimated):")
900 print(" User : %10.2f s." % t_usr)
900 print(" User : %10.2f s." % t_usr)
901 print(" System : %10.2f s." % t_sys)
901 print(" System : %10.2f s." % t_sys)
902 else:
902 else:
903 runs = range(nruns)
903 runs = range(nruns)
904 t0 = clock2()
904 t0 = clock2()
905 for nr in runs:
905 for nr in runs:
906 run()
906 run()
907 t1 = clock2()
907 t1 = clock2()
908 t_usr = t1[0] - t0[0]
908 t_usr = t1[0] - t0[0]
909 t_sys = t1[1] - t0[1]
909 t_sys = t1[1] - t0[1]
910 print("\nIPython CPU timings (estimated):")
910 print("\nIPython CPU timings (estimated):")
911 print("Total runs performed:", nruns)
911 print("Total runs performed:", nruns)
912 print(" Times : %10s %10s" % ('Total', 'Per run'))
912 print(" Times : %10s %10s" % ('Total', 'Per run'))
913 print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns))
913 print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns))
914 print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns))
914 print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns))
915 twall1 = time.time()
915 twall1 = time.time()
916 print("Wall time: %10.2f s." % (twall1 - twall0))
916 print("Wall time: %10.2f s." % (twall1 - twall0))
917
917
918 @skip_doctest
918 @skip_doctest
919 @line_cell_magic
919 @line_cell_magic
920 def timeit(self, line='', cell=None):
920 def timeit(self, line='', cell=None):
921 """Time execution of a Python statement or expression
921 """Time execution of a Python statement or expression
922
922
923 Usage, in line mode:
923 Usage, in line mode:
924 %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
924 %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
925 or in cell mode:
925 or in cell mode:
926 %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
926 %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
927 code
927 code
928 code...
928 code...
929
929
930 Time execution of a Python statement or expression using the timeit
930 Time execution of a Python statement or expression using the timeit
931 module. This function can be used both as a line and cell magic:
931 module. This function can be used both as a line and cell magic:
932
932
933 - In line mode you can time a single-line statement (though multiple
933 - In line mode you can time a single-line statement (though multiple
934 ones can be chained with using semicolons).
934 ones can be chained with using semicolons).
935
935
936 - In cell mode, the statement in the first line is used as setup code
936 - In cell mode, the statement in the first line is used as setup code
937 (executed but not timed) and the body of the cell is timed. The cell
937 (executed but not timed) and the body of the cell is timed. The cell
938 body has access to any variables created in the setup code.
938 body has access to any variables created in the setup code.
939
939
940 Options:
940 Options:
941 -n<N>: execute the given statement <N> times in a loop. If this value
941 -n<N>: execute the given statement <N> times in a loop. If this value
942 is not given, a fitting value is chosen.
942 is not given, a fitting value is chosen.
943
943
944 -r<R>: repeat the loop iteration <R> times and take the best result.
944 -r<R>: repeat the loop iteration <R> times and take the best result.
945 Default: 3
945 Default: 3
946
946
947 -t: use time.time to measure the time, which is the default on Unix.
947 -t: use time.time to measure the time, which is the default on Unix.
948 This function measures wall time.
948 This function measures wall time.
949
949
950 -c: use time.clock to measure the time, which is the default on
950 -c: use time.clock to measure the time, which is the default on
951 Windows and measures wall time. On Unix, resource.getrusage is used
951 Windows and measures wall time. On Unix, resource.getrusage is used
952 instead and returns the CPU user time.
952 instead and returns the CPU user time.
953
953
954 -p<P>: use a precision of <P> digits to display the timing result.
954 -p<P>: use a precision of <P> digits to display the timing result.
955 Default: 3
955 Default: 3
956
956
957 -q: Quiet, do not print result.
957 -q: Quiet, do not print result.
958
958
959 -o: return a TimeitResult that can be stored in a variable to inspect
959 -o: return a TimeitResult that can be stored in a variable to inspect
960 the result in more details.
960 the result in more details.
961
961
962
962
963 Examples
963 Examples
964 --------
964 --------
965 ::
965 ::
966
966
967 In [1]: %timeit pass
967 In [1]: %timeit pass
968 100000000 loops, average of 7: 5.48 ns +- 0.354 ns per loop (using standard deviation)
968 100000000 loops, average of 7: 5.48 ns +- 0.354 ns per loop (using standard deviation)
969
969
970 In [2]: u = None
970 In [2]: u = None
971
971
972 In [3]: %timeit u is None
972 In [3]: %timeit u is None
973 10000000 loops, average of 7: 22.7 ns +- 2.33 ns per loop (using standard deviation)
973 10000000 loops, average of 7: 22.7 ns +- 2.33 ns per loop (using standard deviation)
974
974
975 In [4]: %timeit -r 4 u == None
975 In [4]: %timeit -r 4 u == None
976 10000000 loops, average of 4: 27.5 ns +- 2.91 ns per loop (using standard deviation)
976 10000000 loops, average of 4: 27.5 ns +- 2.91 ns per loop (using standard deviation)
977
977
978 In [5]: import time
978 In [5]: import time
979
979
980 In [6]: %timeit -n1 time.sleep(2)
980 In [6]: %timeit -n1 time.sleep(2)
981 1 loop, average of 7: 2 s +- 4.71 µs per loop (using standard deviation)
981 1 loop, average of 7: 2 s +- 4.71 µs per loop (using standard deviation)
982
982
983
983
984 The times reported by %timeit will be slightly higher than those
984 The times reported by %timeit will be slightly higher than those
985 reported by the timeit.py script when variables are accessed. This is
985 reported by the timeit.py script when variables are accessed. This is
986 due to the fact that %timeit executes the statement in the namespace
986 due to the fact that %timeit executes the statement in the namespace
987 of the shell, compared with timeit.py, which uses a single setup
987 of the shell, compared with timeit.py, which uses a single setup
988 statement to import function or create variables. Generally, the bias
988 statement to import function or create variables. Generally, the bias
989 does not matter as long as results from timeit.py are not mixed with
989 does not matter as long as results from timeit.py are not mixed with
990 those from %timeit."""
990 those from %timeit."""
991
991
992 opts, stmt = self.parse_options(line,'n:r:tcp:qo',
992 opts, stmt = self.parse_options(line,'n:r:tcp:qo',
993 posix=False, strict=False)
993 posix=False, strict=False)
994 if stmt == "" and cell is None:
994 if stmt == "" and cell is None:
995 return
995 return
996
996
997 timefunc = timeit.default_timer
997 timefunc = timeit.default_timer
998 number = int(getattr(opts, "n", 0))
998 number = int(getattr(opts, "n", 0))
999 default_repeat = 7 if timeit.default_repeat < 7 else timeit.default_repeat
999 default_repeat = 7 if timeit.default_repeat < 7 else timeit.default_repeat
1000 repeat = int(getattr(opts, "r", default_repeat))
1000 repeat = int(getattr(opts, "r", default_repeat))
1001 precision = int(getattr(opts, "p", 3))
1001 precision = int(getattr(opts, "p", 3))
1002 quiet = 'q' in opts
1002 quiet = 'q' in opts
1003 return_result = 'o' in opts
1003 return_result = 'o' in opts
1004 if hasattr(opts, "t"):
1004 if hasattr(opts, "t"):
1005 timefunc = time.time
1005 timefunc = time.time
1006 if hasattr(opts, "c"):
1006 if hasattr(opts, "c"):
1007 timefunc = clock
1007 timefunc = clock
1008
1008
1009 timer = Timer(timer=timefunc)
1009 timer = Timer(timer=timefunc)
1010 # this code has tight coupling to the inner workings of timeit.Timer,
1010 # this code has tight coupling to the inner workings of timeit.Timer,
1011 # but is there a better way to achieve that the code stmt has access
1011 # but is there a better way to achieve that the code stmt has access
1012 # to the shell namespace?
1012 # to the shell namespace?
1013 transform = self.shell.input_splitter.transform_cell
1013 transform = self.shell.input_splitter.transform_cell
1014
1014
1015 if cell is None:
1015 if cell is None:
1016 # called as line magic
1016 # called as line magic
1017 ast_setup = self.shell.compile.ast_parse("pass")
1017 ast_setup = self.shell.compile.ast_parse("pass")
1018 ast_stmt = self.shell.compile.ast_parse(transform(stmt))
1018 ast_stmt = self.shell.compile.ast_parse(transform(stmt))
1019 else:
1019 else:
1020 ast_setup = self.shell.compile.ast_parse(transform(stmt))
1020 ast_setup = self.shell.compile.ast_parse(transform(stmt))
1021 ast_stmt = self.shell.compile.ast_parse(transform(cell))
1021 ast_stmt = self.shell.compile.ast_parse(transform(cell))
1022
1022
1023 ast_setup = self.shell.transform_ast(ast_setup)
1023 ast_setup = self.shell.transform_ast(ast_setup)
1024 ast_stmt = self.shell.transform_ast(ast_stmt)
1024 ast_stmt = self.shell.transform_ast(ast_stmt)
1025
1025
1026 # This codestring is taken from timeit.template - we fill it in as an
1026 # This codestring is taken from timeit.template - we fill it in as an
1027 # AST, so that we can apply our AST transformations to the user code
1027 # AST, so that we can apply our AST transformations to the user code
1028 # without affecting the timing code.
1028 # without affecting the timing code.
1029 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
1029 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
1030 ' setup\n'
1030 ' setup\n'
1031 ' _t0 = _timer()\n'
1031 ' _t0 = _timer()\n'
1032 ' for _i in _it:\n'
1032 ' for _i in _it:\n'
1033 ' stmt\n'
1033 ' stmt\n'
1034 ' _t1 = _timer()\n'
1034 ' _t1 = _timer()\n'
1035 ' return _t1 - _t0\n')
1035 ' return _t1 - _t0\n')
1036
1036
1037 timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
1037 timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
1038 timeit_ast = ast.fix_missing_locations(timeit_ast)
1038 timeit_ast = ast.fix_missing_locations(timeit_ast)
1039
1039
1040 # Track compilation time so it can be reported if too long
1040 # Track compilation time so it can be reported if too long
1041 # Minimum time above which compilation time will be reported
1041 # Minimum time above which compilation time will be reported
1042 tc_min = 0.1
1042 tc_min = 0.1
1043
1043
1044 t0 = clock()
1044 t0 = clock()
1045 code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
1045 code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
1046 tc = clock()-t0
1046 tc = clock()-t0
1047
1047
1048 ns = {}
1048 ns = {}
1049 exec(code, self.shell.user_ns, ns)
1049 exec(code, self.shell.user_ns, ns)
1050 timer.inner = ns["inner"]
1050 timer.inner = ns["inner"]
1051
1051
1052 # This is used to check if there is a huge difference between the
1052 # This is used to check if there is a huge difference between the
1053 # best and worst timings.
1053 # best and worst timings.
1054 # Issue: https://github.com/ipython/ipython/issues/6471
1054 # Issue: https://github.com/ipython/ipython/issues/6471
1055 if number == 0:
1055 if number == 0:
1056 # determine number so that 0.2 <= total time < 2.0
1056 # determine number so that 0.2 <= total time < 2.0
1057 for index in range(0, 10):
1057 for index in range(0, 10):
1058 number = 10 ** index
1058 number = 10 ** index
1059 time_number = timer.timeit(number)
1059 time_number = timer.timeit(number)
1060 if time_number >= 0.2:
1060 if time_number >= 0.2:
1061 break
1061 break
1062
1062
1063 all_runs = timer.repeat(repeat, number)
1063 all_runs = timer.repeat(repeat, number)
1064 best = min(all_runs) / number
1064 best = min(all_runs) / number
1065 worst = max(all_runs) / number
1065 worst = max(all_runs) / number
1066 timeit_result = TimeitResult(number, repeat, best, worst, all_runs, tc, precision)
1066 timeit_result = TimeitResult(number, repeat, best, worst, all_runs, tc, precision)
1067
1067
1068 if not quiet :
1068 if not quiet :
1069 # Check best timing is greater than zero to avoid a
1069 # Check best timing is greater than zero to avoid a
1070 # ZeroDivisionError.
1070 # ZeroDivisionError.
1071 # In cases where the slowest timing is lesser than a micosecond
1071 # In cases where the slowest timing is lesser than a micosecond
1072 # we assume that it does not really matter if the fastest
1072 # we assume that it does not really matter if the fastest
1073 # timing is 4 times faster than the slowest timing or not.
1073 # timing is 4 times faster than the slowest timing or not.
1074 if worst > 4 * best and best > 0 and worst > 1e-6:
1074 if worst > 4 * best and best > 0 and worst > 1e-6:
1075 print("The slowest run took %0.2f times longer than the "
1075 print("The slowest run took %0.2f times longer than the "
1076 "fastest. This could mean that an intermediate result "
1076 "fastest. This could mean that an intermediate result "
1077 "is being cached." % (worst / best))
1077 "is being cached." % (worst / best))
1078
1078
1079 print( timeit_result )
1079 print( timeit_result )
1080
1080
1081 if tc > tc_min:
1081 if tc > tc_min:
1082 print("Compiler time: %.2f s" % tc)
1082 print("Compiler time: %.2f s" % tc)
1083 if return_result:
1083 if return_result:
1084 return timeit_result
1084 return timeit_result
1085
1085
1086 @skip_doctest
1086 @skip_doctest
1087 @needs_local_scope
1087 @needs_local_scope
1088 @line_cell_magic
1088 @line_cell_magic
1089 def time(self,line='', cell=None, local_ns=None):
1089 def time(self,line='', cell=None, local_ns=None):
1090 """Time execution of a Python statement or expression.
1090 """Time execution of a Python statement or expression.
1091
1091
1092 The CPU and wall clock times are printed, and the value of the
1092 The CPU and wall clock times are printed, and the value of the
1093 expression (if any) is returned. Note that under Win32, system time
1093 expression (if any) is returned. Note that under Win32, system time
1094 is always reported as 0, since it can not be measured.
1094 is always reported as 0, since it can not be measured.
1095
1095
1096 This function can be used both as a line and cell magic:
1096 This function can be used both as a line and cell magic:
1097
1097
1098 - In line mode you can time a single-line statement (though multiple
1098 - In line mode you can time a single-line statement (though multiple
1099 ones can be chained with using semicolons).
1099 ones can be chained with using semicolons).
1100
1100
1101 - In cell mode, you can time the cell body (a directly
1101 - In cell mode, you can time the cell body (a directly
1102 following statement raises an error).
1102 following statement raises an error).
1103
1103
1104 This function provides very basic timing functionality. Use the timeit
1104 This function provides very basic timing functionality. Use the timeit
1105 magic for more control over the measurement.
1105 magic for more control over the measurement.
1106
1106
1107 Examples
1107 Examples
1108 --------
1108 --------
1109 ::
1109 ::
1110
1110
1111 In [1]: %time 2**128
1111 In [1]: %time 2**128
1112 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1112 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1113 Wall time: 0.00
1113 Wall time: 0.00
1114 Out[1]: 340282366920938463463374607431768211456L
1114 Out[1]: 340282366920938463463374607431768211456L
1115
1115
1116 In [2]: n = 1000000
1116 In [2]: n = 1000000
1117
1117
1118 In [3]: %time sum(range(n))
1118 In [3]: %time sum(range(n))
1119 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1119 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1120 Wall time: 1.37
1120 Wall time: 1.37
1121 Out[3]: 499999500000L
1121 Out[3]: 499999500000L
1122
1122
1123 In [4]: %time print 'hello world'
1123 In [4]: %time print 'hello world'
1124 hello world
1124 hello world
1125 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1125 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1126 Wall time: 0.00
1126 Wall time: 0.00
1127
1127
1128 Note that the time needed by Python to compile the given expression
1128 Note that the time needed by Python to compile the given expression
1129 will be reported if it is more than 0.1s. In this example, the
1129 will be reported if it is more than 0.1s. In this example, the
1130 actual exponentiation is done by Python at compilation time, so while
1130 actual exponentiation is done by Python at compilation time, so while
1131 the expression can take a noticeable amount of time to compute, that
1131 the expression can take a noticeable amount of time to compute, that
1132 time is purely due to the compilation:
1132 time is purely due to the compilation:
1133
1133
1134 In [5]: %time 3**9999;
1134 In [5]: %time 3**9999;
1135 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1135 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1136 Wall time: 0.00 s
1136 Wall time: 0.00 s
1137
1137
1138 In [6]: %time 3**999999;
1138 In [6]: %time 3**999999;
1139 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1139 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1140 Wall time: 0.00 s
1140 Wall time: 0.00 s
1141 Compiler : 0.78 s
1141 Compiler : 0.78 s
1142 """
1142 """
1143
1143
1144 # fail immediately if the given expression can't be compiled
1144 # fail immediately if the given expression can't be compiled
1145
1145
1146 if line and cell:
1146 if line and cell:
1147 raise UsageError("Can't use statement directly after '%%time'!")
1147 raise UsageError("Can't use statement directly after '%%time'!")
1148
1148
1149 if cell:
1149 if cell:
1150 expr = self.shell.input_transformer_manager.transform_cell(cell)
1150 expr = self.shell.input_transformer_manager.transform_cell(cell)
1151 else:
1151 else:
1152 expr = self.shell.input_transformer_manager.transform_cell(line)
1152 expr = self.shell.input_transformer_manager.transform_cell(line)
1153
1153
1154 # Minimum time above which parse time will be reported
1154 # Minimum time above which parse time will be reported
1155 tp_min = 0.1
1155 tp_min = 0.1
1156
1156
1157 t0 = clock()
1157 t0 = clock()
1158 expr_ast = self.shell.compile.ast_parse(expr)
1158 expr_ast = self.shell.compile.ast_parse(expr)
1159 tp = clock()-t0
1159 tp = clock()-t0
1160
1160
1161 # Apply AST transformations
1161 # Apply AST transformations
1162 expr_ast = self.shell.transform_ast(expr_ast)
1162 expr_ast = self.shell.transform_ast(expr_ast)
1163
1163
1164 # Minimum time above which compilation time will be reported
1164 # Minimum time above which compilation time will be reported
1165 tc_min = 0.1
1165 tc_min = 0.1
1166
1166
1167 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
1167 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
1168 mode = 'eval'
1168 mode = 'eval'
1169 source = '<timed eval>'
1169 source = '<timed eval>'
1170 expr_ast = ast.Expression(expr_ast.body[0].value)
1170 expr_ast = ast.Expression(expr_ast.body[0].value)
1171 else:
1171 else:
1172 mode = 'exec'
1172 mode = 'exec'
1173 source = '<timed exec>'
1173 source = '<timed exec>'
1174 t0 = clock()
1174 t0 = clock()
1175 code = self.shell.compile(expr_ast, source, mode)
1175 code = self.shell.compile(expr_ast, source, mode)
1176 tc = clock()-t0
1176 tc = clock()-t0
1177
1177
1178 # skew measurement as little as possible
1178 # skew measurement as little as possible
1179 glob = self.shell.user_ns
1179 glob = self.shell.user_ns
1180 wtime = time.time
1180 wtime = time.time
1181 # time execution
1181 # time execution
1182 wall_st = wtime()
1182 wall_st = wtime()
1183 if mode=='eval':
1183 if mode=='eval':
1184 st = clock2()
1184 st = clock2()
1185 try:
1185 try:
1186 out = eval(code, glob, local_ns)
1186 out = eval(code, glob, local_ns)
1187 except:
1187 except:
1188 self.shell.showtraceback()
1188 self.shell.showtraceback()
1189 return
1189 return
1190 end = clock2()
1190 end = clock2()
1191 else:
1191 else:
1192 st = clock2()
1192 st = clock2()
1193 try:
1193 try:
1194 exec(code, glob, local_ns)
1194 exec(code, glob, local_ns)
1195 except:
1195 except:
1196 self.shell.showtraceback()
1196 self.shell.showtraceback()
1197 return
1197 return
1198 end = clock2()
1198 end = clock2()
1199 out = None
1199 out = None
1200 wall_end = wtime()
1200 wall_end = wtime()
1201 # Compute actual times and report
1201 # Compute actual times and report
1202 wall_time = wall_end-wall_st
1202 wall_time = wall_end-wall_st
1203 cpu_user = end[0]-st[0]
1203 cpu_user = end[0]-st[0]
1204 cpu_sys = end[1]-st[1]
1204 cpu_sys = end[1]-st[1]
1205 cpu_tot = cpu_user+cpu_sys
1205 cpu_tot = cpu_user+cpu_sys
1206 # On windows cpu_sys is always zero, so no new information to the next print
1206 # On windows cpu_sys is always zero, so no new information to the next print
1207 if sys.platform != 'win32':
1207 if sys.platform != 'win32':
1208 print("CPU times: user %s, sys: %s, total: %s" % \
1208 print("CPU times: user %s, sys: %s, total: %s" % \
1209 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
1209 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
1210 print("Wall time: %s" % _format_time(wall_time))
1210 print("Wall time: %s" % _format_time(wall_time))
1211 if tc > tc_min:
1211 if tc > tc_min:
1212 print("Compiler : %s" % _format_time(tc))
1212 print("Compiler : %s" % _format_time(tc))
1213 if tp > tp_min:
1213 if tp > tp_min:
1214 print("Parser : %s" % _format_time(tp))
1214 print("Parser : %s" % _format_time(tp))
1215 return out
1215 return out
1216
1216
1217 @skip_doctest
1217 @skip_doctest
1218 @line_magic
1218 @line_magic
1219 def macro(self, parameter_s=''):
1219 def macro(self, parameter_s=''):
1220 """Define a macro for future re-execution. It accepts ranges of history,
1220 """Define a macro for future re-execution. It accepts ranges of history,
1221 filenames or string objects.
1221 filenames or string objects.
1222
1222
1223 Usage:\\
1223 Usage:\\
1224 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1224 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1225
1225
1226 Options:
1226 Options:
1227
1227
1228 -r: use 'raw' input. By default, the 'processed' history is used,
1228 -r: use 'raw' input. By default, the 'processed' history is used,
1229 so that magics are loaded in their transformed version to valid
1229 so that magics are loaded in their transformed version to valid
1230 Python. If this option is given, the raw input as typed at the
1230 Python. If this option is given, the raw input as typed at the
1231 command line is used instead.
1231 command line is used instead.
1232
1232
1233 -q: quiet macro definition. By default, a tag line is printed
1233 -q: quiet macro definition. By default, a tag line is printed
1234 to indicate the macro has been created, and then the contents of
1234 to indicate the macro has been created, and then the contents of
1235 the macro are printed. If this option is given, then no printout
1235 the macro are printed. If this option is given, then no printout
1236 is produced once the macro is created.
1236 is produced once the macro is created.
1237
1237
1238 This will define a global variable called `name` which is a string
1238 This will define a global variable called `name` which is a string
1239 made of joining the slices and lines you specify (n1,n2,... numbers
1239 made of joining the slices and lines you specify (n1,n2,... numbers
1240 above) from your input history into a single string. This variable
1240 above) from your input history into a single string. This variable
1241 acts like an automatic function which re-executes those lines as if
1241 acts like an automatic function which re-executes those lines as if
1242 you had typed them. You just type 'name' at the prompt and the code
1242 you had typed them. You just type 'name' at the prompt and the code
1243 executes.
1243 executes.
1244
1244
1245 The syntax for indicating input ranges is described in %history.
1245 The syntax for indicating input ranges is described in %history.
1246
1246
1247 Note: as a 'hidden' feature, you can also use traditional python slice
1247 Note: as a 'hidden' feature, you can also use traditional python slice
1248 notation, where N:M means numbers N through M-1.
1248 notation, where N:M means numbers N through M-1.
1249
1249
1250 For example, if your history contains (print using %hist -n )::
1250 For example, if your history contains (print using %hist -n )::
1251
1251
1252 44: x=1
1252 44: x=1
1253 45: y=3
1253 45: y=3
1254 46: z=x+y
1254 46: z=x+y
1255 47: print x
1255 47: print x
1256 48: a=5
1256 48: a=5
1257 49: print 'x',x,'y',y
1257 49: print 'x',x,'y',y
1258
1258
1259 you can create a macro with lines 44 through 47 (included) and line 49
1259 you can create a macro with lines 44 through 47 (included) and line 49
1260 called my_macro with::
1260 called my_macro with::
1261
1261
1262 In [55]: %macro my_macro 44-47 49
1262 In [55]: %macro my_macro 44-47 49
1263
1263
1264 Now, typing `my_macro` (without quotes) will re-execute all this code
1264 Now, typing `my_macro` (without quotes) will re-execute all this code
1265 in one pass.
1265 in one pass.
1266
1266
1267 You don't need to give the line-numbers in order, and any given line
1267 You don't need to give the line-numbers in order, and any given line
1268 number can appear multiple times. You can assemble macros with any
1268 number can appear multiple times. You can assemble macros with any
1269 lines from your input history in any order.
1269 lines from your input history in any order.
1270
1270
1271 The macro is a simple object which holds its value in an attribute,
1271 The macro is a simple object which holds its value in an attribute,
1272 but IPython's display system checks for macros and executes them as
1272 but IPython's display system checks for macros and executes them as
1273 code instead of printing them when you type their name.
1273 code instead of printing them when you type their name.
1274
1274
1275 You can view a macro's contents by explicitly printing it with::
1275 You can view a macro's contents by explicitly printing it with::
1276
1276
1277 print macro_name
1277 print macro_name
1278
1278
1279 """
1279 """
1280 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1280 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1281 if not args: # List existing macros
1281 if not args: # List existing macros
1282 return sorted(k for k,v in iteritems(self.shell.user_ns) if\
1282 return sorted(k for k,v in self.shell.user_ns.items() if isinstance(v, Macro))
1283 isinstance(v, Macro))
1284 if len(args) == 1:
1283 if len(args) == 1:
1285 raise UsageError(
1284 raise UsageError(
1286 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1285 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1287 name, codefrom = args[0], " ".join(args[1:])
1286 name, codefrom = args[0], " ".join(args[1:])
1288
1287
1289 #print 'rng',ranges # dbg
1288 #print 'rng',ranges # dbg
1290 try:
1289 try:
1291 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1290 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1292 except (ValueError, TypeError) as e:
1291 except (ValueError, TypeError) as e:
1293 print(e.args[0])
1292 print(e.args[0])
1294 return
1293 return
1295 macro = Macro(lines)
1294 macro = Macro(lines)
1296 self.shell.define_macro(name, macro)
1295 self.shell.define_macro(name, macro)
1297 if not ( 'q' in opts) :
1296 if not ( 'q' in opts) :
1298 print('Macro `%s` created. To execute, type its name (without quotes).' % name)
1297 print('Macro `%s` created. To execute, type its name (without quotes).' % name)
1299 print('=== Macro contents: ===')
1298 print('=== Macro contents: ===')
1300 print(macro, end=' ')
1299 print(macro, end=' ')
1301
1300
1302 @magic_arguments.magic_arguments()
1301 @magic_arguments.magic_arguments()
1303 @magic_arguments.argument('output', type=str, default='', nargs='?',
1302 @magic_arguments.argument('output', type=str, default='', nargs='?',
1304 help="""The name of the variable in which to store output.
1303 help="""The name of the variable in which to store output.
1305 This is a utils.io.CapturedIO object with stdout/err attributes
1304 This is a utils.io.CapturedIO object with stdout/err attributes
1306 for the text of the captured output.
1305 for the text of the captured output.
1307
1306
1308 CapturedOutput also has a show() method for displaying the output,
1307 CapturedOutput also has a show() method for displaying the output,
1309 and __call__ as well, so you can use that to quickly display the
1308 and __call__ as well, so you can use that to quickly display the
1310 output.
1309 output.
1311
1310
1312 If unspecified, captured output is discarded.
1311 If unspecified, captured output is discarded.
1313 """
1312 """
1314 )
1313 )
1315 @magic_arguments.argument('--no-stderr', action="store_true",
1314 @magic_arguments.argument('--no-stderr', action="store_true",
1316 help="""Don't capture stderr."""
1315 help="""Don't capture stderr."""
1317 )
1316 )
1318 @magic_arguments.argument('--no-stdout', action="store_true",
1317 @magic_arguments.argument('--no-stdout', action="store_true",
1319 help="""Don't capture stdout."""
1318 help="""Don't capture stdout."""
1320 )
1319 )
1321 @magic_arguments.argument('--no-display', action="store_true",
1320 @magic_arguments.argument('--no-display', action="store_true",
1322 help="""Don't capture IPython's rich display."""
1321 help="""Don't capture IPython's rich display."""
1323 )
1322 )
1324 @cell_magic
1323 @cell_magic
1325 def capture(self, line, cell):
1324 def capture(self, line, cell):
1326 """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
1325 """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
1327 args = magic_arguments.parse_argstring(self.capture, line)
1326 args = magic_arguments.parse_argstring(self.capture, line)
1328 out = not args.no_stdout
1327 out = not args.no_stdout
1329 err = not args.no_stderr
1328 err = not args.no_stderr
1330 disp = not args.no_display
1329 disp = not args.no_display
1331 with capture_output(out, err, disp) as io:
1330 with capture_output(out, err, disp) as io:
1332 self.shell.run_cell(cell)
1331 self.shell.run_cell(cell)
1333 if args.output:
1332 if args.output:
1334 self.shell.user_ns[args.output] = io
1333 self.shell.user_ns[args.output] = io
1335
1334
1336 def parse_breakpoint(text, current_file):
1335 def parse_breakpoint(text, current_file):
1337 '''Returns (file, line) for file:line and (current_file, line) for line'''
1336 '''Returns (file, line) for file:line and (current_file, line) for line'''
1338 colon = text.find(':')
1337 colon = text.find(':')
1339 if colon == -1:
1338 if colon == -1:
1340 return current_file, int(text)
1339 return current_file, int(text)
1341 else:
1340 else:
1342 return text[:colon], int(text[colon+1:])
1341 return text[:colon], int(text[colon+1:])
1343
1342
1344 def _format_time(timespan, precision=3):
1343 def _format_time(timespan, precision=3):
1345 """Formats the timespan in a human readable form"""
1344 """Formats the timespan in a human readable form"""
1346
1345
1347 if timespan >= 60.0:
1346 if timespan >= 60.0:
1348 # we have more than a minute, format that in a human readable form
1347 # we have more than a minute, format that in a human readable form
1349 # Idea from http://snipplr.com/view/5713/
1348 # Idea from http://snipplr.com/view/5713/
1350 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1349 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1351 time = []
1350 time = []
1352 leftover = timespan
1351 leftover = timespan
1353 for suffix, length in parts:
1352 for suffix, length in parts:
1354 value = int(leftover / length)
1353 value = int(leftover / length)
1355 if value > 0:
1354 if value > 0:
1356 leftover = leftover % length
1355 leftover = leftover % length
1357 time.append(u'%s%s' % (str(value), suffix))
1356 time.append(u'%s%s' % (str(value), suffix))
1358 if leftover < 1:
1357 if leftover < 1:
1359 break
1358 break
1360 return " ".join(time)
1359 return " ".join(time)
1361
1360
1362
1361
1363 # Unfortunately the unicode 'micro' symbol can cause problems in
1362 # Unfortunately the unicode 'micro' symbol can cause problems in
1364 # certain terminals.
1363 # certain terminals.
1365 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1364 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1366 # Try to prevent crashes by being more secure than it needs to
1365 # Try to prevent crashes by being more secure than it needs to
1367 # E.g. eclipse is able to print a µ, but has no sys.stdout.encoding set.
1366 # E.g. eclipse is able to print a µ, but has no sys.stdout.encoding set.
1368 units = [u"s", u"ms",u'us',"ns"] # the save value
1367 units = [u"s", u"ms",u'us',"ns"] # the save value
1369 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1368 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1370 try:
1369 try:
1371 u'\xb5'.encode(sys.stdout.encoding)
1370 u'\xb5'.encode(sys.stdout.encoding)
1372 units = [u"s", u"ms",u'\xb5s',"ns"]
1371 units = [u"s", u"ms",u'\xb5s',"ns"]
1373 except:
1372 except:
1374 pass
1373 pass
1375 scaling = [1, 1e3, 1e6, 1e9]
1374 scaling = [1, 1e3, 1e6, 1e9]
1376
1375
1377 if timespan > 0.0:
1376 if timespan > 0.0:
1378 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1377 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1379 else:
1378 else:
1380 order = 3
1379 order = 3
1381 return u"%.*g %s" % (precision, timespan * scaling[order], units[order])
1380 return u"%.*g %s" % (precision, timespan * scaling[order], units[order])
@@ -1,184 +1,183 b''
1 """Implementation of magic functions for IPython's own logging.
1 """Implementation of magic functions for IPython's own logging.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Copyright (c) 2012 The IPython Development Team.
4 # Copyright (c) 2012 The IPython Development Team.
5 #
5 #
6 # Distributed under the terms of the Modified BSD License.
6 # Distributed under the terms of the Modified BSD License.
7 #
7 #
8 # The full license is in the file COPYING.txt, distributed with this software.
8 # The full license is in the file COPYING.txt, distributed with this software.
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Imports
12 # Imports
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 # Stdlib
15 # Stdlib
16 import os
16 import os
17 import sys
17 import sys
18
18
19 # Our own packages
19 # Our own packages
20 from IPython.core.magic import Magics, magics_class, line_magic
20 from IPython.core.magic import Magics, magics_class, line_magic
21 from warnings import warn
21 from warnings import warn
22 from IPython.utils.py3compat import str_to_unicode
23
22
24 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
25 # Magic implementation classes
24 # Magic implementation classes
26 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
27
26
28 @magics_class
27 @magics_class
29 class LoggingMagics(Magics):
28 class LoggingMagics(Magics):
30 """Magics related to all logging machinery."""
29 """Magics related to all logging machinery."""
31
30
32 @line_magic
31 @line_magic
33 def logstart(self, parameter_s=''):
32 def logstart(self, parameter_s=''):
34 """Start logging anywhere in a session.
33 """Start logging anywhere in a session.
35
34
36 %logstart [-o|-r|-t] [log_name [log_mode]]
35 %logstart [-o|-r|-t] [log_name [log_mode]]
37
36
38 If no name is given, it defaults to a file named 'ipython_log.py' in your
37 If no name is given, it defaults to a file named 'ipython_log.py' in your
39 current directory, in 'rotate' mode (see below).
38 current directory, in 'rotate' mode (see below).
40
39
41 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
40 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
42 history up to that point and then continues logging.
41 history up to that point and then continues logging.
43
42
44 %logstart takes a second optional parameter: logging mode. This can be one
43 %logstart takes a second optional parameter: logging mode. This can be one
45 of (note that the modes are given unquoted):
44 of (note that the modes are given unquoted):
46
45
47 append
46 append
48 Keep logging at the end of any existing file.
47 Keep logging at the end of any existing file.
49
48
50 backup
49 backup
51 Rename any existing file to name~ and start name.
50 Rename any existing file to name~ and start name.
52
51
53 global
52 global
54 Append to a single logfile in your home directory.
53 Append to a single logfile in your home directory.
55
54
56 over
55 over
57 Overwrite any existing log.
56 Overwrite any existing log.
58
57
59 rotate
58 rotate
60 Create rotating logs: name.1~, name.2~, etc.
59 Create rotating logs: name.1~, name.2~, etc.
61
60
62 Options:
61 Options:
63
62
64 -o
63 -o
65 log also IPython's output. In this mode, all commands which
64 log also IPython's output. In this mode, all commands which
66 generate an Out[NN] prompt are recorded to the logfile, right after
65 generate an Out[NN] prompt are recorded to the logfile, right after
67 their corresponding input line. The output lines are always
66 their corresponding input line. The output lines are always
68 prepended with a '#[Out]# ' marker, so that the log remains valid
67 prepended with a '#[Out]# ' marker, so that the log remains valid
69 Python code.
68 Python code.
70
69
71 Since this marker is always the same, filtering only the output from
70 Since this marker is always the same, filtering only the output from
72 a log is very easy, using for example a simple awk call::
71 a log is very easy, using for example a simple awk call::
73
72
74 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
73 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
75
74
76 -r
75 -r
77 log 'raw' input. Normally, IPython's logs contain the processed
76 log 'raw' input. Normally, IPython's logs contain the processed
78 input, so that user lines are logged in their final form, converted
77 input, so that user lines are logged in their final form, converted
79 into valid Python. For example, %Exit is logged as
78 into valid Python. For example, %Exit is logged as
80 _ip.magic("Exit"). If the -r flag is given, all input is logged
79 _ip.magic("Exit"). If the -r flag is given, all input is logged
81 exactly as typed, with no transformations applied.
80 exactly as typed, with no transformations applied.
82
81
83 -t
82 -t
84 put timestamps before each input line logged (these are put in
83 put timestamps before each input line logged (these are put in
85 comments).
84 comments).
86 """
85 """
87
86
88 opts,par = self.parse_options(parameter_s,'ort')
87 opts,par = self.parse_options(parameter_s,'ort')
89 log_output = 'o' in opts
88 log_output = 'o' in opts
90 log_raw_input = 'r' in opts
89 log_raw_input = 'r' in opts
91 timestamp = 't' in opts
90 timestamp = 't' in opts
92
91
93 logger = self.shell.logger
92 logger = self.shell.logger
94
93
95 # if no args are given, the defaults set in the logger constructor by
94 # if no args are given, the defaults set in the logger constructor by
96 # ipython remain valid
95 # ipython remain valid
97 if par:
96 if par:
98 try:
97 try:
99 logfname,logmode = par.split()
98 logfname,logmode = par.split()
100 except:
99 except:
101 logfname = par
100 logfname = par
102 logmode = 'backup'
101 logmode = 'backup'
103 else:
102 else:
104 logfname = logger.logfname
103 logfname = logger.logfname
105 logmode = logger.logmode
104 logmode = logger.logmode
106 # put logfname into rc struct as if it had been called on the command
105 # put logfname into rc struct as if it had been called on the command
107 # line, so it ends up saved in the log header Save it in case we need
106 # line, so it ends up saved in the log header Save it in case we need
108 # to restore it...
107 # to restore it...
109 old_logfile = self.shell.logfile
108 old_logfile = self.shell.logfile
110 if logfname:
109 if logfname:
111 logfname = os.path.expanduser(logfname)
110 logfname = os.path.expanduser(logfname)
112 self.shell.logfile = logfname
111 self.shell.logfile = logfname
113
112
114 loghead = u'# IPython log file\n\n'
113 loghead = u'# IPython log file\n\n'
115 try:
114 try:
116 logger.logstart(logfname, loghead, logmode, log_output, timestamp,
115 logger.logstart(logfname, loghead, logmode, log_output, timestamp,
117 log_raw_input)
116 log_raw_input)
118 except:
117 except:
119 self.shell.logfile = old_logfile
118 self.shell.logfile = old_logfile
120 warn("Couldn't start log: %s" % sys.exc_info()[1])
119 warn("Couldn't start log: %s" % sys.exc_info()[1])
121 else:
120 else:
122 # log input history up to this point, optionally interleaving
121 # log input history up to this point, optionally interleaving
123 # output if requested
122 # output if requested
124
123
125 if timestamp:
124 if timestamp:
126 # disable timestamping for the previous history, since we've
125 # disable timestamping for the previous history, since we've
127 # lost those already (no time machine here).
126 # lost those already (no time machine here).
128 logger.timestamp = False
127 logger.timestamp = False
129
128
130 if log_raw_input:
129 if log_raw_input:
131 input_hist = self.shell.history_manager.input_hist_raw
130 input_hist = self.shell.history_manager.input_hist_raw
132 else:
131 else:
133 input_hist = self.shell.history_manager.input_hist_parsed
132 input_hist = self.shell.history_manager.input_hist_parsed
134
133
135 if log_output:
134 if log_output:
136 log_write = logger.log_write
135 log_write = logger.log_write
137 output_hist = self.shell.history_manager.output_hist
136 output_hist = self.shell.history_manager.output_hist
138 for n in range(1,len(input_hist)-1):
137 for n in range(1,len(input_hist)-1):
139 log_write(input_hist[n].rstrip() + u'\n')
138 log_write(input_hist[n].rstrip() + u'\n')
140 if n in output_hist:
139 if n in output_hist:
141 log_write(str_to_unicode(repr(output_hist[n])),'output')
140 log_write(repr(output_hist[n]),'output')
142 else:
141 else:
143 logger.log_write(u'\n'.join(input_hist[1:]))
142 logger.log_write(u'\n'.join(input_hist[1:]))
144 logger.log_write(u'\n')
143 logger.log_write(u'\n')
145 if timestamp:
144 if timestamp:
146 # re-enable timestamping
145 # re-enable timestamping
147 logger.timestamp = True
146 logger.timestamp = True
148
147
149 print ('Activating auto-logging. '
148 print ('Activating auto-logging. '
150 'Current session state plus future input saved.')
149 'Current session state plus future input saved.')
151 logger.logstate()
150 logger.logstate()
152
151
153 @line_magic
152 @line_magic
154 def logstop(self, parameter_s=''):
153 def logstop(self, parameter_s=''):
155 """Fully stop logging and close log file.
154 """Fully stop logging and close log file.
156
155
157 In order to start logging again, a new %logstart call needs to be made,
156 In order to start logging again, a new %logstart call needs to be made,
158 possibly (though not necessarily) with a new filename, mode and other
157 possibly (though not necessarily) with a new filename, mode and other
159 options."""
158 options."""
160 self.shell.logger.logstop()
159 self.shell.logger.logstop()
161
160
162 @line_magic
161 @line_magic
163 def logoff(self, parameter_s=''):
162 def logoff(self, parameter_s=''):
164 """Temporarily stop logging.
163 """Temporarily stop logging.
165
164
166 You must have previously started logging."""
165 You must have previously started logging."""
167 self.shell.logger.switch_log(0)
166 self.shell.logger.switch_log(0)
168
167
169 @line_magic
168 @line_magic
170 def logon(self, parameter_s=''):
169 def logon(self, parameter_s=''):
171 """Restart logging.
170 """Restart logging.
172
171
173 This function is for restarting logging which you've temporarily
172 This function is for restarting logging which you've temporarily
174 stopped with %logoff. For starting logging for the first time, you
173 stopped with %logoff. For starting logging for the first time, you
175 must use the %logstart function, which allows you to specify an
174 must use the %logstart function, which allows you to specify an
176 optional log filename."""
175 optional log filename."""
177
176
178 self.shell.logger.switch_log(1)
177 self.shell.logger.switch_log(1)
179
178
180 @line_magic
179 @line_magic
181 def logstate(self, parameter_s=''):
180 def logstate(self, parameter_s=''):
182 """Print the status of the logging system."""
181 """Print the status of the logging system."""
183
182
184 self.shell.logger.logstate()
183 self.shell.logger.logstate()
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now