##// END OF EJS Templates
update dependency imports...
Min RK -
Show More

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

@@ -1,147 +1,146 b''
1 1 # encoding: utf-8
2 2 """
3 3 IPython: tools for interactive and parallel computing in Python.
4 4
5 5 http://ipython.org
6 6 """
7 7 #-----------------------------------------------------------------------------
8 8 # Copyright (c) 2008-2011, IPython Development Team.
9 9 # Copyright (c) 2001-2007, Fernando Perez <fernando.perez@colorado.edu>
10 10 # Copyright (c) 2001, Janko Hauser <jhauser@zscout.de>
11 11 # Copyright (c) 2001, Nathaniel Gray <n8gray@caltech.edu>
12 12 #
13 13 # Distributed under the terms of the Modified BSD License.
14 14 #
15 15 # The full license is in the file COPYING.txt, distributed with this software.
16 16 #-----------------------------------------------------------------------------
17 17
18 18 #-----------------------------------------------------------------------------
19 19 # Imports
20 20 #-----------------------------------------------------------------------------
21 21 from __future__ import absolute_import
22 22
23 23 import os
24 24 import sys
25 25
26 26 #-----------------------------------------------------------------------------
27 27 # Setup everything
28 28 #-----------------------------------------------------------------------------
29 29
30 30 # Don't forget to also update setup.py when this changes!
31 31 v = sys.version_info
32 32 if v[:2] < (2,7) or (v[0] >= 3 and v[:2] < (3,3)):
33 33 raise ImportError('IPython requires Python version 2.7 or 3.3 or above.')
34 34 del v
35 35
36 36 # Make it easy to import extensions - they are always directly on pythonpath.
37 37 # Therefore, non-IPython modules can be added to extensions directory.
38 38 # This should probably be in ipapp.py.
39 39 sys.path.append(os.path.join(os.path.dirname(__file__), "extensions"))
40 40
41 41 #-----------------------------------------------------------------------------
42 42 # Setup the top level names
43 43 #-----------------------------------------------------------------------------
44 44
45 from .config.loader import Config
46 45 from .core.getipython import get_ipython
47 46 from .core import release
48 47 from .core.application import Application
49 48 from .terminal.embed import embed
50 49
51 50 from .core.error import TryNext
52 51 from .core.interactiveshell import InteractiveShell
53 52 from .testing import test
54 53 from .utils.sysinfo import sys_info
55 54 from .utils.frame import extract_module_locals
56 55
57 56 # Release data
58 57 __author__ = '%s <%s>' % (release.author, release.author_email)
59 58 __license__ = release.license
60 59 __version__ = release.version
61 60 version_info = release.version_info
62 61
63 62 def embed_kernel(module=None, local_ns=None, **kwargs):
64 63 """Embed and start an IPython kernel in a given scope.
65 64
66 65 If you don't want the kernel to initialize the namespace
67 66 from the scope of the surrounding function,
68 67 and/or you want to load full IPython configuration,
69 68 you probably want `IPython.start_kernel()` instead.
70 69
71 70 Parameters
72 71 ----------
73 72 module : ModuleType, optional
74 73 The module to load into IPython globals (default: caller)
75 74 local_ns : dict, optional
76 75 The namespace to load into IPython user namespace (default: caller)
77 76
78 77 kwargs : various, optional
79 78 Further keyword args are relayed to the IPKernelApp constructor,
80 79 allowing configuration of the Kernel. Will only have an effect
81 80 on the first embed_kernel call for a given process.
82 81 """
83 82
84 83 (caller_module, caller_locals) = extract_module_locals(1)
85 84 if module is None:
86 85 module = caller_module
87 86 if local_ns is None:
88 87 local_ns = caller_locals
89 88
90 89 # Only import .zmq when we really need it
91 from IPython.kernel.zmq.embed import embed_kernel as real_embed_kernel
90 from ipython_kernel.embed import embed_kernel as real_embed_kernel
92 91 real_embed_kernel(module=module, local_ns=local_ns, **kwargs)
93 92
94 93 def start_ipython(argv=None, **kwargs):
95 94 """Launch a normal IPython instance (as opposed to embedded)
96 95
97 96 `IPython.embed()` puts a shell in a particular calling scope,
98 97 such as a function or method for debugging purposes,
99 98 which is often not desirable.
100 99
101 100 `start_ipython()` does full, regular IPython initialization,
102 101 including loading startup files, configuration, etc.
103 102 much of which is skipped by `embed()`.
104 103
105 104 This is a public API method, and will survive implementation changes.
106 105
107 106 Parameters
108 107 ----------
109 108
110 109 argv : list or None, optional
111 110 If unspecified or None, IPython will parse command-line options from sys.argv.
112 111 To prevent any command-line parsing, pass an empty list: `argv=[]`.
113 112 user_ns : dict, optional
114 113 specify this dictionary to initialize the IPython user namespace with particular values.
115 114 kwargs : various, optional
116 115 Any other kwargs will be passed to the Application constructor,
117 116 such as `config`.
118 117 """
119 118 from IPython.terminal.ipapp import launch_new_instance
120 119 return launch_new_instance(argv=argv, **kwargs)
121 120
122 121 def start_kernel(argv=None, **kwargs):
123 122 """Launch a normal IPython kernel instance (as opposed to embedded)
124 123
125 124 `IPython.embed_kernel()` puts a shell in a particular calling scope,
126 125 such as a function or method for debugging purposes,
127 126 which is often not desirable.
128 127
129 128 `start_kernel()` does full, regular IPython initialization,
130 129 including loading startup files, configuration, etc.
131 130 much of which is skipped by `embed()`.
132 131
133 132 Parameters
134 133 ----------
135 134
136 135 argv : list or None, optional
137 136 If unspecified or None, IPython will parse command-line options from sys.argv.
138 137 To prevent any command-line parsing, pass an empty list: `argv=[]`.
139 138 user_ns : dict, optional
140 139 specify this dictionary to initialize the IPython user namespace with particular values.
141 140 kwargs : various, optional
142 141 Any other kwargs will be passed to the Application constructor,
143 142 such as `config`.
144 143 """
145 144 from IPython.kernel.zmq.kernelapp import launch_new_instance
146 145 return launch_new_instance(argv=argv, **kwargs)
147 146 No newline at end of file
@@ -1,256 +1,256 b''
1 1 # encoding: utf-8
2 2 """
3 3 System command aliases.
4 4
5 5 Authors:
6 6
7 7 * Fernando Perez
8 8 * Brian Granger
9 9 """
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Copyright (C) 2008-2011 The IPython Development Team
13 13 #
14 14 # Distributed under the terms of the BSD License.
15 15 #
16 16 # The full license is in the file COPYING.txt, distributed with this software.
17 17 #-----------------------------------------------------------------------------
18 18
19 19 #-----------------------------------------------------------------------------
20 20 # Imports
21 21 #-----------------------------------------------------------------------------
22 22
23 23 import os
24 24 import re
25 25 import sys
26 26
27 from IPython.config.configurable import Configurable
27 from traitlets.config.configurable import Configurable
28 28 from IPython.core.error import UsageError
29 29
30 30 from IPython.utils.py3compat import string_types
31 from IPython.utils.traitlets import List, Instance
31 from traitlets import List, Instance
32 32 from IPython.utils.warn import error
33 33
34 34 #-----------------------------------------------------------------------------
35 35 # Utilities
36 36 #-----------------------------------------------------------------------------
37 37
38 38 # This is used as the pattern for calls to split_user_input.
39 39 shell_line_split = re.compile(r'^(\s*)()(\S+)(.*$)')
40 40
41 41 def default_aliases():
42 42 """Return list of shell aliases to auto-define.
43 43 """
44 44 # Note: the aliases defined here should be safe to use on a kernel
45 45 # regardless of what frontend it is attached to. Frontends that use a
46 46 # kernel in-process can define additional aliases that will only work in
47 47 # their case. For example, things like 'less' or 'clear' that manipulate
48 48 # the terminal should NOT be declared here, as they will only work if the
49 49 # kernel is running inside a true terminal, and not over the network.
50 50
51 51 if os.name == 'posix':
52 52 default_aliases = [('mkdir', 'mkdir'), ('rmdir', 'rmdir'),
53 53 ('mv', 'mv'), ('rm', 'rm'), ('cp', 'cp'),
54 54 ('cat', 'cat'),
55 55 ]
56 56 # Useful set of ls aliases. The GNU and BSD options are a little
57 57 # different, so we make aliases that provide as similar as possible
58 58 # behavior in ipython, by passing the right flags for each platform
59 59 if sys.platform.startswith('linux'):
60 60 ls_aliases = [('ls', 'ls -F --color'),
61 61 # long ls
62 62 ('ll', 'ls -F -o --color'),
63 63 # ls normal files only
64 64 ('lf', 'ls -F -o --color %l | grep ^-'),
65 65 # ls symbolic links
66 66 ('lk', 'ls -F -o --color %l | grep ^l'),
67 67 # directories or links to directories,
68 68 ('ldir', 'ls -F -o --color %l | grep /$'),
69 69 # things which are executable
70 70 ('lx', 'ls -F -o --color %l | grep ^-..x'),
71 71 ]
72 72 elif sys.platform.startswith('openbsd') or sys.platform.startswith('netbsd'):
73 73 # OpenBSD, NetBSD. The ls implementation on these platforms do not support
74 74 # the -G switch and lack the ability to use colorized output.
75 75 ls_aliases = [('ls', 'ls -F'),
76 76 # long ls
77 77 ('ll', 'ls -F -l'),
78 78 # ls normal files only
79 79 ('lf', 'ls -F -l %l | grep ^-'),
80 80 # ls symbolic links
81 81 ('lk', 'ls -F -l %l | grep ^l'),
82 82 # directories or links to directories,
83 83 ('ldir', 'ls -F -l %l | grep /$'),
84 84 # things which are executable
85 85 ('lx', 'ls -F -l %l | grep ^-..x'),
86 86 ]
87 87 else:
88 88 # BSD, OSX, etc.
89 89 ls_aliases = [('ls', 'ls -F -G'),
90 90 # long ls
91 91 ('ll', 'ls -F -l -G'),
92 92 # ls normal files only
93 93 ('lf', 'ls -F -l -G %l | grep ^-'),
94 94 # ls symbolic links
95 95 ('lk', 'ls -F -l -G %l | grep ^l'),
96 96 # directories or links to directories,
97 97 ('ldir', 'ls -F -G -l %l | grep /$'),
98 98 # things which are executable
99 99 ('lx', 'ls -F -l -G %l | grep ^-..x'),
100 100 ]
101 101 default_aliases = default_aliases + ls_aliases
102 102 elif os.name in ['nt', 'dos']:
103 103 default_aliases = [('ls', 'dir /on'),
104 104 ('ddir', 'dir /ad /on'), ('ldir', 'dir /ad /on'),
105 105 ('mkdir', 'mkdir'), ('rmdir', 'rmdir'),
106 106 ('echo', 'echo'), ('ren', 'ren'), ('copy', 'copy'),
107 107 ]
108 108 else:
109 109 default_aliases = []
110 110
111 111 return default_aliases
112 112
113 113
114 114 class AliasError(Exception):
115 115 pass
116 116
117 117
118 118 class InvalidAliasError(AliasError):
119 119 pass
120 120
121 121 class Alias(object):
122 122 """Callable object storing the details of one alias.
123 123
124 124 Instances are registered as magic functions to allow use of aliases.
125 125 """
126 126
127 127 # Prepare blacklist
128 128 blacklist = {'cd','popd','pushd','dhist','alias','unalias'}
129 129
130 130 def __init__(self, shell, name, cmd):
131 131 self.shell = shell
132 132 self.name = name
133 133 self.cmd = cmd
134 134 self.nargs = self.validate()
135 135
136 136 def validate(self):
137 137 """Validate the alias, and return the number of arguments."""
138 138 if self.name in self.blacklist:
139 139 raise InvalidAliasError("The name %s can't be aliased "
140 140 "because it is a keyword or builtin." % self.name)
141 141 try:
142 142 caller = self.shell.magics_manager.magics['line'][self.name]
143 143 except KeyError:
144 144 pass
145 145 else:
146 146 if not isinstance(caller, Alias):
147 147 raise InvalidAliasError("The name %s can't be aliased "
148 148 "because it is another magic command." % self.name)
149 149
150 150 if not (isinstance(self.cmd, string_types)):
151 151 raise InvalidAliasError("An alias command must be a string, "
152 152 "got: %r" % self.cmd)
153 153
154 154 nargs = self.cmd.count('%s') - self.cmd.count('%%s')
155 155
156 156 if (nargs > 0) and (self.cmd.find('%l') >= 0):
157 157 raise InvalidAliasError('The %s and %l specifiers are mutually '
158 158 'exclusive in alias definitions.')
159 159
160 160 return nargs
161 161
162 162 def __repr__(self):
163 163 return "<alias {} for {!r}>".format(self.name, self.cmd)
164 164
165 165 def __call__(self, rest=''):
166 166 cmd = self.cmd
167 167 nargs = self.nargs
168 168 # Expand the %l special to be the user's input line
169 169 if cmd.find('%l') >= 0:
170 170 cmd = cmd.replace('%l', rest)
171 171 rest = ''
172 172
173 173 if nargs==0:
174 174 if cmd.find('%%s') >= 1:
175 175 cmd = cmd.replace('%%s', '%s')
176 176 # Simple, argument-less aliases
177 177 cmd = '%s %s' % (cmd, rest)
178 178 else:
179 179 # Handle aliases with positional arguments
180 180 args = rest.split(None, nargs)
181 181 if len(args) < nargs:
182 182 raise UsageError('Alias <%s> requires %s arguments, %s given.' %
183 183 (self.name, nargs, len(args)))
184 184 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
185 185
186 186 self.shell.system(cmd)
187 187
188 188 #-----------------------------------------------------------------------------
189 189 # Main AliasManager class
190 190 #-----------------------------------------------------------------------------
191 191
192 192 class AliasManager(Configurable):
193 193
194 194 default_aliases = List(default_aliases(), config=True)
195 195 user_aliases = List(default_value=[], config=True)
196 196 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
197 197
198 198 def __init__(self, shell=None, **kwargs):
199 199 super(AliasManager, self).__init__(shell=shell, **kwargs)
200 200 # For convenient access
201 201 self.linemagics = self.shell.magics_manager.magics['line']
202 202 self.init_aliases()
203 203
204 204 def init_aliases(self):
205 205 # Load default & user aliases
206 206 for name, cmd in self.default_aliases + self.user_aliases:
207 207 self.soft_define_alias(name, cmd)
208 208
209 209 @property
210 210 def aliases(self):
211 211 return [(n, func.cmd) for (n, func) in self.linemagics.items()
212 212 if isinstance(func, Alias)]
213 213
214 214 def soft_define_alias(self, name, cmd):
215 215 """Define an alias, but don't raise on an AliasError."""
216 216 try:
217 217 self.define_alias(name, cmd)
218 218 except AliasError as e:
219 219 error("Invalid alias: %s" % e)
220 220
221 221 def define_alias(self, name, cmd):
222 222 """Define a new alias after validating it.
223 223
224 224 This will raise an :exc:`AliasError` if there are validation
225 225 problems.
226 226 """
227 227 caller = Alias(shell=self.shell, name=name, cmd=cmd)
228 228 self.shell.magics_manager.register_function(caller, magic_kind='line',
229 229 magic_name=name)
230 230
231 231 def get_alias(self, name):
232 232 """Return an alias, or None if no alias by that name exists."""
233 233 aname = self.linemagics.get(name, None)
234 234 return aname if isinstance(aname, Alias) else None
235 235
236 236 def is_alias(self, name):
237 237 """Return whether or not a given name has been defined as an alias"""
238 238 return self.get_alias(name) is not None
239 239
240 240 def undefine_alias(self, name):
241 241 if self.is_alias(name):
242 242 del self.linemagics[name]
243 243 else:
244 244 raise ValueError('%s is not an alias' % name)
245 245
246 246 def clear_aliases(self):
247 247 for name, cmd in self.aliases:
248 248 self.undefine_alias(name)
249 249
250 250 def retrieve_alias(self, name):
251 251 """Retrieve the command to which an alias expands."""
252 252 caller = self.get_alias(name)
253 253 if caller:
254 254 return caller.cmd
255 255 else:
256 256 raise ValueError('%s is not an alias' % name)
@@ -1,396 +1,397 b''
1 1 # encoding: utf-8
2 2 """
3 3 An application for IPython.
4 4
5 5 All top-level applications should use the classes in this module for
6 6 handling configuration and creating configurables.
7 7
8 8 The job of an :class:`Application` is to create the master configuration
9 9 object and then create the configurable objects, passing the config to them.
10 10 """
11 11
12 12 # Copyright (c) IPython Development Team.
13 13 # Distributed under the terms of the Modified BSD License.
14 14
15 15 import atexit
16 16 import glob
17 17 import logging
18 18 import os
19 19 import shutil
20 20 import sys
21 21
22 from IPython.config.application import Application, catch_config_error
23 from IPython.config.loader import ConfigFileNotFound, PyFileConfigLoader
22 from traitlets.config.application import Application, catch_config_error
23 from traitlets.config.loader import ConfigFileNotFound, PyFileConfigLoader
24 24 from IPython.core import release, crashhandler
25 25 from IPython.core.profiledir import ProfileDir, ProfileDirError
26 from IPython.utils.path import get_ipython_dir, get_ipython_package_dir, ensure_dir_exists
26 from IPython.paths import get_ipython_dir, get_ipython_package_dir
27 from IPython.utils.path import ensure_dir_exists
27 28 from IPython.utils import py3compat
28 from IPython.utils.traitlets import List, Unicode, Type, Bool, Dict, Set, Instance, Undefined
29 from traitlets import List, Unicode, Type, Bool, Dict, Set, Instance, Undefined
29 30
30 31 if os.name == 'nt':
31 32 programdata = os.environ.get('PROGRAMDATA', None)
32 33 if programdata:
33 34 SYSTEM_CONFIG_DIRS = [os.path.join(programdata, 'ipython')]
34 35 else: # PROGRAMDATA is not defined by default on XP.
35 36 SYSTEM_CONFIG_DIRS = []
36 37 else:
37 38 SYSTEM_CONFIG_DIRS = [
38 39 "/usr/local/etc/ipython",
39 40 "/etc/ipython",
40 41 ]
41 42
42 43
43 44 # aliases and flags
44 45
45 46 base_aliases = {
46 47 'profile-dir' : 'ProfileDir.location',
47 48 'profile' : 'BaseIPythonApplication.profile',
48 49 'ipython-dir' : 'BaseIPythonApplication.ipython_dir',
49 50 'log-level' : 'Application.log_level',
50 51 'config' : 'BaseIPythonApplication.extra_config_file',
51 52 }
52 53
53 54 base_flags = dict(
54 55 debug = ({'Application' : {'log_level' : logging.DEBUG}},
55 56 "set log level to logging.DEBUG (maximize logging output)"),
56 57 quiet = ({'Application' : {'log_level' : logging.CRITICAL}},
57 58 "set log level to logging.CRITICAL (minimize logging output)"),
58 59 init = ({'BaseIPythonApplication' : {
59 60 'copy_config_files' : True,
60 61 'auto_create' : True}
61 62 }, """Initialize profile with default config files. This is equivalent
62 63 to running `ipython profile create <profile>` prior to startup.
63 64 """)
64 65 )
65 66
66 67 class ProfileAwareConfigLoader(PyFileConfigLoader):
67 68 """A Python file config loader that is aware of IPython profiles."""
68 69 def load_subconfig(self, fname, path=None, profile=None):
69 70 if profile is not None:
70 71 try:
71 72 profile_dir = ProfileDir.find_profile_dir_by_name(
72 73 get_ipython_dir(),
73 74 profile,
74 75 )
75 76 except ProfileDirError:
76 77 return
77 78 path = profile_dir.location
78 79 return super(ProfileAwareConfigLoader, self).load_subconfig(fname, path=path)
79 80
80 81 class BaseIPythonApplication(Application):
81 82
82 83 name = Unicode(u'ipython')
83 84 description = Unicode(u'IPython: an enhanced interactive Python shell.')
84 85 version = Unicode(release.version)
85 86
86 87 aliases = Dict(base_aliases)
87 88 flags = Dict(base_flags)
88 89 classes = List([ProfileDir])
89 90
90 91 # enable `load_subconfig('cfg.py', profile='name')`
91 92 python_config_loader_class = ProfileAwareConfigLoader
92 93
93 94 # Track whether the config_file has changed,
94 95 # because some logic happens only if we aren't using the default.
95 96 config_file_specified = Set()
96 97
97 98 config_file_name = Unicode()
98 99 def _config_file_name_default(self):
99 100 return self.name.replace('-','_') + u'_config.py'
100 101 def _config_file_name_changed(self, name, old, new):
101 102 if new != old:
102 103 self.config_file_specified.add(new)
103 104
104 105 # The directory that contains IPython's builtin profiles.
105 106 builtin_profile_dir = Unicode(
106 107 os.path.join(get_ipython_package_dir(), u'config', u'profile', u'default')
107 108 )
108 109
109 110 config_file_paths = List(Unicode)
110 111 def _config_file_paths_default(self):
111 112 return [py3compat.getcwd()]
112 113
113 114 extra_config_file = Unicode(config=True,
114 115 help="""Path to an extra config file to load.
115 116
116 117 If specified, load this config file in addition to any other IPython config.
117 118 """)
118 119 def _extra_config_file_changed(self, name, old, new):
119 120 try:
120 121 self.config_files.remove(old)
121 122 except ValueError:
122 123 pass
123 124 self.config_file_specified.add(new)
124 125 self.config_files.append(new)
125 126
126 127 profile = Unicode(u'default', config=True,
127 128 help="""The IPython profile to use."""
128 129 )
129 130
130 131 def _profile_changed(self, name, old, new):
131 132 self.builtin_profile_dir = os.path.join(
132 133 get_ipython_package_dir(), u'config', u'profile', new
133 134 )
134 135
135 136 ipython_dir = Unicode(config=True,
136 137 help="""
137 138 The name of the IPython directory. This directory is used for logging
138 139 configuration (through profiles), history storage, etc. The default
139 140 is usually $HOME/.ipython. This option can also be specified through
140 141 the environment variable IPYTHONDIR.
141 142 """
142 143 )
143 144 def _ipython_dir_default(self):
144 145 d = get_ipython_dir()
145 146 self._ipython_dir_changed('ipython_dir', d, d)
146 147 return d
147 148
148 149 _in_init_profile_dir = False
149 150 profile_dir = Instance(ProfileDir, allow_none=True)
150 151 def _profile_dir_default(self):
151 152 # avoid recursion
152 153 if self._in_init_profile_dir:
153 154 return
154 155 # profile_dir requested early, force initialization
155 156 self.init_profile_dir()
156 157 return self.profile_dir
157 158
158 159 overwrite = Bool(False, config=True,
159 160 help="""Whether to overwrite existing config files when copying""")
160 161 auto_create = Bool(False, config=True,
161 162 help="""Whether to create profile dir if it doesn't exist""")
162 163
163 164 config_files = List(Unicode)
164 165 def _config_files_default(self):
165 166 return [self.config_file_name]
166 167
167 168 copy_config_files = Bool(False, config=True,
168 169 help="""Whether to install the default config files into the profile dir.
169 170 If a new profile is being created, and IPython contains config files for that
170 171 profile, then they will be staged into the new directory. Otherwise,
171 172 default config files will be automatically generated.
172 173 """)
173 174
174 175 verbose_crash = Bool(False, config=True,
175 176 help="""Create a massive crash report when IPython encounters what may be an
176 177 internal error. The default is to append a short message to the
177 178 usual traceback""")
178 179
179 180 # The class to use as the crash handler.
180 181 crash_handler_class = Type(crashhandler.CrashHandler)
181 182
182 183 @catch_config_error
183 184 def __init__(self, **kwargs):
184 185 super(BaseIPythonApplication, self).__init__(**kwargs)
185 186 # ensure current working directory exists
186 187 try:
187 188 directory = py3compat.getcwd()
188 189 except:
189 190 # exit if cwd doesn't exist
190 191 self.log.error("Current working directory doesn't exist.")
191 192 self.exit(1)
192 193
193 194 #-------------------------------------------------------------------------
194 195 # Various stages of Application creation
195 196 #-------------------------------------------------------------------------
196 197
197 198 def init_crash_handler(self):
198 199 """Create a crash handler, typically setting sys.excepthook to it."""
199 200 self.crash_handler = self.crash_handler_class(self)
200 201 sys.excepthook = self.excepthook
201 202 def unset_crashhandler():
202 203 sys.excepthook = sys.__excepthook__
203 204 atexit.register(unset_crashhandler)
204 205
205 206 def excepthook(self, etype, evalue, tb):
206 207 """this is sys.excepthook after init_crashhandler
207 208
208 209 set self.verbose_crash=True to use our full crashhandler, instead of
209 210 a regular traceback with a short message (crash_handler_lite)
210 211 """
211 212
212 213 if self.verbose_crash:
213 214 return self.crash_handler(etype, evalue, tb)
214 215 else:
215 216 return crashhandler.crash_handler_lite(etype, evalue, tb)
216 217
217 218 def _ipython_dir_changed(self, name, old, new):
218 219 if old is not Undefined:
219 220 str_old = py3compat.cast_bytes_py2(os.path.abspath(old),
220 221 sys.getfilesystemencoding()
221 222 )
222 223 if str_old in sys.path:
223 224 sys.path.remove(str_old)
224 225 str_path = py3compat.cast_bytes_py2(os.path.abspath(new),
225 226 sys.getfilesystemencoding()
226 227 )
227 228 sys.path.append(str_path)
228 229 ensure_dir_exists(new)
229 230 readme = os.path.join(new, 'README')
230 231 readme_src = os.path.join(get_ipython_package_dir(), u'config', u'profile', 'README')
231 232 if not os.path.exists(readme) and os.path.exists(readme_src):
232 233 shutil.copy(readme_src, readme)
233 234 for d in ('extensions', 'nbextensions'):
234 235 path = os.path.join(new, d)
235 236 try:
236 237 ensure_dir_exists(path)
237 238 except OSError:
238 239 # this will not be EEXIST
239 240 self.log.error("couldn't create path %s: %s", path, e)
240 241 self.log.debug("IPYTHONDIR set to: %s" % new)
241 242
242 243 def load_config_file(self, suppress_errors=True):
243 244 """Load the config file.
244 245
245 246 By default, errors in loading config are handled, and a warning
246 247 printed on screen. For testing, the suppress_errors option is set
247 248 to False, so errors will make tests fail.
248 249 """
249 250 self.log.debug("Searching path %s for config files", self.config_file_paths)
250 251 base_config = 'ipython_config.py'
251 252 self.log.debug("Attempting to load config file: %s" %
252 253 base_config)
253 254 try:
254 255 Application.load_config_file(
255 256 self,
256 257 base_config,
257 258 path=self.config_file_paths
258 259 )
259 260 except ConfigFileNotFound:
260 261 # ignore errors loading parent
261 262 self.log.debug("Config file %s not found", base_config)
262 263 pass
263 264
264 265 for config_file_name in self.config_files:
265 266 if not config_file_name or config_file_name == base_config:
266 267 continue
267 268 self.log.debug("Attempting to load config file: %s" %
268 269 self.config_file_name)
269 270 try:
270 271 Application.load_config_file(
271 272 self,
272 273 config_file_name,
273 274 path=self.config_file_paths
274 275 )
275 276 except ConfigFileNotFound:
276 277 # Only warn if the default config file was NOT being used.
277 278 if config_file_name in self.config_file_specified:
278 279 msg = self.log.warn
279 280 else:
280 281 msg = self.log.debug
281 282 msg("Config file not found, skipping: %s", config_file_name)
282 283 except:
283 284 # For testing purposes.
284 285 if not suppress_errors:
285 286 raise
286 287 self.log.warn("Error loading config file: %s" %
287 288 self.config_file_name, exc_info=True)
288 289
289 290 def init_profile_dir(self):
290 291 """initialize the profile dir"""
291 292 self._in_init_profile_dir = True
292 293 if self.profile_dir is not None:
293 294 # already ran
294 295 return
295 296 if 'ProfileDir.location' not in self.config:
296 297 # location not specified, find by profile name
297 298 try:
298 299 p = ProfileDir.find_profile_dir_by_name(self.ipython_dir, self.profile, self.config)
299 300 except ProfileDirError:
300 301 # not found, maybe create it (always create default profile)
301 302 if self.auto_create or self.profile == 'default':
302 303 try:
303 304 p = ProfileDir.create_profile_dir_by_name(self.ipython_dir, self.profile, self.config)
304 305 except ProfileDirError:
305 306 self.log.fatal("Could not create profile: %r"%self.profile)
306 307 self.exit(1)
307 308 else:
308 309 self.log.info("Created profile dir: %r"%p.location)
309 310 else:
310 311 self.log.fatal("Profile %r not found."%self.profile)
311 312 self.exit(1)
312 313 else:
313 314 self.log.debug("Using existing profile dir: %r"%p.location)
314 315 else:
315 316 location = self.config.ProfileDir.location
316 317 # location is fully specified
317 318 try:
318 319 p = ProfileDir.find_profile_dir(location, self.config)
319 320 except ProfileDirError:
320 321 # not found, maybe create it
321 322 if self.auto_create:
322 323 try:
323 324 p = ProfileDir.create_profile_dir(location, self.config)
324 325 except ProfileDirError:
325 326 self.log.fatal("Could not create profile directory: %r"%location)
326 327 self.exit(1)
327 328 else:
328 329 self.log.debug("Creating new profile dir: %r"%location)
329 330 else:
330 331 self.log.fatal("Profile directory %r not found."%location)
331 332 self.exit(1)
332 333 else:
333 334 self.log.info("Using existing profile dir: %r"%location)
334 335 # if profile_dir is specified explicitly, set profile name
335 336 dir_name = os.path.basename(p.location)
336 337 if dir_name.startswith('profile_'):
337 338 self.profile = dir_name[8:]
338 339
339 340 self.profile_dir = p
340 341 self.config_file_paths.append(p.location)
341 342 self._in_init_profile_dir = False
342 343
343 344 def init_config_files(self):
344 345 """[optionally] copy default config files into profile dir."""
345 346 self.config_file_paths.extend(SYSTEM_CONFIG_DIRS)
346 347 # copy config files
347 348 path = self.builtin_profile_dir
348 349 if self.copy_config_files:
349 350 src = self.profile
350 351
351 352 cfg = self.config_file_name
352 353 if path and os.path.exists(os.path.join(path, cfg)):
353 354 self.log.warn("Staging %r from %s into %r [overwrite=%s]"%(
354 355 cfg, src, self.profile_dir.location, self.overwrite)
355 356 )
356 357 self.profile_dir.copy_config_file(cfg, path=path, overwrite=self.overwrite)
357 358 else:
358 359 self.stage_default_config_file()
359 360 else:
360 361 # Still stage *bundled* config files, but not generated ones
361 362 # This is necessary for `ipython profile=sympy` to load the profile
362 363 # on the first go
363 364 files = glob.glob(os.path.join(path, '*.py'))
364 365 for fullpath in files:
365 366 cfg = os.path.basename(fullpath)
366 367 if self.profile_dir.copy_config_file(cfg, path=path, overwrite=False):
367 368 # file was copied
368 369 self.log.warn("Staging bundled %s from %s into %r"%(
369 370 cfg, self.profile, self.profile_dir.location)
370 371 )
371 372
372 373
373 374 def stage_default_config_file(self):
374 375 """auto generate default config file, and stage it into the profile."""
375 376 s = self.generate_config_file()
376 377 fname = os.path.join(self.profile_dir.location, self.config_file_name)
377 378 if self.overwrite or not os.path.exists(fname):
378 379 self.log.warn("Generating default config file: %r"%(fname))
379 380 with open(fname, 'w') as f:
380 381 f.write(s)
381 382
382 383 @catch_config_error
383 384 def initialize(self, argv=None):
384 385 # don't hook up crash handler before parsing command-line
385 386 self.parse_command_line(argv)
386 387 self.init_crash_handler()
387 388 if self.subapp is not None:
388 389 # stop here if subapp is taking over
389 390 return
390 391 cl_config = self.config
391 392 self.init_profile_dir()
392 393 self.init_config_files()
393 394 self.load_config_file()
394 395 # enforce cl-opts override configfile opts:
395 396 self.update_config(cl_config)
396 397
@@ -1,112 +1,112 b''
1 1 """
2 2 A context manager for managing things injected into :mod:`__builtin__`.
3 3
4 4 Authors:
5 5
6 6 * Brian Granger
7 7 * Fernando Perez
8 8 """
9 9 #-----------------------------------------------------------------------------
10 10 # Copyright (C) 2010-2011 The IPython Development Team.
11 11 #
12 12 # Distributed under the terms of the BSD License.
13 13 #
14 14 # Complete license in the file COPYING.txt, distributed with this software.
15 15 #-----------------------------------------------------------------------------
16 16
17 17 #-----------------------------------------------------------------------------
18 18 # Imports
19 19 #-----------------------------------------------------------------------------
20 20
21 from IPython.config.configurable import Configurable
21 from traitlets.config.configurable import Configurable
22 22
23 23 from IPython.utils.py3compat import builtin_mod, iteritems
24 from IPython.utils.traitlets import Instance
24 from traitlets import Instance
25 25
26 26 #-----------------------------------------------------------------------------
27 27 # Classes and functions
28 28 #-----------------------------------------------------------------------------
29 29
30 30 class __BuiltinUndefined(object): pass
31 31 BuiltinUndefined = __BuiltinUndefined()
32 32
33 33 class __HideBuiltin(object): pass
34 34 HideBuiltin = __HideBuiltin()
35 35
36 36
37 37 class BuiltinTrap(Configurable):
38 38
39 39 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
40 40 allow_none=True)
41 41
42 42 def __init__(self, shell=None):
43 43 super(BuiltinTrap, self).__init__(shell=shell, config=None)
44 44 self._orig_builtins = {}
45 45 # We define this to track if a single BuiltinTrap is nested.
46 46 # Only turn off the trap when the outermost call to __exit__ is made.
47 47 self._nested_level = 0
48 48 self.shell = shell
49 49 # builtins we always add - if set to HideBuiltin, they will just
50 50 # be removed instead of being replaced by something else
51 51 self.auto_builtins = {'exit': HideBuiltin,
52 52 'quit': HideBuiltin,
53 53 'get_ipython': self.shell.get_ipython,
54 54 }
55 55 # Recursive reload function
56 56 try:
57 57 from IPython.lib import deepreload
58 58 if self.shell.deep_reload:
59 59 self.auto_builtins['reload'] = deepreload.reload
60 60 else:
61 61 self.auto_builtins['dreload']= deepreload.reload
62 62 except ImportError:
63 63 pass
64 64
65 65 def __enter__(self):
66 66 if self._nested_level == 0:
67 67 self.activate()
68 68 self._nested_level += 1
69 69 # I return self, so callers can use add_builtin in a with clause.
70 70 return self
71 71
72 72 def __exit__(self, type, value, traceback):
73 73 if self._nested_level == 1:
74 74 self.deactivate()
75 75 self._nested_level -= 1
76 76 # Returning False will cause exceptions to propagate
77 77 return False
78 78
79 79 def add_builtin(self, key, value):
80 80 """Add a builtin and save the original."""
81 81 bdict = builtin_mod.__dict__
82 82 orig = bdict.get(key, BuiltinUndefined)
83 83 if value is HideBuiltin:
84 84 if orig is not BuiltinUndefined: #same as 'key in bdict'
85 85 self._orig_builtins[key] = orig
86 86 del bdict[key]
87 87 else:
88 88 self._orig_builtins[key] = orig
89 89 bdict[key] = value
90 90
91 91 def remove_builtin(self, key, orig):
92 92 """Remove an added builtin and re-set the original."""
93 93 if orig is BuiltinUndefined:
94 94 del builtin_mod.__dict__[key]
95 95 else:
96 96 builtin_mod.__dict__[key] = orig
97 97
98 98 def activate(self):
99 99 """Store ipython references in the __builtin__ namespace."""
100 100
101 101 add_builtin = self.add_builtin
102 102 for name, func in iteritems(self.auto_builtins):
103 103 add_builtin(name, func)
104 104
105 105 def deactivate(self):
106 106 """Remove any builtins which might have been added by add_builtins, or
107 107 restore overwritten ones to their previous values."""
108 108 remove_builtin = self.remove_builtin
109 109 for key, val in iteritems(self._orig_builtins):
110 110 remove_builtin(key, val)
111 111 self._orig_builtins.clear()
112 112 self._builtins_added = False
@@ -1,1266 +1,1266 b''
1 1 # encoding: utf-8
2 2 """Word completion for IPython.
3 3
4 4 This module is a fork of the rlcompleter module in the Python standard
5 5 library. The original enhancements made to rlcompleter have been sent
6 6 upstream and were accepted as of Python 2.3, but we need a lot more
7 7 functionality specific to IPython, so this module will continue to live as an
8 8 IPython-specific utility.
9 9
10 10 Original rlcompleter documentation:
11 11
12 12 This requires the latest extension to the readline module (the
13 13 completes keywords, built-ins and globals in __main__; when completing
14 14 NAME.NAME..., it evaluates (!) the expression up to the last dot and
15 15 completes its attributes.
16 16
17 17 It's very cool to do "import string" type "string.", hit the
18 18 completion key (twice), and see the list of names defined by the
19 19 string module!
20 20
21 21 Tip: to use the tab key as the completion key, call
22 22
23 23 readline.parse_and_bind("tab: complete")
24 24
25 25 Notes:
26 26
27 27 - Exceptions raised by the completer function are *ignored* (and
28 28 generally cause the completion to fail). This is a feature -- since
29 29 readline sets the tty device in raw (or cbreak) mode, printing a
30 30 traceback wouldn't work well without some complicated hoopla to save,
31 31 reset and restore the tty state.
32 32
33 33 - The evaluation of the NAME.NAME... form may cause arbitrary
34 34 application defined code to be executed if an object with a
35 35 ``__getattr__`` hook is found. Since it is the responsibility of the
36 36 application (or the user) to enable this feature, I consider this an
37 37 acceptable risk. More complicated expressions (e.g. function calls or
38 38 indexing operations) are *not* evaluated.
39 39
40 40 - GNU readline is also used by the built-in functions input() and
41 41 raw_input(), and thus these also benefit/suffer from the completer
42 42 features. Clearly an interactive application can benefit by
43 43 specifying its own completer function and using raw_input() for all
44 44 its input.
45 45
46 46 - When the original stdin is not a tty device, GNU readline is never
47 47 used, and this module (and the readline module) are silently inactive.
48 48 """
49 49
50 50 # Copyright (c) IPython Development Team.
51 51 # Distributed under the terms of the Modified BSD License.
52 52 #
53 53 # Some of this code originated from rlcompleter in the Python standard library
54 54 # Copyright (C) 2001 Python Software Foundation, www.python.org
55 55
56 56 import __main__
57 57 import glob
58 58 import inspect
59 59 import itertools
60 60 import keyword
61 61 import os
62 62 import re
63 63 import sys
64 64 import unicodedata
65 65 import string
66 66
67 from IPython.config.configurable import Configurable
67 from traitlets.config.configurable import Configurable
68 68 from IPython.core.error import TryNext
69 69 from IPython.core.inputsplitter import ESC_MAGIC
70 70 from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
71 71 from IPython.utils import generics
72 72 from IPython.utils import io
73 73 from IPython.utils.decorators import undoc
74 74 from IPython.utils.dir2 import dir2
75 75 from IPython.utils.process import arg_split
76 76 from IPython.utils.py3compat import builtin_mod, string_types, PY3
77 from IPython.utils.traitlets import CBool, Enum
77 from traitlets import CBool, Enum
78 78
79 79 #-----------------------------------------------------------------------------
80 80 # Globals
81 81 #-----------------------------------------------------------------------------
82 82
83 83 # Public API
84 84 __all__ = ['Completer','IPCompleter']
85 85
86 86 if sys.platform == 'win32':
87 87 PROTECTABLES = ' '
88 88 else:
89 89 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
90 90
91 91
92 92 #-----------------------------------------------------------------------------
93 93 # Main functions and classes
94 94 #-----------------------------------------------------------------------------
95 95
96 96 def has_open_quotes(s):
97 97 """Return whether a string has open quotes.
98 98
99 99 This simply counts whether the number of quote characters of either type in
100 100 the string is odd.
101 101
102 102 Returns
103 103 -------
104 104 If there is an open quote, the quote character is returned. Else, return
105 105 False.
106 106 """
107 107 # We check " first, then ', so complex cases with nested quotes will get
108 108 # the " to take precedence.
109 109 if s.count('"') % 2:
110 110 return '"'
111 111 elif s.count("'") % 2:
112 112 return "'"
113 113 else:
114 114 return False
115 115
116 116
117 117 def protect_filename(s):
118 118 """Escape a string to protect certain characters."""
119 119
120 120 return "".join([(ch in PROTECTABLES and '\\' + ch or ch)
121 121 for ch in s])
122 122
123 123 def expand_user(path):
124 124 """Expand '~'-style usernames in strings.
125 125
126 126 This is similar to :func:`os.path.expanduser`, but it computes and returns
127 127 extra information that will be useful if the input was being used in
128 128 computing completions, and you wish to return the completions with the
129 129 original '~' instead of its expanded value.
130 130
131 131 Parameters
132 132 ----------
133 133 path : str
134 134 String to be expanded. If no ~ is present, the output is the same as the
135 135 input.
136 136
137 137 Returns
138 138 -------
139 139 newpath : str
140 140 Result of ~ expansion in the input path.
141 141 tilde_expand : bool
142 142 Whether any expansion was performed or not.
143 143 tilde_val : str
144 144 The value that ~ was replaced with.
145 145 """
146 146 # Default values
147 147 tilde_expand = False
148 148 tilde_val = ''
149 149 newpath = path
150 150
151 151 if path.startswith('~'):
152 152 tilde_expand = True
153 153 rest = len(path)-1
154 154 newpath = os.path.expanduser(path)
155 155 if rest:
156 156 tilde_val = newpath[:-rest]
157 157 else:
158 158 tilde_val = newpath
159 159
160 160 return newpath, tilde_expand, tilde_val
161 161
162 162
163 163 def compress_user(path, tilde_expand, tilde_val):
164 164 """Does the opposite of expand_user, with its outputs.
165 165 """
166 166 if tilde_expand:
167 167 return path.replace(tilde_val, '~')
168 168 else:
169 169 return path
170 170
171 171
172 172
173 173 def penalize_magics_key(word):
174 174 """key for sorting that penalizes magic commands in the ordering
175 175
176 176 Normal words are left alone.
177 177
178 178 Magic commands have the initial % moved to the end, e.g.
179 179 %matplotlib is transformed as follows:
180 180
181 181 %matplotlib -> matplotlib%
182 182
183 183 [The choice of the final % is arbitrary.]
184 184
185 185 Since "matplotlib" < "matplotlib%" as strings,
186 186 "timeit" will appear before the magic "%timeit" in the ordering
187 187
188 188 For consistency, move "%%" to the end, so cell magics appear *after*
189 189 line magics with the same name.
190 190
191 191 A check is performed that there are no other "%" in the string;
192 192 if there are, then the string is not a magic command and is left unchanged.
193 193
194 194 """
195 195
196 196 # Move any % signs from start to end of the key
197 197 # provided there are no others elsewhere in the string
198 198
199 199 if word[:2] == "%%":
200 200 if not "%" in word[2:]:
201 201 return word[2:] + "%%"
202 202
203 203 if word[:1] == "%":
204 204 if not "%" in word[1:]:
205 205 return word[1:] + "%"
206 206
207 207 return word
208 208
209 209
210 210 @undoc
211 211 class Bunch(object): pass
212 212
213 213
214 214 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
215 215 GREEDY_DELIMS = ' =\r\n'
216 216
217 217
218 218 class CompletionSplitter(object):
219 219 """An object to split an input line in a manner similar to readline.
220 220
221 221 By having our own implementation, we can expose readline-like completion in
222 222 a uniform manner to all frontends. This object only needs to be given the
223 223 line of text to be split and the cursor position on said line, and it
224 224 returns the 'word' to be completed on at the cursor after splitting the
225 225 entire line.
226 226
227 227 What characters are used as splitting delimiters can be controlled by
228 228 setting the `delims` attribute (this is a property that internally
229 229 automatically builds the necessary regular expression)"""
230 230
231 231 # Private interface
232 232
233 233 # A string of delimiter characters. The default value makes sense for
234 234 # IPython's most typical usage patterns.
235 235 _delims = DELIMS
236 236
237 237 # The expression (a normal string) to be compiled into a regular expression
238 238 # for actual splitting. We store it as an attribute mostly for ease of
239 239 # debugging, since this type of code can be so tricky to debug.
240 240 _delim_expr = None
241 241
242 242 # The regular expression that does the actual splitting
243 243 _delim_re = None
244 244
245 245 def __init__(self, delims=None):
246 246 delims = CompletionSplitter._delims if delims is None else delims
247 247 self.delims = delims
248 248
249 249 @property
250 250 def delims(self):
251 251 """Return the string of delimiter characters."""
252 252 return self._delims
253 253
254 254 @delims.setter
255 255 def delims(self, delims):
256 256 """Set the delimiters for line splitting."""
257 257 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
258 258 self._delim_re = re.compile(expr)
259 259 self._delims = delims
260 260 self._delim_expr = expr
261 261
262 262 def split_line(self, line, cursor_pos=None):
263 263 """Split a line of text with a cursor at the given position.
264 264 """
265 265 l = line if cursor_pos is None else line[:cursor_pos]
266 266 return self._delim_re.split(l)[-1]
267 267
268 268
269 269 class Completer(Configurable):
270 270
271 271 greedy = CBool(False, config=True,
272 272 help="""Activate greedy completion
273 273
274 274 This will enable completion on elements of lists, results of function calls, etc.,
275 275 but can be unsafe because the code is actually evaluated on TAB.
276 276 """
277 277 )
278 278
279 279
280 280 def __init__(self, namespace=None, global_namespace=None, **kwargs):
281 281 """Create a new completer for the command line.
282 282
283 283 Completer(namespace=ns,global_namespace=ns2) -> completer instance.
284 284
285 285 If unspecified, the default namespace where completions are performed
286 286 is __main__ (technically, __main__.__dict__). Namespaces should be
287 287 given as dictionaries.
288 288
289 289 An optional second namespace can be given. This allows the completer
290 290 to handle cases where both the local and global scopes need to be
291 291 distinguished.
292 292
293 293 Completer instances should be used as the completion mechanism of
294 294 readline via the set_completer() call:
295 295
296 296 readline.set_completer(Completer(my_namespace).complete)
297 297 """
298 298
299 299 # Don't bind to namespace quite yet, but flag whether the user wants a
300 300 # specific namespace or to use __main__.__dict__. This will allow us
301 301 # to bind to __main__.__dict__ at completion time, not now.
302 302 if namespace is None:
303 303 self.use_main_ns = 1
304 304 else:
305 305 self.use_main_ns = 0
306 306 self.namespace = namespace
307 307
308 308 # The global namespace, if given, can be bound directly
309 309 if global_namespace is None:
310 310 self.global_namespace = {}
311 311 else:
312 312 self.global_namespace = global_namespace
313 313
314 314 super(Completer, self).__init__(**kwargs)
315 315
316 316 def complete(self, text, state):
317 317 """Return the next possible completion for 'text'.
318 318
319 319 This is called successively with state == 0, 1, 2, ... until it
320 320 returns None. The completion should begin with 'text'.
321 321
322 322 """
323 323 if self.use_main_ns:
324 324 self.namespace = __main__.__dict__
325 325
326 326 if state == 0:
327 327 if "." in text:
328 328 self.matches = self.attr_matches(text)
329 329 else:
330 330 self.matches = self.global_matches(text)
331 331 try:
332 332 return self.matches[state]
333 333 except IndexError:
334 334 return None
335 335
336 336 def global_matches(self, text):
337 337 """Compute matches when text is a simple name.
338 338
339 339 Return a list of all keywords, built-in functions and names currently
340 340 defined in self.namespace or self.global_namespace that match.
341 341
342 342 """
343 343 #print 'Completer->global_matches, txt=%r' % text # dbg
344 344 matches = []
345 345 match_append = matches.append
346 346 n = len(text)
347 347 for lst in [keyword.kwlist,
348 348 builtin_mod.__dict__.keys(),
349 349 self.namespace.keys(),
350 350 self.global_namespace.keys()]:
351 351 for word in lst:
352 352 if word[:n] == text and word != "__builtins__":
353 353 match_append(word)
354 354 return matches
355 355
356 356 def attr_matches(self, text):
357 357 """Compute matches when text contains a dot.
358 358
359 359 Assuming the text is of the form NAME.NAME....[NAME], and is
360 360 evaluatable in self.namespace or self.global_namespace, it will be
361 361 evaluated and its attributes (as revealed by dir()) are used as
362 362 possible completions. (For class instances, class members are are
363 363 also considered.)
364 364
365 365 WARNING: this can still invoke arbitrary C code, if an object
366 366 with a __getattr__ hook is evaluated.
367 367
368 368 """
369 369
370 370 #io.rprint('Completer->attr_matches, txt=%r' % text) # dbg
371 371 # Another option, seems to work great. Catches things like ''.<tab>
372 372 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
373 373
374 374 if m:
375 375 expr, attr = m.group(1, 3)
376 376 elif self.greedy:
377 377 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
378 378 if not m2:
379 379 return []
380 380 expr, attr = m2.group(1,2)
381 381 else:
382 382 return []
383 383
384 384 try:
385 385 obj = eval(expr, self.namespace)
386 386 except:
387 387 try:
388 388 obj = eval(expr, self.global_namespace)
389 389 except:
390 390 return []
391 391
392 392 if self.limit_to__all__ and hasattr(obj, '__all__'):
393 393 words = get__all__entries(obj)
394 394 else:
395 395 words = dir2(obj)
396 396
397 397 try:
398 398 words = generics.complete_object(obj, words)
399 399 except TryNext:
400 400 pass
401 401 except Exception:
402 402 # Silence errors from completion function
403 403 #raise # dbg
404 404 pass
405 405 # Build match list to return
406 406 n = len(attr)
407 407 res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
408 408 return res
409 409
410 410
411 411 def get__all__entries(obj):
412 412 """returns the strings in the __all__ attribute"""
413 413 try:
414 414 words = getattr(obj, '__all__')
415 415 except:
416 416 return []
417 417
418 418 return [w for w in words if isinstance(w, string_types)]
419 419
420 420
421 421 def match_dict_keys(keys, prefix):
422 422 """Used by dict_key_matches, matching the prefix to a list of keys"""
423 423 if not prefix:
424 424 return None, 0, [repr(k) for k in keys
425 425 if isinstance(k, (string_types, bytes))]
426 426 quote_match = re.search('["\']', prefix)
427 427 quote = quote_match.group()
428 428 try:
429 429 prefix_str = eval(prefix + quote, {})
430 430 except Exception:
431 431 return None, 0, []
432 432
433 433 token_match = re.search(r'\w*$', prefix, re.UNICODE)
434 434 token_start = token_match.start()
435 435 token_prefix = token_match.group()
436 436
437 437 # TODO: support bytes in Py3k
438 438 matched = []
439 439 for key in keys:
440 440 try:
441 441 if not key.startswith(prefix_str):
442 442 continue
443 443 except (AttributeError, TypeError, UnicodeError):
444 444 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
445 445 continue
446 446
447 447 # reformat remainder of key to begin with prefix
448 448 rem = key[len(prefix_str):]
449 449 # force repr wrapped in '
450 450 rem_repr = repr(rem + '"')
451 451 if rem_repr.startswith('u') and prefix[0] not in 'uU':
452 452 # Found key is unicode, but prefix is Py2 string.
453 453 # Therefore attempt to interpret key as string.
454 454 try:
455 455 rem_repr = repr(rem.encode('ascii') + '"')
456 456 except UnicodeEncodeError:
457 457 continue
458 458
459 459 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
460 460 if quote == '"':
461 461 # The entered prefix is quoted with ",
462 462 # but the match is quoted with '.
463 463 # A contained " hence needs escaping for comparison:
464 464 rem_repr = rem_repr.replace('"', '\\"')
465 465
466 466 # then reinsert prefix from start of token
467 467 matched.append('%s%s' % (token_prefix, rem_repr))
468 468 return quote, token_start, matched
469 469
470 470
471 471 def _safe_isinstance(obj, module, class_name):
472 472 """Checks if obj is an instance of module.class_name if loaded
473 473 """
474 474 return (module in sys.modules and
475 475 isinstance(obj, getattr(__import__(module), class_name)))
476 476
477 477
478 478
479 479 def back_unicode_name_matches(text):
480 480 u"""Match unicode characters back to unicode name
481 481
482 482 This does ☃ -> \\snowman
483 483
484 484 Note that snowman is not a valid python3 combining character but will be expanded.
485 485 Though it will not recombine back to the snowman character by the completion machinery.
486 486
487 487 This will not either back-complete standard sequences like \n, \b ...
488 488
489 489 Used on Python 3 only.
490 490 """
491 491 if len(text)<2:
492 492 return u'', ()
493 493 maybe_slash = text[-2]
494 494 if maybe_slash != '\\':
495 495 return u'', ()
496 496
497 497 char = text[-1]
498 498 # no expand on quote for completion in strings.
499 499 # nor backcomplete standard ascii keys
500 500 if char in string.ascii_letters or char in ['"',"'"]:
501 501 return u'', ()
502 502 try :
503 503 unic = unicodedata.name(char)
504 504 return '\\'+char,['\\'+unic]
505 505 except KeyError as e:
506 506 pass
507 507 return u'', ()
508 508
509 509 def back_latex_name_matches(text):
510 510 u"""Match latex characters back to unicode name
511 511
512 512 This does ->\\sqrt
513 513
514 514 Used on Python 3 only.
515 515 """
516 516 if len(text)<2:
517 517 return u'', ()
518 518 maybe_slash = text[-2]
519 519 if maybe_slash != '\\':
520 520 return u'', ()
521 521
522 522
523 523 char = text[-1]
524 524 # no expand on quote for completion in strings.
525 525 # nor backcomplete standard ascii keys
526 526 if char in string.ascii_letters or char in ['"',"'"]:
527 527 return u'', ()
528 528 try :
529 529 latex = reverse_latex_symbol[char]
530 530 # '\\' replace the \ as well
531 531 return '\\'+char,[latex]
532 532 except KeyError as e:
533 533 pass
534 534 return u'', ()
535 535
536 536
537 537 class IPCompleter(Completer):
538 538 """Extension of the completer class with IPython-specific features"""
539 539
540 540 def _greedy_changed(self, name, old, new):
541 541 """update the splitter and readline delims when greedy is changed"""
542 542 if new:
543 543 self.splitter.delims = GREEDY_DELIMS
544 544 else:
545 545 self.splitter.delims = DELIMS
546 546
547 547 if self.readline:
548 548 self.readline.set_completer_delims(self.splitter.delims)
549 549
550 550 merge_completions = CBool(True, config=True,
551 551 help="""Whether to merge completion results into a single list
552 552
553 553 If False, only the completion results from the first non-empty
554 554 completer will be returned.
555 555 """
556 556 )
557 557 omit__names = Enum((0,1,2), default_value=2, config=True,
558 558 help="""Instruct the completer to omit private method names
559 559
560 560 Specifically, when completing on ``object.<tab>``.
561 561
562 562 When 2 [default]: all names that start with '_' will be excluded.
563 563
564 564 When 1: all 'magic' names (``__foo__``) will be excluded.
565 565
566 566 When 0: nothing will be excluded.
567 567 """
568 568 )
569 569 limit_to__all__ = CBool(default_value=False, config=True,
570 570 help="""Instruct the completer to use __all__ for the completion
571 571
572 572 Specifically, when completing on ``object.<tab>``.
573 573
574 574 When True: only those names in obj.__all__ will be included.
575 575
576 576 When False [default]: the __all__ attribute is ignored
577 577 """
578 578 )
579 579
580 580 def __init__(self, shell=None, namespace=None, global_namespace=None,
581 581 use_readline=True, config=None, **kwargs):
582 582 """IPCompleter() -> completer
583 583
584 584 Return a completer object suitable for use by the readline library
585 585 via readline.set_completer().
586 586
587 587 Inputs:
588 588
589 589 - shell: a pointer to the ipython shell itself. This is needed
590 590 because this completer knows about magic functions, and those can
591 591 only be accessed via the ipython instance.
592 592
593 593 - namespace: an optional dict where completions are performed.
594 594
595 595 - global_namespace: secondary optional dict for completions, to
596 596 handle cases (such as IPython embedded inside functions) where
597 597 both Python scopes are visible.
598 598
599 599 use_readline : bool, optional
600 600 If true, use the readline library. This completer can still function
601 601 without readline, though in that case callers must provide some extra
602 602 information on each call about the current line."""
603 603
604 604 self.magic_escape = ESC_MAGIC
605 605 self.splitter = CompletionSplitter()
606 606
607 607 # Readline configuration, only used by the rlcompleter method.
608 608 if use_readline:
609 609 # We store the right version of readline so that later code
610 610 import IPython.utils.rlineimpl as readline
611 611 self.readline = readline
612 612 else:
613 613 self.readline = None
614 614
615 615 # _greedy_changed() depends on splitter and readline being defined:
616 616 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
617 617 config=config, **kwargs)
618 618
619 619 # List where completion matches will be stored
620 620 self.matches = []
621 621 self.shell = shell
622 622 # Regexp to split filenames with spaces in them
623 623 self.space_name_re = re.compile(r'([^\\] )')
624 624 # Hold a local ref. to glob.glob for speed
625 625 self.glob = glob.glob
626 626
627 627 # Determine if we are running on 'dumb' terminals, like (X)Emacs
628 628 # buffers, to avoid completion problems.
629 629 term = os.environ.get('TERM','xterm')
630 630 self.dumb_terminal = term in ['dumb','emacs']
631 631
632 632 # Special handling of backslashes needed in win32 platforms
633 633 if sys.platform == "win32":
634 634 self.clean_glob = self._clean_glob_win32
635 635 else:
636 636 self.clean_glob = self._clean_glob
637 637
638 638 #regexp to parse docstring for function signature
639 639 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
640 640 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
641 641 #use this if positional argument name is also needed
642 642 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
643 643
644 644 # All active matcher routines for completion
645 645 self.matchers = [self.python_matches,
646 646 self.file_matches,
647 647 self.magic_matches,
648 648 self.python_func_kw_matches,
649 649 self.dict_key_matches,
650 650 ]
651 651
652 652 def all_completions(self, text):
653 653 """
654 654 Wrapper around the complete method for the benefit of emacs
655 655 and pydb.
656 656 """
657 657 return self.complete(text)[1]
658 658
659 659 def _clean_glob(self,text):
660 660 return self.glob("%s*" % text)
661 661
662 662 def _clean_glob_win32(self,text):
663 663 return [f.replace("\\","/")
664 664 for f in self.glob("%s*" % text)]
665 665
666 666 def file_matches(self, text):
667 667 """Match filenames, expanding ~USER type strings.
668 668
669 669 Most of the seemingly convoluted logic in this completer is an
670 670 attempt to handle filenames with spaces in them. And yet it's not
671 671 quite perfect, because Python's readline doesn't expose all of the
672 672 GNU readline details needed for this to be done correctly.
673 673
674 674 For a filename with a space in it, the printed completions will be
675 675 only the parts after what's already been typed (instead of the
676 676 full completions, as is normally done). I don't think with the
677 677 current (as of Python 2.3) Python readline it's possible to do
678 678 better."""
679 679
680 680 #io.rprint('Completer->file_matches: <%r>' % text) # dbg
681 681
682 682 # chars that require escaping with backslash - i.e. chars
683 683 # that readline treats incorrectly as delimiters, but we
684 684 # don't want to treat as delimiters in filename matching
685 685 # when escaped with backslash
686 686 if text.startswith('!'):
687 687 text = text[1:]
688 688 text_prefix = '!'
689 689 else:
690 690 text_prefix = ''
691 691
692 692 text_until_cursor = self.text_until_cursor
693 693 # track strings with open quotes
694 694 open_quotes = has_open_quotes(text_until_cursor)
695 695
696 696 if '(' in text_until_cursor or '[' in text_until_cursor:
697 697 lsplit = text
698 698 else:
699 699 try:
700 700 # arg_split ~ shlex.split, but with unicode bugs fixed by us
701 701 lsplit = arg_split(text_until_cursor)[-1]
702 702 except ValueError:
703 703 # typically an unmatched ", or backslash without escaped char.
704 704 if open_quotes:
705 705 lsplit = text_until_cursor.split(open_quotes)[-1]
706 706 else:
707 707 return []
708 708 except IndexError:
709 709 # tab pressed on empty line
710 710 lsplit = ""
711 711
712 712 if not open_quotes and lsplit != protect_filename(lsplit):
713 713 # if protectables are found, do matching on the whole escaped name
714 714 has_protectables = True
715 715 text0,text = text,lsplit
716 716 else:
717 717 has_protectables = False
718 718 text = os.path.expanduser(text)
719 719
720 720 if text == "":
721 721 return [text_prefix + protect_filename(f) for f in self.glob("*")]
722 722
723 723 # Compute the matches from the filesystem
724 724 m0 = self.clean_glob(text.replace('\\',''))
725 725
726 726 if has_protectables:
727 727 # If we had protectables, we need to revert our changes to the
728 728 # beginning of filename so that we don't double-write the part
729 729 # of the filename we have so far
730 730 len_lsplit = len(lsplit)
731 731 matches = [text_prefix + text0 +
732 732 protect_filename(f[len_lsplit:]) for f in m0]
733 733 else:
734 734 if open_quotes:
735 735 # if we have a string with an open quote, we don't need to
736 736 # protect the names at all (and we _shouldn't_, as it
737 737 # would cause bugs when the filesystem call is made).
738 738 matches = m0
739 739 else:
740 740 matches = [text_prefix +
741 741 protect_filename(f) for f in m0]
742 742
743 743 #io.rprint('mm', matches) # dbg
744 744
745 745 # Mark directories in input list by appending '/' to their names.
746 746 matches = [x+'/' if os.path.isdir(x) else x for x in matches]
747 747 return matches
748 748
749 749 def magic_matches(self, text):
750 750 """Match magics"""
751 751 #print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg
752 752 # Get all shell magics now rather than statically, so magics loaded at
753 753 # runtime show up too.
754 754 lsm = self.shell.magics_manager.lsmagic()
755 755 line_magics = lsm['line']
756 756 cell_magics = lsm['cell']
757 757 pre = self.magic_escape
758 758 pre2 = pre+pre
759 759
760 760 # Completion logic:
761 761 # - user gives %%: only do cell magics
762 762 # - user gives %: do both line and cell magics
763 763 # - no prefix: do both
764 764 # In other words, line magics are skipped if the user gives %% explicitly
765 765 bare_text = text.lstrip(pre)
766 766 comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
767 767 if not text.startswith(pre2):
768 768 comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
769 769 return comp
770 770
771 771 def python_matches(self,text):
772 772 """Match attributes or global python names"""
773 773
774 774 #io.rprint('Completer->python_matches, txt=%r' % text) # dbg
775 775 if "." in text:
776 776 try:
777 777 matches = self.attr_matches(text)
778 778 if text.endswith('.') and self.omit__names:
779 779 if self.omit__names == 1:
780 780 # true if txt is _not_ a __ name, false otherwise:
781 781 no__name = (lambda txt:
782 782 re.match(r'.*\.__.*?__',txt) is None)
783 783 else:
784 784 # true if txt is _not_ a _ name, false otherwise:
785 785 no__name = (lambda txt:
786 786 re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
787 787 matches = filter(no__name, matches)
788 788 except NameError:
789 789 # catches <undefined attributes>.<tab>
790 790 matches = []
791 791 else:
792 792 matches = self.global_matches(text)
793 793
794 794 return matches
795 795
796 796 def _default_arguments_from_docstring(self, doc):
797 797 """Parse the first line of docstring for call signature.
798 798
799 799 Docstring should be of the form 'min(iterable[, key=func])\n'.
800 800 It can also parse cython docstring of the form
801 801 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
802 802 """
803 803 if doc is None:
804 804 return []
805 805
806 806 #care only the firstline
807 807 line = doc.lstrip().splitlines()[0]
808 808
809 809 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
810 810 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
811 811 sig = self.docstring_sig_re.search(line)
812 812 if sig is None:
813 813 return []
814 814 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
815 815 sig = sig.groups()[0].split(',')
816 816 ret = []
817 817 for s in sig:
818 818 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
819 819 ret += self.docstring_kwd_re.findall(s)
820 820 return ret
821 821
822 822 def _default_arguments(self, obj):
823 823 """Return the list of default arguments of obj if it is callable,
824 824 or empty list otherwise."""
825 825 call_obj = obj
826 826 ret = []
827 827 if inspect.isbuiltin(obj):
828 828 pass
829 829 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
830 830 if inspect.isclass(obj):
831 831 #for cython embededsignature=True the constructor docstring
832 832 #belongs to the object itself not __init__
833 833 ret += self._default_arguments_from_docstring(
834 834 getattr(obj, '__doc__', ''))
835 835 # for classes, check for __init__,__new__
836 836 call_obj = (getattr(obj, '__init__', None) or
837 837 getattr(obj, '__new__', None))
838 838 # for all others, check if they are __call__able
839 839 elif hasattr(obj, '__call__'):
840 840 call_obj = obj.__call__
841 841
842 842 ret += self._default_arguments_from_docstring(
843 843 getattr(call_obj, '__doc__', ''))
844 844
845 845 try:
846 846 args,_,_1,defaults = inspect.getargspec(call_obj)
847 847 if defaults:
848 848 ret+=args[-len(defaults):]
849 849 except TypeError:
850 850 pass
851 851
852 852 return list(set(ret))
853 853
854 854 def python_func_kw_matches(self,text):
855 855 """Match named parameters (kwargs) of the last open function"""
856 856
857 857 if "." in text: # a parameter cannot be dotted
858 858 return []
859 859 try: regexp = self.__funcParamsRegex
860 860 except AttributeError:
861 861 regexp = self.__funcParamsRegex = re.compile(r'''
862 862 '.*?(?<!\\)' | # single quoted strings or
863 863 ".*?(?<!\\)" | # double quoted strings or
864 864 \w+ | # identifier
865 865 \S # other characters
866 866 ''', re.VERBOSE | re.DOTALL)
867 867 # 1. find the nearest identifier that comes before an unclosed
868 868 # parenthesis before the cursor
869 869 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
870 870 tokens = regexp.findall(self.text_until_cursor)
871 871 tokens.reverse()
872 872 iterTokens = iter(tokens); openPar = 0
873 873
874 874 for token in iterTokens:
875 875 if token == ')':
876 876 openPar -= 1
877 877 elif token == '(':
878 878 openPar += 1
879 879 if openPar > 0:
880 880 # found the last unclosed parenthesis
881 881 break
882 882 else:
883 883 return []
884 884 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
885 885 ids = []
886 886 isId = re.compile(r'\w+$').match
887 887
888 888 while True:
889 889 try:
890 890 ids.append(next(iterTokens))
891 891 if not isId(ids[-1]):
892 892 ids.pop(); break
893 893 if not next(iterTokens) == '.':
894 894 break
895 895 except StopIteration:
896 896 break
897 897 # lookup the candidate callable matches either using global_matches
898 898 # or attr_matches for dotted names
899 899 if len(ids) == 1:
900 900 callableMatches = self.global_matches(ids[0])
901 901 else:
902 902 callableMatches = self.attr_matches('.'.join(ids[::-1]))
903 903 argMatches = []
904 904 for callableMatch in callableMatches:
905 905 try:
906 906 namedArgs = self._default_arguments(eval(callableMatch,
907 907 self.namespace))
908 908 except:
909 909 continue
910 910
911 911 for namedArg in namedArgs:
912 912 if namedArg.startswith(text):
913 913 argMatches.append("%s=" %namedArg)
914 914 return argMatches
915 915
916 916 def dict_key_matches(self, text):
917 917 "Match string keys in a dictionary, after e.g. 'foo[' "
918 918 def get_keys(obj):
919 919 # Only allow completion for known in-memory dict-like types
920 920 if isinstance(obj, dict) or\
921 921 _safe_isinstance(obj, 'pandas', 'DataFrame'):
922 922 try:
923 923 return list(obj.keys())
924 924 except Exception:
925 925 return []
926 926 elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
927 927 _safe_isinstance(obj, 'numpy', 'void'):
928 928 return obj.dtype.names or []
929 929 return []
930 930
931 931 try:
932 932 regexps = self.__dict_key_regexps
933 933 except AttributeError:
934 934 dict_key_re_fmt = r'''(?x)
935 935 ( # match dict-referring expression wrt greedy setting
936 936 %s
937 937 )
938 938 \[ # open bracket
939 939 \s* # and optional whitespace
940 940 ([uUbB]? # string prefix (r not handled)
941 941 (?: # unclosed string
942 942 '(?:[^']|(?<!\\)\\')*
943 943 |
944 944 "(?:[^"]|(?<!\\)\\")*
945 945 )
946 946 )?
947 947 $
948 948 '''
949 949 regexps = self.__dict_key_regexps = {
950 950 False: re.compile(dict_key_re_fmt % '''
951 951 # identifiers separated by .
952 952 (?!\d)\w+
953 953 (?:\.(?!\d)\w+)*
954 954 '''),
955 955 True: re.compile(dict_key_re_fmt % '''
956 956 .+
957 957 ''')
958 958 }
959 959
960 960 match = regexps[self.greedy].search(self.text_until_cursor)
961 961 if match is None:
962 962 return []
963 963
964 964 expr, prefix = match.groups()
965 965 try:
966 966 obj = eval(expr, self.namespace)
967 967 except Exception:
968 968 try:
969 969 obj = eval(expr, self.global_namespace)
970 970 except Exception:
971 971 return []
972 972
973 973 keys = get_keys(obj)
974 974 if not keys:
975 975 return keys
976 976 closing_quote, token_offset, matches = match_dict_keys(keys, prefix)
977 977 if not matches:
978 978 return matches
979 979
980 980 # get the cursor position of
981 981 # - the text being completed
982 982 # - the start of the key text
983 983 # - the start of the completion
984 984 text_start = len(self.text_until_cursor) - len(text)
985 985 if prefix:
986 986 key_start = match.start(2)
987 987 completion_start = key_start + token_offset
988 988 else:
989 989 key_start = completion_start = match.end()
990 990
991 991 # grab the leading prefix, to make sure all completions start with `text`
992 992 if text_start > key_start:
993 993 leading = ''
994 994 else:
995 995 leading = text[text_start:completion_start]
996 996
997 997 # the index of the `[` character
998 998 bracket_idx = match.end(1)
999 999
1000 1000 # append closing quote and bracket as appropriate
1001 1001 # this is *not* appropriate if the opening quote or bracket is outside
1002 1002 # the text given to this method
1003 1003 suf = ''
1004 1004 continuation = self.line_buffer[len(self.text_until_cursor):]
1005 1005 if key_start > text_start and closing_quote:
1006 1006 # quotes were opened inside text, maybe close them
1007 1007 if continuation.startswith(closing_quote):
1008 1008 continuation = continuation[len(closing_quote):]
1009 1009 else:
1010 1010 suf += closing_quote
1011 1011 if bracket_idx > text_start:
1012 1012 # brackets were opened inside text, maybe close them
1013 1013 if not continuation.startswith(']'):
1014 1014 suf += ']'
1015 1015
1016 1016 return [leading + k + suf for k in matches]
1017 1017
1018 1018 def unicode_name_matches(self, text):
1019 1019 u"""Match Latex-like syntax for unicode characters base
1020 1020 on the name of the character.
1021 1021
1022 1022 This does \\GREEK SMALL LETTER ETA -> η
1023 1023
1024 1024 Works only on valid python 3 identifier, or on combining characters that
1025 1025 will combine to form a valid identifier.
1026 1026
1027 1027 Used on Python 3 only.
1028 1028 """
1029 1029 slashpos = text.rfind('\\')
1030 1030 if slashpos > -1:
1031 1031 s = text[slashpos+1:]
1032 1032 try :
1033 1033 unic = unicodedata.lookup(s)
1034 1034 # allow combining chars
1035 1035 if ('a'+unic).isidentifier():
1036 1036 return '\\'+s,[unic]
1037 1037 except KeyError as e:
1038 1038 pass
1039 1039 return u'', []
1040 1040
1041 1041
1042 1042
1043 1043
1044 1044 def latex_matches(self, text):
1045 1045 u"""Match Latex syntax for unicode characters.
1046 1046
1047 1047 This does both \\alp -> \\alpha and \\alpha -> α
1048 1048
1049 1049 Used on Python 3 only.
1050 1050 """
1051 1051 slashpos = text.rfind('\\')
1052 1052 if slashpos > -1:
1053 1053 s = text[slashpos:]
1054 1054 if s in latex_symbols:
1055 1055 # Try to complete a full latex symbol to unicode
1056 1056 # \\alpha -> α
1057 1057 return s, [latex_symbols[s]]
1058 1058 else:
1059 1059 # If a user has partially typed a latex symbol, give them
1060 1060 # a full list of options \al -> [\aleph, \alpha]
1061 1061 matches = [k for k in latex_symbols if k.startswith(s)]
1062 1062 return s, matches
1063 1063 return u'', []
1064 1064
1065 1065 def dispatch_custom_completer(self, text):
1066 1066 #io.rprint("Custom! '%s' %s" % (text, self.custom_completers)) # dbg
1067 1067 line = self.line_buffer
1068 1068 if not line.strip():
1069 1069 return None
1070 1070
1071 1071 # Create a little structure to pass all the relevant information about
1072 1072 # the current completion to any custom completer.
1073 1073 event = Bunch()
1074 1074 event.line = line
1075 1075 event.symbol = text
1076 1076 cmd = line.split(None,1)[0]
1077 1077 event.command = cmd
1078 1078 event.text_until_cursor = self.text_until_cursor
1079 1079
1080 1080 #print "\ncustom:{%s]\n" % event # dbg
1081 1081
1082 1082 # for foo etc, try also to find completer for %foo
1083 1083 if not cmd.startswith(self.magic_escape):
1084 1084 try_magic = self.custom_completers.s_matches(
1085 1085 self.magic_escape + cmd)
1086 1086 else:
1087 1087 try_magic = []
1088 1088
1089 1089 for c in itertools.chain(self.custom_completers.s_matches(cmd),
1090 1090 try_magic,
1091 1091 self.custom_completers.flat_matches(self.text_until_cursor)):
1092 1092 #print "try",c # dbg
1093 1093 try:
1094 1094 res = c(event)
1095 1095 if res:
1096 1096 # first, try case sensitive match
1097 1097 withcase = [r for r in res if r.startswith(text)]
1098 1098 if withcase:
1099 1099 return withcase
1100 1100 # if none, then case insensitive ones are ok too
1101 1101 text_low = text.lower()
1102 1102 return [r for r in res if r.lower().startswith(text_low)]
1103 1103 except TryNext:
1104 1104 pass
1105 1105
1106 1106 return None
1107 1107
1108 1108 def complete(self, text=None, line_buffer=None, cursor_pos=None):
1109 1109 """Find completions for the given text and line context.
1110 1110
1111 1111 Note that both the text and the line_buffer are optional, but at least
1112 1112 one of them must be given.
1113 1113
1114 1114 Parameters
1115 1115 ----------
1116 1116 text : string, optional
1117 1117 Text to perform the completion on. If not given, the line buffer
1118 1118 is split using the instance's CompletionSplitter object.
1119 1119
1120 1120 line_buffer : string, optional
1121 1121 If not given, the completer attempts to obtain the current line
1122 1122 buffer via readline. This keyword allows clients which are
1123 1123 requesting for text completions in non-readline contexts to inform
1124 1124 the completer of the entire text.
1125 1125
1126 1126 cursor_pos : int, optional
1127 1127 Index of the cursor in the full line buffer. Should be provided by
1128 1128 remote frontends where kernel has no access to frontend state.
1129 1129
1130 1130 Returns
1131 1131 -------
1132 1132 text : str
1133 1133 Text that was actually used in the completion.
1134 1134
1135 1135 matches : list
1136 1136 A list of completion matches.
1137 1137 """
1138 1138 # io.rprint('\nCOMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
1139 1139
1140 1140 # if the cursor position isn't given, the only sane assumption we can
1141 1141 # make is that it's at the end of the line (the common case)
1142 1142 if cursor_pos is None:
1143 1143 cursor_pos = len(line_buffer) if text is None else len(text)
1144 1144
1145 1145 if PY3:
1146 1146
1147 1147 base_text = text if not line_buffer else line_buffer[:cursor_pos]
1148 1148 latex_text, latex_matches = self.latex_matches(base_text)
1149 1149 if latex_matches:
1150 1150 return latex_text, latex_matches
1151 1151 name_text = ''
1152 1152 name_matches = []
1153 1153 for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches):
1154 1154 name_text, name_matches = meth(base_text)
1155 1155 if name_text:
1156 1156 return name_text, name_matches
1157 1157
1158 1158 # if text is either None or an empty string, rely on the line buffer
1159 1159 if not text:
1160 1160 text = self.splitter.split_line(line_buffer, cursor_pos)
1161 1161
1162 1162 # If no line buffer is given, assume the input text is all there was
1163 1163 if line_buffer is None:
1164 1164 line_buffer = text
1165 1165
1166 1166 self.line_buffer = line_buffer
1167 1167 self.text_until_cursor = self.line_buffer[:cursor_pos]
1168 1168 # io.rprint('COMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
1169 1169
1170 1170 # Start with a clean slate of completions
1171 1171 self.matches[:] = []
1172 1172 custom_res = self.dispatch_custom_completer(text)
1173 1173 if custom_res is not None:
1174 1174 # did custom completers produce something?
1175 1175 self.matches = custom_res
1176 1176 else:
1177 1177 # Extend the list of completions with the results of each
1178 1178 # matcher, so we return results to the user from all
1179 1179 # namespaces.
1180 1180 if self.merge_completions:
1181 1181 self.matches = []
1182 1182 for matcher in self.matchers:
1183 1183 try:
1184 1184 self.matches.extend(matcher(text))
1185 1185 except:
1186 1186 # Show the ugly traceback if the matcher causes an
1187 1187 # exception, but do NOT crash the kernel!
1188 1188 sys.excepthook(*sys.exc_info())
1189 1189 else:
1190 1190 for matcher in self.matchers:
1191 1191 self.matches = matcher(text)
1192 1192 if self.matches:
1193 1193 break
1194 1194 # FIXME: we should extend our api to return a dict with completions for
1195 1195 # different types of objects. The rlcomplete() method could then
1196 1196 # simply collapse the dict into a list for readline, but we'd have
1197 1197 # richer completion semantics in other evironments.
1198 1198
1199 1199 # use penalize_magics_key to put magics after variables with same name
1200 1200 self.matches = sorted(set(self.matches), key=penalize_magics_key)
1201 1201
1202 1202 #io.rprint('COMP TEXT, MATCHES: %r, %r' % (text, self.matches)) # dbg
1203 1203 return text, self.matches
1204 1204
1205 1205 def rlcomplete(self, text, state):
1206 1206 """Return the state-th possible completion for 'text'.
1207 1207
1208 1208 This is called successively with state == 0, 1, 2, ... until it
1209 1209 returns None. The completion should begin with 'text'.
1210 1210
1211 1211 Parameters
1212 1212 ----------
1213 1213 text : string
1214 1214 Text to perform the completion on.
1215 1215
1216 1216 state : int
1217 1217 Counter used by readline.
1218 1218 """
1219 1219 if state==0:
1220 1220
1221 1221 self.line_buffer = line_buffer = self.readline.get_line_buffer()
1222 1222 cursor_pos = self.readline.get_endidx()
1223 1223
1224 1224 #io.rprint("\nRLCOMPLETE: %r %r %r" %
1225 1225 # (text, line_buffer, cursor_pos) ) # dbg
1226 1226
1227 1227 # if there is only a tab on a line with only whitespace, instead of
1228 1228 # the mostly useless 'do you want to see all million completions'
1229 1229 # message, just do the right thing and give the user his tab!
1230 1230 # Incidentally, this enables pasting of tabbed text from an editor
1231 1231 # (as long as autoindent is off).
1232 1232
1233 1233 # It should be noted that at least pyreadline still shows file
1234 1234 # completions - is there a way around it?
1235 1235
1236 1236 # don't apply this on 'dumb' terminals, such as emacs buffers, so
1237 1237 # we don't interfere with their own tab-completion mechanism.
1238 1238 if not (self.dumb_terminal or line_buffer.strip()):
1239 1239 self.readline.insert_text('\t')
1240 1240 sys.stdout.flush()
1241 1241 return None
1242 1242
1243 1243 # Note: debugging exceptions that may occur in completion is very
1244 1244 # tricky, because readline unconditionally silences them. So if
1245 1245 # during development you suspect a bug in the completion code, turn
1246 1246 # this flag on temporarily by uncommenting the second form (don't
1247 1247 # flip the value in the first line, as the '# dbg' marker can be
1248 1248 # automatically detected and is used elsewhere).
1249 1249 DEBUG = False
1250 1250 #DEBUG = True # dbg
1251 1251 if DEBUG:
1252 1252 try:
1253 1253 self.complete(text, line_buffer, cursor_pos)
1254 1254 except:
1255 1255 import traceback; traceback.print_exc()
1256 1256 else:
1257 1257 # The normal production version is here
1258 1258
1259 1259 # This method computes the self.matches array
1260 1260 self.complete(text, line_buffer, cursor_pos)
1261 1261
1262 1262 try:
1263 1263 return self.matches[state]
1264 1264 except IndexError:
1265 1265 return None
1266 1266
@@ -1,967 +1,967 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Top-level display functions for displaying object in different formats."""
3 3
4 4 # Copyright (c) IPython Development Team.
5 5 # Distributed under the terms of the Modified BSD License.
6 6
7 7 from __future__ import print_function
8 8
9 9 import json
10 10 import mimetypes
11 11 import os
12 12 import struct
13 13 import warnings
14 14
15 15 from IPython.core.formatters import _safe_get_formatter_method
16 16 from IPython.utils.py3compat import (string_types, cast_bytes_py2, cast_unicode,
17 17 unicode_type)
18 18 from IPython.testing.skipdoctest import skip_doctest
19 19
20 20 __all__ = ['display', 'display_pretty', 'display_html', 'display_markdown',
21 21 'display_svg', 'display_png', 'display_jpeg', 'display_latex', 'display_json',
22 22 'display_javascript', 'display_pdf', 'DisplayObject', 'TextDisplayObject',
23 23 'Pretty', 'HTML', 'Markdown', 'Math', 'Latex', 'SVG', 'JSON', 'Javascript',
24 24 'Image', 'clear_output', 'set_matplotlib_formats', 'set_matplotlib_close',
25 25 'publish_display_data']
26 26
27 27 #-----------------------------------------------------------------------------
28 28 # utility functions
29 29 #-----------------------------------------------------------------------------
30 30
31 31 def _safe_exists(path):
32 32 """Check path, but don't let exceptions raise"""
33 33 try:
34 34 return os.path.exists(path)
35 35 except Exception:
36 36 return False
37 37
38 38 def _merge(d1, d2):
39 39 """Like update, but merges sub-dicts instead of clobbering at the top level.
40 40
41 41 Updates d1 in-place
42 42 """
43 43
44 44 if not isinstance(d2, dict) or not isinstance(d1, dict):
45 45 return d2
46 46 for key, value in d2.items():
47 47 d1[key] = _merge(d1.get(key), value)
48 48 return d1
49 49
50 50 def _display_mimetype(mimetype, objs, raw=False, metadata=None):
51 51 """internal implementation of all display_foo methods
52 52
53 53 Parameters
54 54 ----------
55 55 mimetype : str
56 56 The mimetype to be published (e.g. 'image/png')
57 57 objs : tuple of objects
58 58 The Python objects to display, or if raw=True raw text data to
59 59 display.
60 60 raw : bool
61 61 Are the data objects raw data or Python objects that need to be
62 62 formatted before display? [default: False]
63 63 metadata : dict (optional)
64 64 Metadata to be associated with the specific mimetype output.
65 65 """
66 66 if metadata:
67 67 metadata = {mimetype: metadata}
68 68 if raw:
69 69 # turn list of pngdata into list of { 'image/png': pngdata }
70 70 objs = [ {mimetype: obj} for obj in objs ]
71 71 display(*objs, raw=raw, metadata=metadata, include=[mimetype])
72 72
73 73 #-----------------------------------------------------------------------------
74 74 # Main functions
75 75 #-----------------------------------------------------------------------------
76 76
77 77 def publish_display_data(data, metadata=None, source=None):
78 78 """Publish data and metadata to all frontends.
79 79
80 80 See the ``display_data`` message in the messaging documentation for
81 81 more details about this message type.
82 82
83 83 The following MIME types are currently implemented:
84 84
85 85 * text/plain
86 86 * text/html
87 87 * text/markdown
88 88 * text/latex
89 89 * application/json
90 90 * application/javascript
91 91 * image/png
92 92 * image/jpeg
93 93 * image/svg+xml
94 94
95 95 Parameters
96 96 ----------
97 97 data : dict
98 98 A dictionary having keys that are valid MIME types (like
99 99 'text/plain' or 'image/svg+xml') and values that are the data for
100 100 that MIME type. The data itself must be a JSON'able data
101 101 structure. Minimally all data should have the 'text/plain' data,
102 102 which can be displayed by all frontends. If more than the plain
103 103 text is given, it is up to the frontend to decide which
104 104 representation to use.
105 105 metadata : dict
106 106 A dictionary for metadata related to the data. This can contain
107 107 arbitrary key, value pairs that frontends can use to interpret
108 108 the data. mime-type keys matching those in data can be used
109 109 to specify metadata about particular representations.
110 110 source : str, deprecated
111 111 Unused.
112 112 """
113 113 from IPython.core.interactiveshell import InteractiveShell
114 114 InteractiveShell.instance().display_pub.publish(
115 115 data=data,
116 116 metadata=metadata,
117 117 )
118 118
119 119 def display(*objs, **kwargs):
120 120 """Display a Python object in all frontends.
121 121
122 122 By default all representations will be computed and sent to the frontends.
123 123 Frontends can decide which representation is used and how.
124 124
125 125 Parameters
126 126 ----------
127 127 objs : tuple of objects
128 128 The Python objects to display.
129 129 raw : bool, optional
130 130 Are the objects to be displayed already mimetype-keyed dicts of raw display data,
131 131 or Python objects that need to be formatted before display? [default: False]
132 132 include : list or tuple, optional
133 133 A list of format type strings (MIME types) to include in the
134 134 format data dict. If this is set *only* the format types included
135 135 in this list will be computed.
136 136 exclude : list or tuple, optional
137 137 A list of format type strings (MIME types) to exclude in the format
138 138 data dict. If this is set all format types will be computed,
139 139 except for those included in this argument.
140 140 metadata : dict, optional
141 141 A dictionary of metadata to associate with the output.
142 142 mime-type keys in this dictionary will be associated with the individual
143 143 representation formats, if they exist.
144 144 """
145 145 raw = kwargs.get('raw', False)
146 146 include = kwargs.get('include')
147 147 exclude = kwargs.get('exclude')
148 148 metadata = kwargs.get('metadata')
149 149
150 150 from IPython.core.interactiveshell import InteractiveShell
151 151
152 152 if not raw:
153 153 format = InteractiveShell.instance().display_formatter.format
154 154
155 155 for obj in objs:
156 156 if raw:
157 157 publish_display_data(data=obj, metadata=metadata)
158 158 else:
159 159 format_dict, md_dict = format(obj, include=include, exclude=exclude)
160 160 if not format_dict:
161 161 # nothing to display (e.g. _ipython_display_ took over)
162 162 continue
163 163 if metadata:
164 164 # kwarg-specified metadata gets precedence
165 165 _merge(md_dict, metadata)
166 166 publish_display_data(data=format_dict, metadata=md_dict)
167 167
168 168
169 169 def display_pretty(*objs, **kwargs):
170 170 """Display the pretty (default) representation of an object.
171 171
172 172 Parameters
173 173 ----------
174 174 objs : tuple of objects
175 175 The Python objects to display, or if raw=True raw text data to
176 176 display.
177 177 raw : bool
178 178 Are the data objects raw data or Python objects that need to be
179 179 formatted before display? [default: False]
180 180 metadata : dict (optional)
181 181 Metadata to be associated with the specific mimetype output.
182 182 """
183 183 _display_mimetype('text/plain', objs, **kwargs)
184 184
185 185
186 186 def display_html(*objs, **kwargs):
187 187 """Display the HTML representation of an object.
188 188
189 189 Parameters
190 190 ----------
191 191 objs : tuple of objects
192 192 The Python objects to display, or if raw=True raw HTML data to
193 193 display.
194 194 raw : bool
195 195 Are the data objects raw data or Python objects that need to be
196 196 formatted before display? [default: False]
197 197 metadata : dict (optional)
198 198 Metadata to be associated with the specific mimetype output.
199 199 """
200 200 _display_mimetype('text/html', objs, **kwargs)
201 201
202 202
203 203 def display_markdown(*objs, **kwargs):
204 204 """Displays the Markdown representation of an object.
205 205
206 206 Parameters
207 207 ----------
208 208 objs : tuple of objects
209 209 The Python objects to display, or if raw=True raw markdown data to
210 210 display.
211 211 raw : bool
212 212 Are the data objects raw data or Python objects that need to be
213 213 formatted before display? [default: False]
214 214 metadata : dict (optional)
215 215 Metadata to be associated with the specific mimetype output.
216 216 """
217 217
218 218 _display_mimetype('text/markdown', objs, **kwargs)
219 219
220 220
221 221 def display_svg(*objs, **kwargs):
222 222 """Display the SVG representation of an object.
223 223
224 224 Parameters
225 225 ----------
226 226 objs : tuple of objects
227 227 The Python objects to display, or if raw=True raw svg data to
228 228 display.
229 229 raw : bool
230 230 Are the data objects raw data or Python objects that need to be
231 231 formatted before display? [default: False]
232 232 metadata : dict (optional)
233 233 Metadata to be associated with the specific mimetype output.
234 234 """
235 235 _display_mimetype('image/svg+xml', objs, **kwargs)
236 236
237 237
238 238 def display_png(*objs, **kwargs):
239 239 """Display the PNG representation of an object.
240 240
241 241 Parameters
242 242 ----------
243 243 objs : tuple of objects
244 244 The Python objects to display, or if raw=True raw png data to
245 245 display.
246 246 raw : bool
247 247 Are the data objects raw data or Python objects that need to be
248 248 formatted before display? [default: False]
249 249 metadata : dict (optional)
250 250 Metadata to be associated with the specific mimetype output.
251 251 """
252 252 _display_mimetype('image/png', objs, **kwargs)
253 253
254 254
255 255 def display_jpeg(*objs, **kwargs):
256 256 """Display the JPEG representation of an object.
257 257
258 258 Parameters
259 259 ----------
260 260 objs : tuple of objects
261 261 The Python objects to display, or if raw=True raw JPEG data to
262 262 display.
263 263 raw : bool
264 264 Are the data objects raw data or Python objects that need to be
265 265 formatted before display? [default: False]
266 266 metadata : dict (optional)
267 267 Metadata to be associated with the specific mimetype output.
268 268 """
269 269 _display_mimetype('image/jpeg', objs, **kwargs)
270 270
271 271
272 272 def display_latex(*objs, **kwargs):
273 273 """Display the LaTeX representation of an object.
274 274
275 275 Parameters
276 276 ----------
277 277 objs : tuple of objects
278 278 The Python objects to display, or if raw=True raw latex data to
279 279 display.
280 280 raw : bool
281 281 Are the data objects raw data or Python objects that need to be
282 282 formatted before display? [default: False]
283 283 metadata : dict (optional)
284 284 Metadata to be associated with the specific mimetype output.
285 285 """
286 286 _display_mimetype('text/latex', objs, **kwargs)
287 287
288 288
289 289 def display_json(*objs, **kwargs):
290 290 """Display the JSON representation of an object.
291 291
292 292 Note that not many frontends support displaying JSON.
293 293
294 294 Parameters
295 295 ----------
296 296 objs : tuple of objects
297 297 The Python objects to display, or if raw=True raw json data to
298 298 display.
299 299 raw : bool
300 300 Are the data objects raw data or Python objects that need to be
301 301 formatted before display? [default: False]
302 302 metadata : dict (optional)
303 303 Metadata to be associated with the specific mimetype output.
304 304 """
305 305 _display_mimetype('application/json', objs, **kwargs)
306 306
307 307
308 308 def display_javascript(*objs, **kwargs):
309 309 """Display the Javascript representation of an object.
310 310
311 311 Parameters
312 312 ----------
313 313 objs : tuple of objects
314 314 The Python objects to display, or if raw=True raw javascript data to
315 315 display.
316 316 raw : bool
317 317 Are the data objects raw data or Python objects that need to be
318 318 formatted before display? [default: False]
319 319 metadata : dict (optional)
320 320 Metadata to be associated with the specific mimetype output.
321 321 """
322 322 _display_mimetype('application/javascript', objs, **kwargs)
323 323
324 324
325 325 def display_pdf(*objs, **kwargs):
326 326 """Display the PDF representation of an object.
327 327
328 328 Parameters
329 329 ----------
330 330 objs : tuple of objects
331 331 The Python objects to display, or if raw=True raw javascript data to
332 332 display.
333 333 raw : bool
334 334 Are the data objects raw data or Python objects that need to be
335 335 formatted before display? [default: False]
336 336 metadata : dict (optional)
337 337 Metadata to be associated with the specific mimetype output.
338 338 """
339 339 _display_mimetype('application/pdf', objs, **kwargs)
340 340
341 341
342 342 #-----------------------------------------------------------------------------
343 343 # Smart classes
344 344 #-----------------------------------------------------------------------------
345 345
346 346
347 347 class DisplayObject(object):
348 348 """An object that wraps data to be displayed."""
349 349
350 350 _read_flags = 'r'
351 351 _show_mem_addr = False
352 352
353 353 def __init__(self, data=None, url=None, filename=None):
354 354 """Create a display object given raw data.
355 355
356 356 When this object is returned by an expression or passed to the
357 357 display function, it will result in the data being displayed
358 358 in the frontend. The MIME type of the data should match the
359 359 subclasses used, so the Png subclass should be used for 'image/png'
360 360 data. If the data is a URL, the data will first be downloaded
361 361 and then displayed. If
362 362
363 363 Parameters
364 364 ----------
365 365 data : unicode, str or bytes
366 366 The raw data or a URL or file to load the data from
367 367 url : unicode
368 368 A URL to download the data from.
369 369 filename : unicode
370 370 Path to a local file to load the data from.
371 371 """
372 372 if data is not None and isinstance(data, string_types):
373 373 if data.startswith('http') and url is None:
374 374 url = data
375 375 filename = None
376 376 data = None
377 377 elif _safe_exists(data) and filename is None:
378 378 url = None
379 379 filename = data
380 380 data = None
381 381
382 382 self.data = data
383 383 self.url = url
384 384 self.filename = None if filename is None else unicode_type(filename)
385 385
386 386 self.reload()
387 387 self._check_data()
388 388
389 389 def __repr__(self):
390 390 if not self._show_mem_addr:
391 391 cls = self.__class__
392 392 r = "<%s.%s object>" % (cls.__module__, cls.__name__)
393 393 else:
394 394 r = super(DisplayObject, self).__repr__()
395 395 return r
396 396
397 397 def _check_data(self):
398 398 """Override in subclasses if there's something to check."""
399 399 pass
400 400
401 401 def reload(self):
402 402 """Reload the raw data from file or URL."""
403 403 if self.filename is not None:
404 404 with open(self.filename, self._read_flags) as f:
405 405 self.data = f.read()
406 406 elif self.url is not None:
407 407 try:
408 408 try:
409 409 from urllib.request import urlopen # Py3
410 410 except ImportError:
411 411 from urllib2 import urlopen
412 412 response = urlopen(self.url)
413 413 self.data = response.read()
414 414 # extract encoding from header, if there is one:
415 415 encoding = None
416 416 for sub in response.headers['content-type'].split(';'):
417 417 sub = sub.strip()
418 418 if sub.startswith('charset'):
419 419 encoding = sub.split('=')[-1].strip()
420 420 break
421 421 # decode data, if an encoding was specified
422 422 if encoding:
423 423 self.data = self.data.decode(encoding, 'replace')
424 424 except:
425 425 self.data = None
426 426
427 427 class TextDisplayObject(DisplayObject):
428 428 """Validate that display data is text"""
429 429 def _check_data(self):
430 430 if self.data is not None and not isinstance(self.data, string_types):
431 431 raise TypeError("%s expects text, not %r" % (self.__class__.__name__, self.data))
432 432
433 433 class Pretty(TextDisplayObject):
434 434
435 435 def _repr_pretty_(self):
436 436 return self.data
437 437
438 438
439 439 class HTML(TextDisplayObject):
440 440
441 441 def _repr_html_(self):
442 442 return self.data
443 443
444 444 def __html__(self):
445 445 """
446 446 This method exists to inform other HTML-using modules (e.g. Markupsafe,
447 447 htmltag, etc) that this object is HTML and does not need things like
448 448 special characters (<>&) escaped.
449 449 """
450 450 return self._repr_html_()
451 451
452 452
453 453 class Markdown(TextDisplayObject):
454 454
455 455 def _repr_markdown_(self):
456 456 return self.data
457 457
458 458
459 459 class Math(TextDisplayObject):
460 460
461 461 def _repr_latex_(self):
462 462 s = self.data.strip('$')
463 463 return "$$%s$$" % s
464 464
465 465
466 466 class Latex(TextDisplayObject):
467 467
468 468 def _repr_latex_(self):
469 469 return self.data
470 470
471 471
472 472 class SVG(DisplayObject):
473 473
474 474 # wrap data in a property, which extracts the <svg> tag, discarding
475 475 # document headers
476 476 _data = None
477 477
478 478 @property
479 479 def data(self):
480 480 return self._data
481 481
482 482 @data.setter
483 483 def data(self, svg):
484 484 if svg is None:
485 485 self._data = None
486 486 return
487 487 # parse into dom object
488 488 from xml.dom import minidom
489 489 svg = cast_bytes_py2(svg)
490 490 x = minidom.parseString(svg)
491 491 # get svg tag (should be 1)
492 492 found_svg = x.getElementsByTagName('svg')
493 493 if found_svg:
494 494 svg = found_svg[0].toxml()
495 495 else:
496 496 # fallback on the input, trust the user
497 497 # but this is probably an error.
498 498 pass
499 499 svg = cast_unicode(svg)
500 500 self._data = svg
501 501
502 502 def _repr_svg_(self):
503 503 return self.data
504 504
505 505
506 506 class JSON(DisplayObject):
507 507 """JSON expects a JSON-able dict or list
508 508
509 509 not an already-serialized JSON string.
510 510
511 511 Scalar types (None, number, string) are not allowed, only dict or list containers.
512 512 """
513 513 # wrap data in a property, which warns about passing already-serialized JSON
514 514 _data = None
515 515 def _check_data(self):
516 516 if self.data is not None and not isinstance(self.data, (dict, list)):
517 517 raise TypeError("%s expects JSONable dict or list, not %r" % (self.__class__.__name__, self.data))
518 518
519 519 @property
520 520 def data(self):
521 521 return self._data
522 522
523 523 @data.setter
524 524 def data(self, data):
525 525 if isinstance(data, string_types):
526 526 warnings.warn("JSON expects JSONable dict or list, not JSON strings")
527 527 data = json.loads(data)
528 528 self._data = data
529 529
530 530 def _repr_json_(self):
531 531 return self.data
532 532
533 533 css_t = """$("head").append($("<link/>").attr({
534 534 rel: "stylesheet",
535 535 type: "text/css",
536 536 href: "%s"
537 537 }));
538 538 """
539 539
540 540 lib_t1 = """$.getScript("%s", function () {
541 541 """
542 542 lib_t2 = """});
543 543 """
544 544
545 545 class Javascript(TextDisplayObject):
546 546
547 547 def __init__(self, data=None, url=None, filename=None, lib=None, css=None):
548 548 """Create a Javascript display object given raw data.
549 549
550 550 When this object is returned by an expression or passed to the
551 551 display function, it will result in the data being displayed
552 552 in the frontend. If the data is a URL, the data will first be
553 553 downloaded and then displayed.
554 554
555 555 In the Notebook, the containing element will be available as `element`,
556 556 and jQuery will be available. Content appended to `element` will be
557 557 visible in the output area.
558 558
559 559 Parameters
560 560 ----------
561 561 data : unicode, str or bytes
562 562 The Javascript source code or a URL to download it from.
563 563 url : unicode
564 564 A URL to download the data from.
565 565 filename : unicode
566 566 Path to a local file to load the data from.
567 567 lib : list or str
568 568 A sequence of Javascript library URLs to load asynchronously before
569 569 running the source code. The full URLs of the libraries should
570 570 be given. A single Javascript library URL can also be given as a
571 571 string.
572 572 css: : list or str
573 573 A sequence of css files to load before running the source code.
574 574 The full URLs of the css files should be given. A single css URL
575 575 can also be given as a string.
576 576 """
577 577 if isinstance(lib, string_types):
578 578 lib = [lib]
579 579 elif lib is None:
580 580 lib = []
581 581 if isinstance(css, string_types):
582 582 css = [css]
583 583 elif css is None:
584 584 css = []
585 585 if not isinstance(lib, (list,tuple)):
586 586 raise TypeError('expected sequence, got: %r' % lib)
587 587 if not isinstance(css, (list,tuple)):
588 588 raise TypeError('expected sequence, got: %r' % css)
589 589 self.lib = lib
590 590 self.css = css
591 591 super(Javascript, self).__init__(data=data, url=url, filename=filename)
592 592
593 593 def _repr_javascript_(self):
594 594 r = ''
595 595 for c in self.css:
596 596 r += css_t % c
597 597 for l in self.lib:
598 598 r += lib_t1 % l
599 599 r += self.data
600 600 r += lib_t2*len(self.lib)
601 601 return r
602 602
603 603 # constants for identifying png/jpeg data
604 604 _PNG = b'\x89PNG\r\n\x1a\n'
605 605 _JPEG = b'\xff\xd8'
606 606
607 607 def _pngxy(data):
608 608 """read the (width, height) from a PNG header"""
609 609 ihdr = data.index(b'IHDR')
610 610 # next 8 bytes are width/height
611 611 w4h4 = data[ihdr+4:ihdr+12]
612 612 return struct.unpack('>ii', w4h4)
613 613
614 614 def _jpegxy(data):
615 615 """read the (width, height) from a JPEG header"""
616 616 # adapted from http://www.64lines.com/jpeg-width-height
617 617
618 618 idx = 4
619 619 while True:
620 620 block_size = struct.unpack('>H', data[idx:idx+2])[0]
621 621 idx = idx + block_size
622 622 if data[idx:idx+2] == b'\xFF\xC0':
623 623 # found Start of Frame
624 624 iSOF = idx
625 625 break
626 626 else:
627 627 # read another block
628 628 idx += 2
629 629
630 630 h, w = struct.unpack('>HH', data[iSOF+5:iSOF+9])
631 631 return w, h
632 632
633 633 class Image(DisplayObject):
634 634
635 635 _read_flags = 'rb'
636 636 _FMT_JPEG = u'jpeg'
637 637 _FMT_PNG = u'png'
638 638 _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG]
639 639
640 640 def __init__(self, data=None, url=None, filename=None, format=u'png',
641 641 embed=None, width=None, height=None, retina=False,
642 642 unconfined=False, metadata=None):
643 643 """Create a PNG/JPEG image object given raw data.
644 644
645 645 When this object is returned by an input cell or passed to the
646 646 display function, it will result in the image being displayed
647 647 in the frontend.
648 648
649 649 Parameters
650 650 ----------
651 651 data : unicode, str or bytes
652 652 The raw image data or a URL or filename to load the data from.
653 653 This always results in embedded image data.
654 654 url : unicode
655 655 A URL to download the data from. If you specify `url=`,
656 656 the image data will not be embedded unless you also specify `embed=True`.
657 657 filename : unicode
658 658 Path to a local file to load the data from.
659 659 Images from a file are always embedded.
660 660 format : unicode
661 661 The format of the image data (png/jpeg/jpg). If a filename or URL is given
662 662 for format will be inferred from the filename extension.
663 663 embed : bool
664 664 Should the image data be embedded using a data URI (True) or be
665 665 loaded using an <img> tag. Set this to True if you want the image
666 666 to be viewable later with no internet connection in the notebook.
667 667
668 668 Default is `True`, unless the keyword argument `url` is set, then
669 669 default value is `False`.
670 670
671 671 Note that QtConsole is not able to display images if `embed` is set to `False`
672 672 width : int
673 673 Width to which to constrain the image in html
674 674 height : int
675 675 Height to which to constrain the image in html
676 676 retina : bool
677 677 Automatically set the width and height to half of the measured
678 678 width and height.
679 679 This only works for embedded images because it reads the width/height
680 680 from image data.
681 681 For non-embedded images, you can just set the desired display width
682 682 and height directly.
683 683 unconfined: bool
684 684 Set unconfined=True to disable max-width confinement of the image.
685 685 metadata: dict
686 686 Specify extra metadata to attach to the image.
687 687
688 688 Examples
689 689 --------
690 690 # embedded image data, works in qtconsole and notebook
691 691 # when passed positionally, the first arg can be any of raw image data,
692 692 # a URL, or a filename from which to load image data.
693 693 # The result is always embedding image data for inline images.
694 694 Image('http://www.google.fr/images/srpr/logo3w.png')
695 695 Image('/path/to/image.jpg')
696 696 Image(b'RAW_PNG_DATA...')
697 697
698 698 # Specifying Image(url=...) does not embed the image data,
699 699 # it only generates `<img>` tag with a link to the source.
700 700 # This will not work in the qtconsole or offline.
701 701 Image(url='http://www.google.fr/images/srpr/logo3w.png')
702 702
703 703 """
704 704 if filename is not None:
705 705 ext = self._find_ext(filename)
706 706 elif url is not None:
707 707 ext = self._find_ext(url)
708 708 elif data is None:
709 709 raise ValueError("No image data found. Expecting filename, url, or data.")
710 710 elif isinstance(data, string_types) and (
711 711 data.startswith('http') or _safe_exists(data)
712 712 ):
713 713 ext = self._find_ext(data)
714 714 else:
715 715 ext = None
716 716
717 717 if ext is not None:
718 718 format = ext.lower()
719 719 if ext == u'jpg' or ext == u'jpeg':
720 720 format = self._FMT_JPEG
721 721 if ext == u'png':
722 722 format = self._FMT_PNG
723 723 elif isinstance(data, bytes) and format == 'png':
724 724 # infer image type from image data header,
725 725 # only if format might not have been specified.
726 726 if data[:2] == _JPEG:
727 727 format = 'jpeg'
728 728
729 729 self.format = unicode_type(format).lower()
730 730 self.embed = embed if embed is not None else (url is None)
731 731
732 732 if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS:
733 733 raise ValueError("Cannot embed the '%s' image format" % (self.format))
734 734 self.width = width
735 735 self.height = height
736 736 self.retina = retina
737 737 self.unconfined = unconfined
738 738 self.metadata = metadata
739 739 super(Image, self).__init__(data=data, url=url, filename=filename)
740 740
741 741 if retina:
742 742 self._retina_shape()
743 743
744 744 def _retina_shape(self):
745 745 """load pixel-doubled width and height from image data"""
746 746 if not self.embed:
747 747 return
748 748 if self.format == 'png':
749 749 w, h = _pngxy(self.data)
750 750 elif self.format == 'jpeg':
751 751 w, h = _jpegxy(self.data)
752 752 else:
753 753 # retina only supports png
754 754 return
755 755 self.width = w // 2
756 756 self.height = h // 2
757 757
758 758 def reload(self):
759 759 """Reload the raw data from file or URL."""
760 760 if self.embed:
761 761 super(Image,self).reload()
762 762 if self.retina:
763 763 self._retina_shape()
764 764
765 765 def _repr_html_(self):
766 766 if not self.embed:
767 767 width = height = klass = ''
768 768 if self.width:
769 769 width = ' width="%d"' % self.width
770 770 if self.height:
771 771 height = ' height="%d"' % self.height
772 772 if self.unconfined:
773 773 klass = ' class="unconfined"'
774 774 return u'<img src="{url}"{width}{height}{klass}/>'.format(
775 775 url=self.url,
776 776 width=width,
777 777 height=height,
778 778 klass=klass,
779 779 )
780 780
781 781 def _data_and_metadata(self):
782 782 """shortcut for returning metadata with shape information, if defined"""
783 783 md = {}
784 784 if self.width:
785 785 md['width'] = self.width
786 786 if self.height:
787 787 md['height'] = self.height
788 788 if self.unconfined:
789 789 md['unconfined'] = self.unconfined
790 790 if self.metadata:
791 791 md.update(self.metadata)
792 792 if md:
793 793 return self.data, md
794 794 else:
795 795 return self.data
796 796
797 797 def _repr_png_(self):
798 798 if self.embed and self.format == u'png':
799 799 return self._data_and_metadata()
800 800
801 801 def _repr_jpeg_(self):
802 802 if self.embed and (self.format == u'jpeg' or self.format == u'jpg'):
803 803 return self._data_and_metadata()
804 804
805 805 def _find_ext(self, s):
806 806 return unicode_type(s.split('.')[-1].lower())
807 807
808 808 class Video(DisplayObject):
809 809
810 810 def __init__(self, data=None, url=None, filename=None, embed=None, mimetype=None):
811 811 """Create a video object given raw data or an URL.
812 812
813 813 When this object is returned by an input cell or passed to the
814 814 display function, it will result in the video being displayed
815 815 in the frontend.
816 816
817 817 Parameters
818 818 ----------
819 819 data : unicode, str or bytes
820 820 The raw image data or a URL or filename to load the data from.
821 821 This always results in embedded image data.
822 822 url : unicode
823 823 A URL to download the data from. If you specify `url=`,
824 824 the image data will not be embedded unless you also specify `embed=True`.
825 825 filename : unicode
826 826 Path to a local file to load the data from.
827 827 Videos from a file are always embedded.
828 828 embed : bool
829 829 Should the image data be embedded using a data URI (True) or be
830 830 loaded using an <img> tag. Set this to True if you want the image
831 831 to be viewable later with no internet connection in the notebook.
832 832
833 833 Default is `True`, unless the keyword argument `url` is set, then
834 834 default value is `False`.
835 835
836 836 Note that QtConsole is not able to display images if `embed` is set to `False`
837 837 mimetype: unicode
838 838 Specify the mimetype in case you load in a encoded video.
839 839 Examples
840 840 --------
841 841 Video('https://archive.org/download/Sita_Sings_the_Blues/Sita_Sings_the_Blues_small.mp4')
842 842 Video('path/to/video.mp4')
843 843 Video('path/to/video.mp4', embed=False)
844 844 """
845 845 if url is None and (data.startswith('http') or data.startswith('https')):
846 846 url = data
847 847 data = None
848 848 embed = False
849 849 elif os.path.exists(data):
850 850 filename = data
851 851 data = None
852 852
853 853 self.mimetype = mimetype
854 854 self.embed = embed if embed is not None else (filename is not None)
855 855 super(Video, self).__init__(data=data, url=url, filename=filename)
856 856
857 857 def _repr_html_(self):
858 858 # External URLs and potentially local files are not embedded into the
859 859 # notebook output.
860 860 if not self.embed:
861 861 url = self.url if self.url is not None else self.filename
862 862 output = """<video src="{0}" controls>
863 863 Your browser does not support the <code>video</code> element.
864 864 </video>""".format(url)
865 865 return output
866 866 # Embedded videos uses base64 encoded videos.
867 867 if self.filename is not None:
868 868 mimetypes.init()
869 869 mimetype, encoding = mimetypes.guess_type(self.filename)
870 870
871 871 video = open(self.filename, 'rb').read()
872 872 video_encoded = video.encode('base64')
873 873 else:
874 874 video_encoded = self.data
875 875 mimetype = self.mimetype
876 876 output = """<video controls>
877 877 <source src="data:{0};base64,{1}" type="{0}">
878 878 Your browser does not support the video tag.
879 879 </video>""".format(mimetype, video_encoded)
880 880 return output
881 881
882 882 def reload(self):
883 883 # TODO
884 884 pass
885 885
886 886 def _repr_png_(self):
887 887 # TODO
888 888 pass
889 889 def _repr_jpeg_(self):
890 890 # TODO
891 891 pass
892 892
893 893 def clear_output(wait=False):
894 894 """Clear the output of the current cell receiving output.
895 895
896 896 Parameters
897 897 ----------
898 898 wait : bool [default: false]
899 899 Wait to clear the output until new output is available to replace it."""
900 900 from IPython.core.interactiveshell import InteractiveShell
901 901 if InteractiveShell.initialized():
902 902 InteractiveShell.instance().display_pub.clear_output(wait)
903 903 else:
904 904 from IPython.utils import io
905 905 print('\033[2K\r', file=io.stdout, end='')
906 906 io.stdout.flush()
907 907 print('\033[2K\r', file=io.stderr, end='')
908 908 io.stderr.flush()
909 909
910 910
911 911 @skip_doctest
912 912 def set_matplotlib_formats(*formats, **kwargs):
913 913 """Select figure formats for the inline backend. Optionally pass quality for JPEG.
914 914
915 915 For example, this enables PNG and JPEG output with a JPEG quality of 90%::
916 916
917 917 In [1]: set_matplotlib_formats('png', 'jpeg', quality=90)
918 918
919 919 To set this in your config files use the following::
920 920
921 921 c.InlineBackend.figure_formats = {'png', 'jpeg'}
922 922 c.InlineBackend.print_figure_kwargs.update({'quality' : 90})
923 923
924 924 Parameters
925 925 ----------
926 926 *formats : strs
927 927 One or more figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'.
928 928 **kwargs :
929 929 Keyword args will be relayed to ``figure.canvas.print_figure``.
930 930 """
931 931 from IPython.core.interactiveshell import InteractiveShell
932 932 from IPython.core.pylabtools import select_figure_formats
933 from IPython.kernel.zmq.pylab.config import InlineBackend
934 933 # build kwargs, starting with InlineBackend config
935 934 kw = {}
935 from ipython_kernel.pylab.config import InlineBackend
936 936 cfg = InlineBackend.instance()
937 937 kw.update(cfg.print_figure_kwargs)
938 938 kw.update(**kwargs)
939 939 shell = InteractiveShell.instance()
940 940 select_figure_formats(shell, formats, **kw)
941 941
942 942 @skip_doctest
943 943 def set_matplotlib_close(close=True):
944 944 """Set whether the inline backend closes all figures automatically or not.
945 945
946 946 By default, the inline backend used in the IPython Notebook will close all
947 947 matplotlib figures automatically after each cell is run. This means that
948 948 plots in different cells won't interfere. Sometimes, you may want to make
949 949 a plot in one cell and then refine it in later cells. This can be accomplished
950 950 by::
951 951
952 952 In [1]: set_matplotlib_close(False)
953 953
954 954 To set this in your config files use the following::
955 955
956 956 c.InlineBackend.close_figures = False
957 957
958 958 Parameters
959 959 ----------
960 960 close : bool
961 961 Should all matplotlib figures be automatically closed after each cell is
962 962 run?
963 963 """
964 from IPython.kernel.zmq.pylab.config import InlineBackend
964 from ipython_kernel.pylab.config import InlineBackend
965 965 cfg = InlineBackend.instance()
966 966 cfg.close_figures = close
967 967
@@ -1,70 +1,70 b''
1 1 # encoding: utf-8
2 2 """
3 3 A context manager for handling sys.displayhook.
4 4
5 5 Authors:
6 6
7 7 * Robert Kern
8 8 * Brian Granger
9 9 """
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Copyright (C) 2008-2011 The IPython Development Team
13 13 #
14 14 # Distributed under the terms of the BSD License. The full license is in
15 15 # the file COPYING, distributed as part of this software.
16 16 #-----------------------------------------------------------------------------
17 17
18 18 #-----------------------------------------------------------------------------
19 19 # Imports
20 20 #-----------------------------------------------------------------------------
21 21
22 22 import sys
23 23
24 from IPython.config.configurable import Configurable
25 from IPython.utils.traitlets import Any
24 from traitlets.config.configurable import Configurable
25 from traitlets import Any
26 26
27 27 #-----------------------------------------------------------------------------
28 28 # Classes and functions
29 29 #-----------------------------------------------------------------------------
30 30
31 31
32 32 class DisplayTrap(Configurable):
33 33 """Object to manage sys.displayhook.
34 34
35 35 This came from IPython.core.kernel.display_hook, but is simplified
36 36 (no callbacks or formatters) until more of the core is refactored.
37 37 """
38 38
39 39 hook = Any
40 40
41 41 def __init__(self, hook=None):
42 42 super(DisplayTrap, self).__init__(hook=hook, config=None)
43 43 self.old_hook = None
44 44 # We define this to track if a single BuiltinTrap is nested.
45 45 # Only turn off the trap when the outermost call to __exit__ is made.
46 46 self._nested_level = 0
47 47
48 48 def __enter__(self):
49 49 if self._nested_level == 0:
50 50 self.set()
51 51 self._nested_level += 1
52 52 return self
53 53
54 54 def __exit__(self, type, value, traceback):
55 55 if self._nested_level == 1:
56 56 self.unset()
57 57 self._nested_level -= 1
58 58 # Returning False will cause exceptions to propagate
59 59 return False
60 60
61 61 def set(self):
62 62 """Set the hook."""
63 63 if sys.displayhook is not self.hook:
64 64 self.old_hook = sys.displayhook
65 65 sys.displayhook = self.hook
66 66
67 67 def unset(self):
68 68 """Unset the hook."""
69 69 sys.displayhook = self.old_hook
70 70
@@ -1,283 +1,283 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Displayhook for IPython.
3 3
4 4 This defines a callable class that IPython uses for `sys.displayhook`.
5 5 """
6 6
7 7 # Copyright (c) IPython Development Team.
8 8 # Distributed under the terms of the Modified BSD License.
9 9
10 10 from __future__ import print_function
11 11
12 12 import sys
13 13
14 14 from IPython.core.formatters import _safe_get_formatter_method
15 from IPython.config.configurable import Configurable
15 from traitlets.config.configurable import Configurable
16 16 from IPython.utils import io
17 17 from IPython.utils.py3compat import builtin_mod
18 from IPython.utils.traitlets import Instance, Float
18 from traitlets import Instance, Float
19 19 from IPython.utils.warn import warn
20 20
21 21 # TODO: Move the various attributes (cache_size, [others now moved]). Some
22 22 # of these are also attributes of InteractiveShell. They should be on ONE object
23 23 # only and the other objects should ask that one object for their values.
24 24
25 25 class DisplayHook(Configurable):
26 26 """The custom IPython displayhook to replace sys.displayhook.
27 27
28 28 This class does many things, but the basic idea is that it is a callable
29 29 that gets called anytime user code returns a value.
30 30 """
31 31
32 32 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
33 33 allow_none=True)
34 34 exec_result = Instance('IPython.core.interactiveshell.ExecutionResult',
35 35 allow_none=True)
36 36 cull_fraction = Float(0.2)
37 37
38 38 def __init__(self, shell=None, cache_size=1000, **kwargs):
39 39 super(DisplayHook, self).__init__(shell=shell, **kwargs)
40 40 cache_size_min = 3
41 41 if cache_size <= 0:
42 42 self.do_full_cache = 0
43 43 cache_size = 0
44 44 elif cache_size < cache_size_min:
45 45 self.do_full_cache = 0
46 46 cache_size = 0
47 47 warn('caching was disabled (min value for cache size is %s).' %
48 48 cache_size_min,level=3)
49 49 else:
50 50 self.do_full_cache = 1
51 51
52 52 self.cache_size = cache_size
53 53
54 54 # we need a reference to the user-level namespace
55 55 self.shell = shell
56 56
57 57 self._,self.__,self.___ = '','',''
58 58
59 59 # these are deliberately global:
60 60 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
61 61 self.shell.user_ns.update(to_user_ns)
62 62
63 63 @property
64 64 def prompt_count(self):
65 65 return self.shell.execution_count
66 66
67 67 #-------------------------------------------------------------------------
68 68 # Methods used in __call__. Override these methods to modify the behavior
69 69 # of the displayhook.
70 70 #-------------------------------------------------------------------------
71 71
72 72 def check_for_underscore(self):
73 73 """Check if the user has set the '_' variable by hand."""
74 74 # If something injected a '_' variable in __builtin__, delete
75 75 # ipython's automatic one so we don't clobber that. gettext() in
76 76 # particular uses _, so we need to stay away from it.
77 77 if '_' in builtin_mod.__dict__:
78 78 try:
79 79 del self.shell.user_ns['_']
80 80 except KeyError:
81 81 pass
82 82
83 83 def quiet(self):
84 84 """Should we silence the display hook because of ';'?"""
85 85 # do not print output if input ends in ';'
86 86 try:
87 87 cell = self.shell.history_manager.input_hist_parsed[self.prompt_count]
88 88 return cell.rstrip().endswith(';')
89 89 except IndexError:
90 90 # some uses of ipshellembed may fail here
91 91 return False
92 92
93 93 def start_displayhook(self):
94 94 """Start the displayhook, initializing resources."""
95 95 pass
96 96
97 97 def write_output_prompt(self):
98 98 """Write the output prompt.
99 99
100 100 The default implementation simply writes the prompt to
101 101 ``io.stdout``.
102 102 """
103 103 # Use write, not print which adds an extra space.
104 104 io.stdout.write(self.shell.separate_out)
105 105 outprompt = self.shell.prompt_manager.render('out')
106 106 if self.do_full_cache:
107 107 io.stdout.write(outprompt)
108 108
109 109 def compute_format_data(self, result):
110 110 """Compute format data of the object to be displayed.
111 111
112 112 The format data is a generalization of the :func:`repr` of an object.
113 113 In the default implementation the format data is a :class:`dict` of
114 114 key value pair where the keys are valid MIME types and the values
115 115 are JSON'able data structure containing the raw data for that MIME
116 116 type. It is up to frontends to determine pick a MIME to to use and
117 117 display that data in an appropriate manner.
118 118
119 119 This method only computes the format data for the object and should
120 120 NOT actually print or write that to a stream.
121 121
122 122 Parameters
123 123 ----------
124 124 result : object
125 125 The Python object passed to the display hook, whose format will be
126 126 computed.
127 127
128 128 Returns
129 129 -------
130 130 (format_dict, md_dict) : dict
131 131 format_dict is a :class:`dict` whose keys are valid MIME types and values are
132 132 JSON'able raw data for that MIME type. It is recommended that
133 133 all return values of this should always include the "text/plain"
134 134 MIME type representation of the object.
135 135 md_dict is a :class:`dict` with the same MIME type keys
136 136 of metadata associated with each output.
137 137
138 138 """
139 139 return self.shell.display_formatter.format(result)
140 140
141 141 def write_format_data(self, format_dict, md_dict=None):
142 142 """Write the format data dict to the frontend.
143 143
144 144 This default version of this method simply writes the plain text
145 145 representation of the object to ``io.stdout``. Subclasses should
146 146 override this method to send the entire `format_dict` to the
147 147 frontends.
148 148
149 149 Parameters
150 150 ----------
151 151 format_dict : dict
152 152 The format dict for the object passed to `sys.displayhook`.
153 153 md_dict : dict (optional)
154 154 The metadata dict to be associated with the display data.
155 155 """
156 156 if 'text/plain' not in format_dict:
157 157 # nothing to do
158 158 return
159 159 # We want to print because we want to always make sure we have a
160 160 # newline, even if all the prompt separators are ''. This is the
161 161 # standard IPython behavior.
162 162 result_repr = format_dict['text/plain']
163 163 if '\n' in result_repr:
164 164 # So that multi-line strings line up with the left column of
165 165 # the screen, instead of having the output prompt mess up
166 166 # their first line.
167 167 # We use the prompt template instead of the expanded prompt
168 168 # because the expansion may add ANSI escapes that will interfere
169 169 # with our ability to determine whether or not we should add
170 170 # a newline.
171 171 prompt_template = self.shell.prompt_manager.out_template
172 172 if prompt_template and not prompt_template.endswith('\n'):
173 173 # But avoid extraneous empty lines.
174 174 result_repr = '\n' + result_repr
175 175
176 176 print(result_repr, file=io.stdout)
177 177
178 178 def update_user_ns(self, result):
179 179 """Update user_ns with various things like _, __, _1, etc."""
180 180
181 181 # Avoid recursive reference when displaying _oh/Out
182 182 if result is not self.shell.user_ns['_oh']:
183 183 if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
184 184 self.cull_cache()
185 185 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
186 186 # we cause buggy behavior for things like gettext).
187 187
188 188 if '_' not in builtin_mod.__dict__:
189 189 self.___ = self.__
190 190 self.__ = self._
191 191 self._ = result
192 192 self.shell.push({'_':self._,
193 193 '__':self.__,
194 194 '___':self.___}, interactive=False)
195 195
196 196 # hackish access to top-level namespace to create _1,_2... dynamically
197 197 to_main = {}
198 198 if self.do_full_cache:
199 199 new_result = '_'+repr(self.prompt_count)
200 200 to_main[new_result] = result
201 201 self.shell.push(to_main, interactive=False)
202 202 self.shell.user_ns['_oh'][self.prompt_count] = result
203 203
204 204 def fill_exec_result(self, result):
205 205 if self.exec_result is not None:
206 206 self.exec_result.result = result
207 207
208 208 def log_output(self, format_dict):
209 209 """Log the output."""
210 210 if 'text/plain' not in format_dict:
211 211 # nothing to do
212 212 return
213 213 if self.shell.logger.log_output:
214 214 self.shell.logger.log_write(format_dict['text/plain'], 'output')
215 215 self.shell.history_manager.output_hist_reprs[self.prompt_count] = \
216 216 format_dict['text/plain']
217 217
218 218 def finish_displayhook(self):
219 219 """Finish up all displayhook activities."""
220 220 io.stdout.write(self.shell.separate_out2)
221 221 io.stdout.flush()
222 222
223 223 def __call__(self, result=None):
224 224 """Printing with history cache management.
225 225
226 226 This is invoked everytime the interpreter needs to print, and is
227 227 activated by setting the variable sys.displayhook to it.
228 228 """
229 229 self.check_for_underscore()
230 230 if result is not None and not self.quiet():
231 231 self.start_displayhook()
232 232 self.write_output_prompt()
233 233 format_dict, md_dict = self.compute_format_data(result)
234 234 self.update_user_ns(result)
235 235 self.fill_exec_result(result)
236 236 if format_dict:
237 237 self.write_format_data(format_dict, md_dict)
238 238 self.log_output(format_dict)
239 239 self.finish_displayhook()
240 240
241 241 def cull_cache(self):
242 242 """Output cache is full, cull the oldest entries"""
243 243 oh = self.shell.user_ns.get('_oh', {})
244 244 sz = len(oh)
245 245 cull_count = max(int(sz * self.cull_fraction), 2)
246 246 warn('Output cache limit (currently {sz} entries) hit.\n'
247 247 'Flushing oldest {cull_count} entries.'.format(sz=sz, cull_count=cull_count))
248 248
249 249 for i, n in enumerate(sorted(oh)):
250 250 if i >= cull_count:
251 251 break
252 252 self.shell.user_ns.pop('_%i' % n, None)
253 253 oh.pop(n, None)
254 254
255 255
256 256 def flush(self):
257 257 if not self.do_full_cache:
258 258 raise ValueError("You shouldn't have reached the cache flush "
259 259 "if full caching is not enabled!")
260 260 # delete auto-generated vars from global namespace
261 261
262 262 for n in range(1,self.prompt_count + 1):
263 263 key = '_'+repr(n)
264 264 try:
265 265 del self.shell.user_ns[key]
266 266 except: pass
267 267 # In some embedded circumstances, the user_ns doesn't have the
268 268 # '_oh' key set up.
269 269 oh = self.shell.user_ns.get('_oh', None)
270 270 if oh is not None:
271 271 oh.clear()
272 272
273 273 # Release our own references to objects:
274 274 self._, self.__, self.___ = '', '', ''
275 275
276 276 if '_' not in builtin_mod.__dict__:
277 277 self.shell.user_ns.update({'_':None,'__':None, '___':None})
278 278 import gc
279 279 # TODO: Is this really needed?
280 280 # IronPython blocks here forever
281 281 if sys.platform != "cli":
282 282 gc.collect()
283 283
@@ -1,116 +1,116 b''
1 1 """An interface for publishing rich data to frontends.
2 2
3 3 There are two components of the display system:
4 4
5 5 * Display formatters, which take a Python object and compute the
6 6 representation of the object in various formats (text, HTML, SVG, etc.).
7 7 * The display publisher that is used to send the representation data to the
8 8 various frontends.
9 9
10 10 This module defines the logic display publishing. The display publisher uses
11 11 the ``display_data`` message type that is defined in the IPython messaging
12 12 spec.
13 13 """
14 14
15 15 # Copyright (c) IPython Development Team.
16 16 # Distributed under the terms of the Modified BSD License.
17 17
18 18 from __future__ import print_function
19 19
20 from IPython.config.configurable import Configurable
20 from traitlets.config.configurable import Configurable
21 21 from IPython.utils import io
22 from IPython.utils.traitlets import List
22 from traitlets import List
23 23
24 24 # This used to be defined here - it is imported for backwards compatibility
25 25 from .display import publish_display_data
26 26
27 27 #-----------------------------------------------------------------------------
28 28 # Main payload class
29 29 #-----------------------------------------------------------------------------
30 30
31 31 class DisplayPublisher(Configurable):
32 32 """A traited class that publishes display data to frontends.
33 33
34 34 Instances of this class are created by the main IPython object and should
35 35 be accessed there.
36 36 """
37 37
38 38 def _validate_data(self, data, metadata=None):
39 39 """Validate the display data.
40 40
41 41 Parameters
42 42 ----------
43 43 data : dict
44 44 The formata data dictionary.
45 45 metadata : dict
46 46 Any metadata for the data.
47 47 """
48 48
49 49 if not isinstance(data, dict):
50 50 raise TypeError('data must be a dict, got: %r' % data)
51 51 if metadata is not None:
52 52 if not isinstance(metadata, dict):
53 53 raise TypeError('metadata must be a dict, got: %r' % data)
54 54
55 55 def publish(self, data, metadata=None, source=None):
56 56 """Publish data and metadata to all frontends.
57 57
58 58 See the ``display_data`` message in the messaging documentation for
59 59 more details about this message type.
60 60
61 61 The following MIME types are currently implemented:
62 62
63 63 * text/plain
64 64 * text/html
65 65 * text/markdown
66 66 * text/latex
67 67 * application/json
68 68 * application/javascript
69 69 * image/png
70 70 * image/jpeg
71 71 * image/svg+xml
72 72
73 73 Parameters
74 74 ----------
75 75 data : dict
76 76 A dictionary having keys that are valid MIME types (like
77 77 'text/plain' or 'image/svg+xml') and values that are the data for
78 78 that MIME type. The data itself must be a JSON'able data
79 79 structure. Minimally all data should have the 'text/plain' data,
80 80 which can be displayed by all frontends. If more than the plain
81 81 text is given, it is up to the frontend to decide which
82 82 representation to use.
83 83 metadata : dict
84 84 A dictionary for metadata related to the data. This can contain
85 85 arbitrary key, value pairs that frontends can use to interpret
86 86 the data. Metadata specific to each mime-type can be specified
87 87 in the metadata dict with the same mime-type keys as
88 88 the data itself.
89 89 source : str, deprecated
90 90 Unused.
91 91 """
92 92
93 93 # The default is to simply write the plain text data using io.stdout.
94 94 if 'text/plain' in data:
95 95 print(data['text/plain'], file=io.stdout)
96 96
97 97 def clear_output(self, wait=False):
98 98 """Clear the output of the cell receiving output."""
99 99 print('\033[2K\r', file=io.stdout, end='')
100 100 io.stdout.flush()
101 101 print('\033[2K\r', file=io.stderr, end='')
102 102 io.stderr.flush()
103 103
104 104
105 105 class CapturingDisplayPublisher(DisplayPublisher):
106 106 """A DisplayPublisher that stores"""
107 107 outputs = List()
108 108
109 109 def publish(self, data, metadata=None, source=None):
110 110 self.outputs.append((data, metadata))
111 111
112 112 def clear_output(self, wait=False):
113 113 super(CapturingDisplayPublisher, self).clear_output(wait)
114 114
115 115 # empty the list, *do not* reassign a new list
116 116 del self.outputs[:]
@@ -1,176 +1,176 b''
1 1 # encoding: utf-8
2 2 """A class for managing IPython extensions."""
3 3
4 4 # Copyright (c) IPython Development Team.
5 5 # Distributed under the terms of the Modified BSD License.
6 6
7 7 import os
8 8 from shutil import copyfile
9 9 import sys
10 10
11 from IPython.config.configurable import Configurable
11 from traitlets.config.configurable import Configurable
12 12 from IPython.utils.path import ensure_dir_exists
13 from IPython.utils.traitlets import Instance
13 from traitlets import Instance
14 14 from IPython.utils.py3compat import PY3
15 15 if PY3:
16 16 from imp import reload
17 17
18 18 #-----------------------------------------------------------------------------
19 19 # Main class
20 20 #-----------------------------------------------------------------------------
21 21
22 22 class ExtensionManager(Configurable):
23 23 """A class to manage IPython extensions.
24 24
25 25 An IPython extension is an importable Python module that has
26 26 a function with the signature::
27 27
28 28 def load_ipython_extension(ipython):
29 29 # Do things with ipython
30 30
31 31 This function is called after your extension is imported and the
32 32 currently active :class:`InteractiveShell` instance is passed as
33 33 the only argument. You can do anything you want with IPython at
34 34 that point, including defining new magic and aliases, adding new
35 35 components, etc.
36 36
37 37 You can also optionally define an :func:`unload_ipython_extension(ipython)`
38 38 function, which will be called if the user unloads or reloads the extension.
39 39 The extension manager will only call :func:`load_ipython_extension` again
40 40 if the extension is reloaded.
41 41
42 42 You can put your extension modules anywhere you want, as long as
43 43 they can be imported by Python's standard import mechanism. However,
44 44 to make it easy to write extensions, you can also put your extensions
45 45 in ``os.path.join(self.ipython_dir, 'extensions')``. This directory
46 46 is added to ``sys.path`` automatically.
47 47 """
48 48
49 49 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
50 50 allow_none=True)
51 51
52 52 def __init__(self, shell=None, **kwargs):
53 53 super(ExtensionManager, self).__init__(shell=shell, **kwargs)
54 54 self.shell.on_trait_change(
55 55 self._on_ipython_dir_changed, 'ipython_dir'
56 56 )
57 57 self.loaded = set()
58 58
59 59 def __del__(self):
60 60 self.shell.on_trait_change(
61 61 self._on_ipython_dir_changed, 'ipython_dir', remove=True
62 62 )
63 63
64 64 @property
65 65 def ipython_extension_dir(self):
66 66 return os.path.join(self.shell.ipython_dir, u'extensions')
67 67
68 68 def _on_ipython_dir_changed(self):
69 69 ensure_dir_exists(self.ipython_extension_dir)
70 70
71 71 def load_extension(self, module_str):
72 72 """Load an IPython extension by its module name.
73 73
74 74 Returns the string "already loaded" if the extension is already loaded,
75 75 "no load function" if the module doesn't have a load_ipython_extension
76 76 function, or None if it succeeded.
77 77 """
78 78 if module_str in self.loaded:
79 79 return "already loaded"
80 80
81 81 from IPython.utils.syspathcontext import prepended_to_syspath
82 82
83 83 with self.shell.builtin_trap:
84 84 if module_str not in sys.modules:
85 85 with prepended_to_syspath(self.ipython_extension_dir):
86 86 __import__(module_str)
87 87 mod = sys.modules[module_str]
88 88 if self._call_load_ipython_extension(mod):
89 89 self.loaded.add(module_str)
90 90 else:
91 91 return "no load function"
92 92
93 93 def unload_extension(self, module_str):
94 94 """Unload an IPython extension by its module name.
95 95
96 96 This function looks up the extension's name in ``sys.modules`` and
97 97 simply calls ``mod.unload_ipython_extension(self)``.
98 98
99 99 Returns the string "no unload function" if the extension doesn't define
100 100 a function to unload itself, "not loaded" if the extension isn't loaded,
101 101 otherwise None.
102 102 """
103 103 if module_str not in self.loaded:
104 104 return "not loaded"
105 105
106 106 if module_str in sys.modules:
107 107 mod = sys.modules[module_str]
108 108 if self._call_unload_ipython_extension(mod):
109 109 self.loaded.discard(module_str)
110 110 else:
111 111 return "no unload function"
112 112
113 113 def reload_extension(self, module_str):
114 114 """Reload an IPython extension by calling reload.
115 115
116 116 If the module has not been loaded before,
117 117 :meth:`InteractiveShell.load_extension` is called. Otherwise
118 118 :func:`reload` is called and then the :func:`load_ipython_extension`
119 119 function of the module, if it exists is called.
120 120 """
121 121 from IPython.utils.syspathcontext import prepended_to_syspath
122 122
123 123 if (module_str in self.loaded) and (module_str in sys.modules):
124 124 self.unload_extension(module_str)
125 125 mod = sys.modules[module_str]
126 126 with prepended_to_syspath(self.ipython_extension_dir):
127 127 reload(mod)
128 128 if self._call_load_ipython_extension(mod):
129 129 self.loaded.add(module_str)
130 130 else:
131 131 self.load_extension(module_str)
132 132
133 133 def _call_load_ipython_extension(self, mod):
134 134 if hasattr(mod, 'load_ipython_extension'):
135 135 mod.load_ipython_extension(self.shell)
136 136 return True
137 137
138 138 def _call_unload_ipython_extension(self, mod):
139 139 if hasattr(mod, 'unload_ipython_extension'):
140 140 mod.unload_ipython_extension(self.shell)
141 141 return True
142 142
143 143 def install_extension(self, url, filename=None):
144 144 """Download and install an IPython extension.
145 145
146 146 If filename is given, the file will be so named (inside the extension
147 147 directory). Otherwise, the name from the URL will be used. The file must
148 148 have a .py or .zip extension; otherwise, a ValueError will be raised.
149 149
150 150 Returns the full path to the installed file.
151 151 """
152 152 # Ensure the extension directory exists
153 153 ensure_dir_exists(self.ipython_extension_dir)
154 154
155 155 if os.path.isfile(url):
156 156 src_filename = os.path.basename(url)
157 157 copy = copyfile
158 158 else:
159 159 # Deferred imports
160 160 try:
161 161 from urllib.parse import urlparse # Py3
162 162 from urllib.request import urlretrieve
163 163 except ImportError:
164 164 from urlparse import urlparse
165 165 from urllib import urlretrieve
166 166 src_filename = urlparse(url).path.split('/')[-1]
167 167 copy = urlretrieve
168 168
169 169 if filename is None:
170 170 filename = src_filename
171 171 if os.path.splitext(filename)[1] not in ('.py', '.zip'):
172 172 raise ValueError("The file must have a .py or .zip extension", filename)
173 173
174 174 filename = os.path.join(self.ipython_extension_dir, filename)
175 175 copy(url, filename)
176 176 return filename
@@ -1,972 +1,972 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Display formatters.
3 3
4 4 Inheritance diagram:
5 5
6 6 .. inheritance-diagram:: IPython.core.formatters
7 7 :parts: 3
8 8 """
9 9
10 10 # Copyright (c) IPython Development Team.
11 11 # Distributed under the terms of the Modified BSD License.
12 12
13 13 import abc
14 14 import inspect
15 15 import json
16 16 import sys
17 17 import traceback
18 18 import warnings
19 19
20 20 from decorator import decorator
21 21
22 from IPython.config.configurable import Configurable
22 from traitlets.config.configurable import Configurable
23 23 from IPython.core.getipython import get_ipython
24 24 from IPython.utils.sentinel import Sentinel
25 25 from IPython.lib import pretty
26 from IPython.utils.traitlets import (
26 from traitlets import (
27 27 Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List,
28 28 ForwardDeclaredInstance,
29 29 )
30 30 from IPython.utils.py3compat import (
31 31 with_metaclass, string_types, unicode_type,
32 32 )
33 33
34 34
35 35 #-----------------------------------------------------------------------------
36 36 # The main DisplayFormatter class
37 37 #-----------------------------------------------------------------------------
38 38
39 39
40 40 def _safe_get_formatter_method(obj, name):
41 41 """Safely get a formatter method
42 42
43 43 - Classes cannot have formatter methods, only instance
44 44 - protect against proxy objects that claim to have everything
45 45 """
46 46 if inspect.isclass(obj):
47 47 # repr methods only make sense on instances, not classes
48 48 return None
49 49 method = pretty._safe_getattr(obj, name, None)
50 50 if callable(method):
51 51 # obj claims to have repr method...
52 52 if callable(pretty._safe_getattr(obj, '_ipython_canary_method_should_not_exist_', None)):
53 53 # ...but don't trust proxy objects that claim to have everything
54 54 return None
55 55 return method
56 56
57 57
58 58 class DisplayFormatter(Configurable):
59 59
60 60 # When set to true only the default plain text formatter will be used.
61 61 plain_text_only = Bool(False, config=True)
62 62 def _plain_text_only_changed(self, name, old, new):
63 63 warnings.warn("""DisplayFormatter.plain_text_only is deprecated.
64 64
65 65 Use DisplayFormatter.active_types = ['text/plain']
66 66 for the same effect.
67 67 """, DeprecationWarning)
68 68 if new:
69 69 self.active_types = ['text/plain']
70 70 else:
71 71 self.active_types = self.format_types
72 72
73 73 active_types = List(Unicode, config=True,
74 74 help="""List of currently active mime-types to display.
75 75 You can use this to set a white-list for formats to display.
76 76
77 77 Most users will not need to change this value.
78 78 """)
79 79 def _active_types_default(self):
80 80 return self.format_types
81 81
82 82 def _active_types_changed(self, name, old, new):
83 83 for key, formatter in self.formatters.items():
84 84 if key in new:
85 85 formatter.enabled = True
86 86 else:
87 87 formatter.enabled = False
88 88
89 89 ipython_display_formatter = ForwardDeclaredInstance('FormatterABC')
90 90 def _ipython_display_formatter_default(self):
91 91 return IPythonDisplayFormatter(parent=self)
92 92
93 93 # A dict of formatter whose keys are format types (MIME types) and whose
94 94 # values are subclasses of BaseFormatter.
95 95 formatters = Dict()
96 96 def _formatters_default(self):
97 97 """Activate the default formatters."""
98 98 formatter_classes = [
99 99 PlainTextFormatter,
100 100 HTMLFormatter,
101 101 MarkdownFormatter,
102 102 SVGFormatter,
103 103 PNGFormatter,
104 104 PDFFormatter,
105 105 JPEGFormatter,
106 106 LatexFormatter,
107 107 JSONFormatter,
108 108 JavascriptFormatter
109 109 ]
110 110 d = {}
111 111 for cls in formatter_classes:
112 112 f = cls(parent=self)
113 113 d[f.format_type] = f
114 114 return d
115 115
116 116 def format(self, obj, include=None, exclude=None):
117 117 """Return a format data dict for an object.
118 118
119 119 By default all format types will be computed.
120 120
121 121 The following MIME types are currently implemented:
122 122
123 123 * text/plain
124 124 * text/html
125 125 * text/markdown
126 126 * text/latex
127 127 * application/json
128 128 * application/javascript
129 129 * application/pdf
130 130 * image/png
131 131 * image/jpeg
132 132 * image/svg+xml
133 133
134 134 Parameters
135 135 ----------
136 136 obj : object
137 137 The Python object whose format data will be computed.
138 138 include : list or tuple, optional
139 139 A list of format type strings (MIME types) to include in the
140 140 format data dict. If this is set *only* the format types included
141 141 in this list will be computed.
142 142 exclude : list or tuple, optional
143 143 A list of format type string (MIME types) to exclude in the format
144 144 data dict. If this is set all format types will be computed,
145 145 except for those included in this argument.
146 146
147 147 Returns
148 148 -------
149 149 (format_dict, metadata_dict) : tuple of two dicts
150 150
151 151 format_dict is a dictionary of key/value pairs, one of each format that was
152 152 generated for the object. The keys are the format types, which
153 153 will usually be MIME type strings and the values and JSON'able
154 154 data structure containing the raw data for the representation in
155 155 that format.
156 156
157 157 metadata_dict is a dictionary of metadata about each mime-type output.
158 158 Its keys will be a strict subset of the keys in format_dict.
159 159 """
160 160 format_dict = {}
161 161 md_dict = {}
162 162
163 163 if self.ipython_display_formatter(obj):
164 164 # object handled itself, don't proceed
165 165 return {}, {}
166 166
167 167 for format_type, formatter in self.formatters.items():
168 168 if include and format_type not in include:
169 169 continue
170 170 if exclude and format_type in exclude:
171 171 continue
172 172
173 173 md = None
174 174 try:
175 175 data = formatter(obj)
176 176 except:
177 177 # FIXME: log the exception
178 178 raise
179 179
180 180 # formatters can return raw data or (data, metadata)
181 181 if isinstance(data, tuple) and len(data) == 2:
182 182 data, md = data
183 183
184 184 if data is not None:
185 185 format_dict[format_type] = data
186 186 if md is not None:
187 187 md_dict[format_type] = md
188 188
189 189 return format_dict, md_dict
190 190
191 191 @property
192 192 def format_types(self):
193 193 """Return the format types (MIME types) of the active formatters."""
194 194 return list(self.formatters.keys())
195 195
196 196
197 197 #-----------------------------------------------------------------------------
198 198 # Formatters for specific format types (text, html, svg, etc.)
199 199 #-----------------------------------------------------------------------------
200 200
201 201
202 202 def _safe_repr(obj):
203 203 """Try to return a repr of an object
204 204
205 205 always returns a string, at least.
206 206 """
207 207 try:
208 208 return repr(obj)
209 209 except Exception as e:
210 210 return "un-repr-able object (%r)" % e
211 211
212 212
213 213 class FormatterWarning(UserWarning):
214 214 """Warning class for errors in formatters"""
215 215
216 216 @decorator
217 217 def catch_format_error(method, self, *args, **kwargs):
218 218 """show traceback on failed format call"""
219 219 try:
220 220 r = method(self, *args, **kwargs)
221 221 except NotImplementedError:
222 222 # don't warn on NotImplementedErrors
223 223 return None
224 224 except Exception:
225 225 exc_info = sys.exc_info()
226 226 ip = get_ipython()
227 227 if ip is not None:
228 228 ip.showtraceback(exc_info)
229 229 else:
230 230 traceback.print_exception(*exc_info)
231 231 return None
232 232 return self._check_return(r, args[0])
233 233
234 234
235 235 class FormatterABC(with_metaclass(abc.ABCMeta, object)):
236 236 """ Abstract base class for Formatters.
237 237
238 238 A formatter is a callable class that is responsible for computing the
239 239 raw format data for a particular format type (MIME type). For example,
240 240 an HTML formatter would have a format type of `text/html` and would return
241 241 the HTML representation of the object when called.
242 242 """
243 243
244 244 # The format type of the data returned, usually a MIME type.
245 245 format_type = 'text/plain'
246 246
247 247 # Is the formatter enabled...
248 248 enabled = True
249 249
250 250 @abc.abstractmethod
251 251 def __call__(self, obj):
252 252 """Return a JSON'able representation of the object.
253 253
254 254 If the object cannot be formatted by this formatter,
255 255 warn and return None.
256 256 """
257 257 return repr(obj)
258 258
259 259
260 260 def _mod_name_key(typ):
261 261 """Return a (__module__, __name__) tuple for a type.
262 262
263 263 Used as key in Formatter.deferred_printers.
264 264 """
265 265 module = getattr(typ, '__module__', None)
266 266 name = getattr(typ, '__name__', None)
267 267 return (module, name)
268 268
269 269
270 270 def _get_type(obj):
271 271 """Return the type of an instance (old and new-style)"""
272 272 return getattr(obj, '__class__', None) or type(obj)
273 273
274 274
275 275 _raise_key_error = Sentinel('_raise_key_error', __name__,
276 276 """
277 277 Special value to raise a KeyError
278 278
279 279 Raise KeyError in `BaseFormatter.pop` if passed as the default value to `pop`
280 280 """)
281 281
282 282
283 283 class BaseFormatter(Configurable):
284 284 """A base formatter class that is configurable.
285 285
286 286 This formatter should usually be used as the base class of all formatters.
287 287 It is a traited :class:`Configurable` class and includes an extensible
288 288 API for users to determine how their objects are formatted. The following
289 289 logic is used to find a function to format an given object.
290 290
291 291 1. The object is introspected to see if it has a method with the name
292 292 :attr:`print_method`. If is does, that object is passed to that method
293 293 for formatting.
294 294 2. If no print method is found, three internal dictionaries are consulted
295 295 to find print method: :attr:`singleton_printers`, :attr:`type_printers`
296 296 and :attr:`deferred_printers`.
297 297
298 298 Users should use these dictionaries to register functions that will be
299 299 used to compute the format data for their objects (if those objects don't
300 300 have the special print methods). The easiest way of using these
301 301 dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
302 302 methods.
303 303
304 304 If no function/callable is found to compute the format data, ``None`` is
305 305 returned and this format type is not used.
306 306 """
307 307
308 308 format_type = Unicode('text/plain')
309 309 _return_type = string_types
310 310
311 311 enabled = Bool(True, config=True)
312 312
313 313 print_method = ObjectName('__repr__')
314 314
315 315 # The singleton printers.
316 316 # Maps the IDs of the builtin singleton objects to the format functions.
317 317 singleton_printers = Dict(config=True)
318 318
319 319 # The type-specific printers.
320 320 # Map type objects to the format functions.
321 321 type_printers = Dict(config=True)
322 322
323 323 # The deferred-import type-specific printers.
324 324 # Map (modulename, classname) pairs to the format functions.
325 325 deferred_printers = Dict(config=True)
326 326
327 327 @catch_format_error
328 328 def __call__(self, obj):
329 329 """Compute the format for an object."""
330 330 if self.enabled:
331 331 # lookup registered printer
332 332 try:
333 333 printer = self.lookup(obj)
334 334 except KeyError:
335 335 pass
336 336 else:
337 337 return printer(obj)
338 338 # Finally look for special method names
339 339 method = _safe_get_formatter_method(obj, self.print_method)
340 340 if method is not None:
341 341 return method()
342 342 return None
343 343 else:
344 344 return None
345 345
346 346 def __contains__(self, typ):
347 347 """map in to lookup_by_type"""
348 348 try:
349 349 self.lookup_by_type(typ)
350 350 except KeyError:
351 351 return False
352 352 else:
353 353 return True
354 354
355 355 def _check_return(self, r, obj):
356 356 """Check that a return value is appropriate
357 357
358 358 Return the value if so, None otherwise, warning if invalid.
359 359 """
360 360 if r is None or isinstance(r, self._return_type) or \
361 361 (isinstance(r, tuple) and r and isinstance(r[0], self._return_type)):
362 362 return r
363 363 else:
364 364 warnings.warn(
365 365 "%s formatter returned invalid type %s (expected %s) for object: %s" % \
366 366 (self.format_type, type(r), self._return_type, _safe_repr(obj)),
367 367 FormatterWarning
368 368 )
369 369
370 370 def lookup(self, obj):
371 371 """Look up the formatter for a given instance.
372 372
373 373 Parameters
374 374 ----------
375 375 obj : object instance
376 376
377 377 Returns
378 378 -------
379 379 f : callable
380 380 The registered formatting callable for the type.
381 381
382 382 Raises
383 383 ------
384 384 KeyError if the type has not been registered.
385 385 """
386 386 # look for singleton first
387 387 obj_id = id(obj)
388 388 if obj_id in self.singleton_printers:
389 389 return self.singleton_printers[obj_id]
390 390 # then lookup by type
391 391 return self.lookup_by_type(_get_type(obj))
392 392
393 393 def lookup_by_type(self, typ):
394 394 """Look up the registered formatter for a type.
395 395
396 396 Parameters
397 397 ----------
398 398 typ : type or '__module__.__name__' string for a type
399 399
400 400 Returns
401 401 -------
402 402 f : callable
403 403 The registered formatting callable for the type.
404 404
405 405 Raises
406 406 ------
407 407 KeyError if the type has not been registered.
408 408 """
409 409 if isinstance(typ, string_types):
410 410 typ_key = tuple(typ.rsplit('.',1))
411 411 if typ_key not in self.deferred_printers:
412 412 # We may have it cached in the type map. We will have to
413 413 # iterate over all of the types to check.
414 414 for cls in self.type_printers:
415 415 if _mod_name_key(cls) == typ_key:
416 416 return self.type_printers[cls]
417 417 else:
418 418 return self.deferred_printers[typ_key]
419 419 else:
420 420 for cls in pretty._get_mro(typ):
421 421 if cls in self.type_printers or self._in_deferred_types(cls):
422 422 return self.type_printers[cls]
423 423
424 424 # If we have reached here, the lookup failed.
425 425 raise KeyError("No registered printer for {0!r}".format(typ))
426 426
427 427 def for_type(self, typ, func=None):
428 428 """Add a format function for a given type.
429 429
430 430 Parameters
431 431 -----------
432 432 typ : type or '__module__.__name__' string for a type
433 433 The class of the object that will be formatted using `func`.
434 434 func : callable
435 435 A callable for computing the format data.
436 436 `func` will be called with the object to be formatted,
437 437 and will return the raw data in this formatter's format.
438 438 Subclasses may use a different call signature for the
439 439 `func` argument.
440 440
441 441 If `func` is None or not specified, there will be no change,
442 442 only returning the current value.
443 443
444 444 Returns
445 445 -------
446 446 oldfunc : callable
447 447 The currently registered callable.
448 448 If you are registering a new formatter,
449 449 this will be the previous value (to enable restoring later).
450 450 """
451 451 # if string given, interpret as 'pkg.module.class_name'
452 452 if isinstance(typ, string_types):
453 453 type_module, type_name = typ.rsplit('.', 1)
454 454 return self.for_type_by_name(type_module, type_name, func)
455 455
456 456 try:
457 457 oldfunc = self.lookup_by_type(typ)
458 458 except KeyError:
459 459 oldfunc = None
460 460
461 461 if func is not None:
462 462 self.type_printers[typ] = func
463 463
464 464 return oldfunc
465 465
466 466 def for_type_by_name(self, type_module, type_name, func=None):
467 467 """Add a format function for a type specified by the full dotted
468 468 module and name of the type, rather than the type of the object.
469 469
470 470 Parameters
471 471 ----------
472 472 type_module : str
473 473 The full dotted name of the module the type is defined in, like
474 474 ``numpy``.
475 475 type_name : str
476 476 The name of the type (the class name), like ``dtype``
477 477 func : callable
478 478 A callable for computing the format data.
479 479 `func` will be called with the object to be formatted,
480 480 and will return the raw data in this formatter's format.
481 481 Subclasses may use a different call signature for the
482 482 `func` argument.
483 483
484 484 If `func` is None or unspecified, there will be no change,
485 485 only returning the current value.
486 486
487 487 Returns
488 488 -------
489 489 oldfunc : callable
490 490 The currently registered callable.
491 491 If you are registering a new formatter,
492 492 this will be the previous value (to enable restoring later).
493 493 """
494 494 key = (type_module, type_name)
495 495
496 496 try:
497 497 oldfunc = self.lookup_by_type("%s.%s" % key)
498 498 except KeyError:
499 499 oldfunc = None
500 500
501 501 if func is not None:
502 502 self.deferred_printers[key] = func
503 503 return oldfunc
504 504
505 505 def pop(self, typ, default=_raise_key_error):
506 506 """Pop a formatter for the given type.
507 507
508 508 Parameters
509 509 ----------
510 510 typ : type or '__module__.__name__' string for a type
511 511 default : object
512 512 value to be returned if no formatter is registered for typ.
513 513
514 514 Returns
515 515 -------
516 516 obj : object
517 517 The last registered object for the type.
518 518
519 519 Raises
520 520 ------
521 521 KeyError if the type is not registered and default is not specified.
522 522 """
523 523
524 524 if isinstance(typ, string_types):
525 525 typ_key = tuple(typ.rsplit('.',1))
526 526 if typ_key not in self.deferred_printers:
527 527 # We may have it cached in the type map. We will have to
528 528 # iterate over all of the types to check.
529 529 for cls in self.type_printers:
530 530 if _mod_name_key(cls) == typ_key:
531 531 old = self.type_printers.pop(cls)
532 532 break
533 533 else:
534 534 old = default
535 535 else:
536 536 old = self.deferred_printers.pop(typ_key)
537 537 else:
538 538 if typ in self.type_printers:
539 539 old = self.type_printers.pop(typ)
540 540 else:
541 541 old = self.deferred_printers.pop(_mod_name_key(typ), default)
542 542 if old is _raise_key_error:
543 543 raise KeyError("No registered value for {0!r}".format(typ))
544 544 return old
545 545
546 546 def _in_deferred_types(self, cls):
547 547 """
548 548 Check if the given class is specified in the deferred type registry.
549 549
550 550 Successful matches will be moved to the regular type registry for future use.
551 551 """
552 552 mod = getattr(cls, '__module__', None)
553 553 name = getattr(cls, '__name__', None)
554 554 key = (mod, name)
555 555 if key in self.deferred_printers:
556 556 # Move the printer over to the regular registry.
557 557 printer = self.deferred_printers.pop(key)
558 558 self.type_printers[cls] = printer
559 559 return True
560 560 return False
561 561
562 562
563 563 class PlainTextFormatter(BaseFormatter):
564 564 """The default pretty-printer.
565 565
566 566 This uses :mod:`IPython.lib.pretty` to compute the format data of
567 567 the object. If the object cannot be pretty printed, :func:`repr` is used.
568 568 See the documentation of :mod:`IPython.lib.pretty` for details on
569 569 how to write pretty printers. Here is a simple example::
570 570
571 571 def dtype_pprinter(obj, p, cycle):
572 572 if cycle:
573 573 return p.text('dtype(...)')
574 574 if hasattr(obj, 'fields'):
575 575 if obj.fields is None:
576 576 p.text(repr(obj))
577 577 else:
578 578 p.begin_group(7, 'dtype([')
579 579 for i, field in enumerate(obj.descr):
580 580 if i > 0:
581 581 p.text(',')
582 582 p.breakable()
583 583 p.pretty(field)
584 584 p.end_group(7, '])')
585 585 """
586 586
587 587 # The format type of data returned.
588 588 format_type = Unicode('text/plain')
589 589
590 590 # This subclass ignores this attribute as it always need to return
591 591 # something.
592 592 enabled = Bool(True, config=False)
593 593
594 594 max_seq_length = Integer(pretty.MAX_SEQ_LENGTH, config=True,
595 595 help="""Truncate large collections (lists, dicts, tuples, sets) to this size.
596 596
597 597 Set to 0 to disable truncation.
598 598 """
599 599 )
600 600
601 601 # Look for a _repr_pretty_ methods to use for pretty printing.
602 602 print_method = ObjectName('_repr_pretty_')
603 603
604 604 # Whether to pretty-print or not.
605 605 pprint = Bool(True, config=True)
606 606
607 607 # Whether to be verbose or not.
608 608 verbose = Bool(False, config=True)
609 609
610 610 # The maximum width.
611 611 max_width = Integer(79, config=True)
612 612
613 613 # The newline character.
614 614 newline = Unicode('\n', config=True)
615 615
616 616 # format-string for pprinting floats
617 617 float_format = Unicode('%r')
618 618 # setter for float precision, either int or direct format-string
619 619 float_precision = CUnicode('', config=True)
620 620
621 621 def _float_precision_changed(self, name, old, new):
622 622 """float_precision changed, set float_format accordingly.
623 623
624 624 float_precision can be set by int or str.
625 625 This will set float_format, after interpreting input.
626 626 If numpy has been imported, numpy print precision will also be set.
627 627
628 628 integer `n` sets format to '%.nf', otherwise, format set directly.
629 629
630 630 An empty string returns to defaults (repr for float, 8 for numpy).
631 631
632 632 This parameter can be set via the '%precision' magic.
633 633 """
634 634
635 635 if '%' in new:
636 636 # got explicit format string
637 637 fmt = new
638 638 try:
639 639 fmt%3.14159
640 640 except Exception:
641 641 raise ValueError("Precision must be int or format string, not %r"%new)
642 642 elif new:
643 643 # otherwise, should be an int
644 644 try:
645 645 i = int(new)
646 646 assert i >= 0
647 647 except ValueError:
648 648 raise ValueError("Precision must be int or format string, not %r"%new)
649 649 except AssertionError:
650 650 raise ValueError("int precision must be non-negative, not %r"%i)
651 651
652 652 fmt = '%%.%if'%i
653 653 if 'numpy' in sys.modules:
654 654 # set numpy precision if it has been imported
655 655 import numpy
656 656 numpy.set_printoptions(precision=i)
657 657 else:
658 658 # default back to repr
659 659 fmt = '%r'
660 660 if 'numpy' in sys.modules:
661 661 import numpy
662 662 # numpy default is 8
663 663 numpy.set_printoptions(precision=8)
664 664 self.float_format = fmt
665 665
666 666 # Use the default pretty printers from IPython.lib.pretty.
667 667 def _singleton_printers_default(self):
668 668 return pretty._singleton_pprinters.copy()
669 669
670 670 def _type_printers_default(self):
671 671 d = pretty._type_pprinters.copy()
672 672 d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
673 673 return d
674 674
675 675 def _deferred_printers_default(self):
676 676 return pretty._deferred_type_pprinters.copy()
677 677
678 678 #### FormatterABC interface ####
679 679
680 680 @catch_format_error
681 681 def __call__(self, obj):
682 682 """Compute the pretty representation of the object."""
683 683 if not self.pprint:
684 684 return repr(obj)
685 685 else:
686 686 # handle str and unicode on Python 2
687 687 # io.StringIO only accepts unicode,
688 688 # cStringIO doesn't handle unicode on py2,
689 689 # StringIO allows str, unicode but only ascii str
690 690 stream = pretty.CUnicodeIO()
691 691 printer = pretty.RepresentationPrinter(stream, self.verbose,
692 692 self.max_width, self.newline,
693 693 max_seq_length=self.max_seq_length,
694 694 singleton_pprinters=self.singleton_printers,
695 695 type_pprinters=self.type_printers,
696 696 deferred_pprinters=self.deferred_printers)
697 697 printer.pretty(obj)
698 698 printer.flush()
699 699 return stream.getvalue()
700 700
701 701
702 702 class HTMLFormatter(BaseFormatter):
703 703 """An HTML formatter.
704 704
705 705 To define the callables that compute the HTML representation of your
706 706 objects, define a :meth:`_repr_html_` method or use the :meth:`for_type`
707 707 or :meth:`for_type_by_name` methods to register functions that handle
708 708 this.
709 709
710 710 The return value of this formatter should be a valid HTML snippet that
711 711 could be injected into an existing DOM. It should *not* include the
712 712 ```<html>`` or ```<body>`` tags.
713 713 """
714 714 format_type = Unicode('text/html')
715 715
716 716 print_method = ObjectName('_repr_html_')
717 717
718 718
719 719 class MarkdownFormatter(BaseFormatter):
720 720 """A Markdown formatter.
721 721
722 722 To define the callables that compute the Markdown representation of your
723 723 objects, define a :meth:`_repr_markdown_` method or use the :meth:`for_type`
724 724 or :meth:`for_type_by_name` methods to register functions that handle
725 725 this.
726 726
727 727 The return value of this formatter should be a valid Markdown.
728 728 """
729 729 format_type = Unicode('text/markdown')
730 730
731 731 print_method = ObjectName('_repr_markdown_')
732 732
733 733 class SVGFormatter(BaseFormatter):
734 734 """An SVG formatter.
735 735
736 736 To define the callables that compute the SVG representation of your
737 737 objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type`
738 738 or :meth:`for_type_by_name` methods to register functions that handle
739 739 this.
740 740
741 741 The return value of this formatter should be valid SVG enclosed in
742 742 ```<svg>``` tags, that could be injected into an existing DOM. It should
743 743 *not* include the ```<html>`` or ```<body>`` tags.
744 744 """
745 745 format_type = Unicode('image/svg+xml')
746 746
747 747 print_method = ObjectName('_repr_svg_')
748 748
749 749
750 750 class PNGFormatter(BaseFormatter):
751 751 """A PNG formatter.
752 752
753 753 To define the callables that compute the PNG representation of your
754 754 objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
755 755 or :meth:`for_type_by_name` methods to register functions that handle
756 756 this.
757 757
758 758 The return value of this formatter should be raw PNG data, *not*
759 759 base64 encoded.
760 760 """
761 761 format_type = Unicode('image/png')
762 762
763 763 print_method = ObjectName('_repr_png_')
764 764
765 765 _return_type = (bytes, unicode_type)
766 766
767 767
768 768 class JPEGFormatter(BaseFormatter):
769 769 """A JPEG formatter.
770 770
771 771 To define the callables that compute the JPEG representation of your
772 772 objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type`
773 773 or :meth:`for_type_by_name` methods to register functions that handle
774 774 this.
775 775
776 776 The return value of this formatter should be raw JPEG data, *not*
777 777 base64 encoded.
778 778 """
779 779 format_type = Unicode('image/jpeg')
780 780
781 781 print_method = ObjectName('_repr_jpeg_')
782 782
783 783 _return_type = (bytes, unicode_type)
784 784
785 785
786 786 class LatexFormatter(BaseFormatter):
787 787 """A LaTeX formatter.
788 788
789 789 To define the callables that compute the LaTeX representation of your
790 790 objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type`
791 791 or :meth:`for_type_by_name` methods to register functions that handle
792 792 this.
793 793
794 794 The return value of this formatter should be a valid LaTeX equation,
795 795 enclosed in either ```$```, ```$$``` or another LaTeX equation
796 796 environment.
797 797 """
798 798 format_type = Unicode('text/latex')
799 799
800 800 print_method = ObjectName('_repr_latex_')
801 801
802 802
803 803 class JSONFormatter(BaseFormatter):
804 804 """A JSON string formatter.
805 805
806 806 To define the callables that compute the JSONable representation of
807 807 your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type`
808 808 or :meth:`for_type_by_name` methods to register functions that handle
809 809 this.
810 810
811 811 The return value of this formatter should be a JSONable list or dict.
812 812 JSON scalars (None, number, string) are not allowed, only dict or list containers.
813 813 """
814 814 format_type = Unicode('application/json')
815 815 _return_type = (list, dict)
816 816
817 817 print_method = ObjectName('_repr_json_')
818 818
819 819 def _check_return(self, r, obj):
820 820 """Check that a return value is appropriate
821 821
822 822 Return the value if so, None otherwise, warning if invalid.
823 823 """
824 824 if r is None:
825 825 return
826 826 md = None
827 827 if isinstance(r, tuple):
828 828 # unpack data, metadata tuple for type checking on first element
829 829 r, md = r
830 830
831 831 # handle deprecated JSON-as-string form from IPython < 3
832 832 if isinstance(r, string_types):
833 833 warnings.warn("JSON expects JSONable list/dict containers, not JSON strings",
834 834 FormatterWarning)
835 835 r = json.loads(r)
836 836
837 837 if md is not None:
838 838 # put the tuple back together
839 839 r = (r, md)
840 840 return super(JSONFormatter, self)._check_return(r, obj)
841 841
842 842
843 843 class JavascriptFormatter(BaseFormatter):
844 844 """A Javascript formatter.
845 845
846 846 To define the callables that compute the Javascript representation of
847 847 your objects, define a :meth:`_repr_javascript_` method or use the
848 848 :meth:`for_type` or :meth:`for_type_by_name` methods to register functions
849 849 that handle this.
850 850
851 851 The return value of this formatter should be valid Javascript code and
852 852 should *not* be enclosed in ```<script>``` tags.
853 853 """
854 854 format_type = Unicode('application/javascript')
855 855
856 856 print_method = ObjectName('_repr_javascript_')
857 857
858 858
859 859 class PDFFormatter(BaseFormatter):
860 860 """A PDF formatter.
861 861
862 862 To define the callables that compute the PDF representation of your
863 863 objects, define a :meth:`_repr_pdf_` method or use the :meth:`for_type`
864 864 or :meth:`for_type_by_name` methods to register functions that handle
865 865 this.
866 866
867 867 The return value of this formatter should be raw PDF data, *not*
868 868 base64 encoded.
869 869 """
870 870 format_type = Unicode('application/pdf')
871 871
872 872 print_method = ObjectName('_repr_pdf_')
873 873
874 874 _return_type = (bytes, unicode_type)
875 875
876 876 class IPythonDisplayFormatter(BaseFormatter):
877 877 """A Formatter for objects that know how to display themselves.
878 878
879 879 To define the callables that compute the representation of your
880 880 objects, define a :meth:`_ipython_display_` method or use the :meth:`for_type`
881 881 or :meth:`for_type_by_name` methods to register functions that handle
882 882 this. Unlike mime-type displays, this method should not return anything,
883 883 instead calling any appropriate display methods itself.
884 884
885 885 This display formatter has highest priority.
886 886 If it fires, no other display formatter will be called.
887 887 """
888 888 print_method = ObjectName('_ipython_display_')
889 889 _return_type = (type(None), bool)
890 890
891 891
892 892 @catch_format_error
893 893 def __call__(self, obj):
894 894 """Compute the format for an object."""
895 895 if self.enabled:
896 896 # lookup registered printer
897 897 try:
898 898 printer = self.lookup(obj)
899 899 except KeyError:
900 900 pass
901 901 else:
902 902 printer(obj)
903 903 return True
904 904 # Finally look for special method names
905 905 method = _safe_get_formatter_method(obj, self.print_method)
906 906 if method is not None:
907 907 method()
908 908 return True
909 909
910 910
911 911 FormatterABC.register(BaseFormatter)
912 912 FormatterABC.register(PlainTextFormatter)
913 913 FormatterABC.register(HTMLFormatter)
914 914 FormatterABC.register(MarkdownFormatter)
915 915 FormatterABC.register(SVGFormatter)
916 916 FormatterABC.register(PNGFormatter)
917 917 FormatterABC.register(PDFFormatter)
918 918 FormatterABC.register(JPEGFormatter)
919 919 FormatterABC.register(LatexFormatter)
920 920 FormatterABC.register(JSONFormatter)
921 921 FormatterABC.register(JavascriptFormatter)
922 922 FormatterABC.register(IPythonDisplayFormatter)
923 923
924 924
925 925 def format_display_data(obj, include=None, exclude=None):
926 926 """Return a format data dict for an object.
927 927
928 928 By default all format types will be computed.
929 929
930 930 The following MIME types are currently implemented:
931 931
932 932 * text/plain
933 933 * text/html
934 934 * text/markdown
935 935 * text/latex
936 936 * application/json
937 937 * application/javascript
938 938 * application/pdf
939 939 * image/png
940 940 * image/jpeg
941 941 * image/svg+xml
942 942
943 943 Parameters
944 944 ----------
945 945 obj : object
946 946 The Python object whose format data will be computed.
947 947
948 948 Returns
949 949 -------
950 950 format_dict : dict
951 951 A dictionary of key/value pairs, one or each format that was
952 952 generated for the object. The keys are the format types, which
953 953 will usually be MIME type strings and the values and JSON'able
954 954 data structure containing the raw data for the representation in
955 955 that format.
956 956 include : list or tuple, optional
957 957 A list of format type strings (MIME types) to include in the
958 958 format data dict. If this is set *only* the format types included
959 959 in this list will be computed.
960 960 exclude : list or tuple, optional
961 961 A list of format type string (MIME types) to exclue in the format
962 962 data dict. If this is set all format types will be computed,
963 963 except for those included in this argument.
964 964 """
965 965 from IPython.core.interactiveshell import InteractiveShell
966 966
967 967 InteractiveShell.instance().display_formatter.format(
968 968 obj,
969 969 include,
970 970 exclude
971 971 )
972 972
@@ -1,872 +1,872 b''
1 1 """ History related magics and functionality """
2 2 #-----------------------------------------------------------------------------
3 3 # Copyright (C) 2010-2011 The IPython Development Team.
4 4 #
5 5 # Distributed under the terms of the BSD License.
6 6 #
7 7 # The full license is in the file COPYING.txt, distributed with this software.
8 8 #-----------------------------------------------------------------------------
9 9
10 10 #-----------------------------------------------------------------------------
11 11 # Imports
12 12 #-----------------------------------------------------------------------------
13 13 from __future__ import print_function
14 14
15 15 # Stdlib imports
16 16 import atexit
17 17 import datetime
18 18 import os
19 19 import re
20 20 try:
21 21 import sqlite3
22 22 except ImportError:
23 23 try:
24 24 from pysqlite2 import dbapi2 as sqlite3
25 25 except ImportError:
26 26 sqlite3 = None
27 27 import threading
28 28
29 29 # Our own packages
30 from IPython.config.configurable import Configurable
30 from traitlets.config.configurable import Configurable
31 31 from decorator import decorator
32 32 from IPython.utils.decorators import undoc
33 33 from IPython.utils.path import locate_profile
34 34 from IPython.utils import py3compat
35 from IPython.utils.traitlets import (
35 from traitlets import (
36 36 Any, Bool, Dict, Instance, Integer, List, Unicode, TraitError,
37 37 )
38 38 from IPython.utils.warn import warn
39 39
40 40 #-----------------------------------------------------------------------------
41 41 # Classes and functions
42 42 #-----------------------------------------------------------------------------
43 43
44 44 @undoc
45 45 class DummyDB(object):
46 46 """Dummy DB that will act as a black hole for history.
47 47
48 48 Only used in the absence of sqlite"""
49 49 def execute(*args, **kwargs):
50 50 return []
51 51
52 52 def commit(self, *args, **kwargs):
53 53 pass
54 54
55 55 def __enter__(self, *args, **kwargs):
56 56 pass
57 57
58 58 def __exit__(self, *args, **kwargs):
59 59 pass
60 60
61 61
62 62 @decorator
63 63 def needs_sqlite(f, self, *a, **kw):
64 64 """Decorator: return an empty list in the absence of sqlite."""
65 65 if sqlite3 is None or not self.enabled:
66 66 return []
67 67 else:
68 68 return f(self, *a, **kw)
69 69
70 70
71 71 if sqlite3 is not None:
72 72 DatabaseError = sqlite3.DatabaseError
73 73 else:
74 74 @undoc
75 75 class DatabaseError(Exception):
76 76 "Dummy exception when sqlite could not be imported. Should never occur."
77 77
78 78 @decorator
79 79 def catch_corrupt_db(f, self, *a, **kw):
80 80 """A decorator which wraps HistoryAccessor method calls to catch errors from
81 81 a corrupt SQLite database, move the old database out of the way, and create
82 82 a new one.
83 83 """
84 84 try:
85 85 return f(self, *a, **kw)
86 86 except DatabaseError:
87 87 if os.path.isfile(self.hist_file):
88 88 # Try to move the file out of the way
89 89 base,ext = os.path.splitext(self.hist_file)
90 90 newpath = base + '-corrupt' + ext
91 91 os.rename(self.hist_file, newpath)
92 92 self.init_db()
93 93 print("ERROR! History file wasn't a valid SQLite database.",
94 94 "It was moved to %s" % newpath, "and a new file created.")
95 95 return []
96 96
97 97 else:
98 98 # The hist_file is probably :memory: or something else.
99 99 raise
100 100
101 101 class HistoryAccessorBase(Configurable):
102 102 """An abstract class for History Accessors """
103 103
104 104 def get_tail(self, n=10, raw=True, output=False, include_latest=False):
105 105 raise NotImplementedError
106 106
107 107 def search(self, pattern="*", raw=True, search_raw=True,
108 108 output=False, n=None, unique=False):
109 109 raise NotImplementedError
110 110
111 111 def get_range(self, session, start=1, stop=None, raw=True,output=False):
112 112 raise NotImplementedError
113 113
114 114 def get_range_by_str(self, rangestr, raw=True, output=False):
115 115 raise NotImplementedError
116 116
117 117
118 118 class HistoryAccessor(HistoryAccessorBase):
119 119 """Access the history database without adding to it.
120 120
121 121 This is intended for use by standalone history tools. IPython shells use
122 122 HistoryManager, below, which is a subclass of this."""
123 123
124 124 # String holding the path to the history file
125 125 hist_file = Unicode(config=True,
126 126 help="""Path to file to use for SQLite history database.
127 127
128 128 By default, IPython will put the history database in the IPython
129 129 profile directory. If you would rather share one history among
130 130 profiles, you can set this value in each, so that they are consistent.
131 131
132 132 Due to an issue with fcntl, SQLite is known to misbehave on some NFS
133 133 mounts. If you see IPython hanging, try setting this to something on a
134 134 local disk, e.g::
135 135
136 136 ipython --HistoryManager.hist_file=/tmp/ipython_hist.sqlite
137 137
138 138 """)
139 139
140 140 enabled = Bool(True, config=True,
141 141 help="""enable the SQLite history
142 142
143 143 set enabled=False to disable the SQLite history,
144 144 in which case there will be no stored history, no SQLite connection,
145 145 and no background saving thread. This may be necessary in some
146 146 threaded environments where IPython is embedded.
147 147 """
148 148 )
149 149
150 150 connection_options = Dict(config=True,
151 151 help="""Options for configuring the SQLite connection
152 152
153 153 These options are passed as keyword args to sqlite3.connect
154 154 when establishing database conenctions.
155 155 """
156 156 )
157 157
158 158 # The SQLite database
159 159 db = Any()
160 160 def _db_changed(self, name, old, new):
161 161 """validate the db, since it can be an Instance of two different types"""
162 162 connection_types = (DummyDB,)
163 163 if sqlite3 is not None:
164 164 connection_types = (DummyDB, sqlite3.Connection)
165 165 if not isinstance(new, connection_types):
166 166 msg = "%s.db must be sqlite3 Connection or DummyDB, not %r" % \
167 167 (self.__class__.__name__, new)
168 168 raise TraitError(msg)
169 169
170 170 def __init__(self, profile='default', hist_file=u'', **traits):
171 171 """Create a new history accessor.
172 172
173 173 Parameters
174 174 ----------
175 175 profile : str
176 176 The name of the profile from which to open history.
177 177 hist_file : str
178 178 Path to an SQLite history database stored by IPython. If specified,
179 179 hist_file overrides profile.
180 config : :class:`~IPython.config.loader.Config`
180 config : :class:`~traitlets.config.loader.Config`
181 181 Config object. hist_file can also be set through this.
182 182 """
183 183 # We need a pointer back to the shell for various tasks.
184 184 super(HistoryAccessor, self).__init__(**traits)
185 185 # defer setting hist_file from kwarg until after init,
186 186 # otherwise the default kwarg value would clobber any value
187 187 # set by config
188 188 if hist_file:
189 189 self.hist_file = hist_file
190 190
191 191 if self.hist_file == u'':
192 192 # No one has set the hist_file, yet.
193 193 self.hist_file = self._get_hist_file_name(profile)
194 194
195 195 if sqlite3 is None and self.enabled:
196 196 warn("IPython History requires SQLite, your history will not be saved")
197 197 self.enabled = False
198 198
199 199 self.init_db()
200 200
201 201 def _get_hist_file_name(self, profile='default'):
202 202 """Find the history file for the given profile name.
203 203
204 204 This is overridden by the HistoryManager subclass, to use the shell's
205 205 active profile.
206 206
207 207 Parameters
208 208 ----------
209 209 profile : str
210 210 The name of a profile which has a history file.
211 211 """
212 212 return os.path.join(locate_profile(profile), 'history.sqlite')
213 213
214 214 @catch_corrupt_db
215 215 def init_db(self):
216 216 """Connect to the database, and create tables if necessary."""
217 217 if not self.enabled:
218 218 self.db = DummyDB()
219 219 return
220 220
221 221 # use detect_types so that timestamps return datetime objects
222 222 kwargs = dict(detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
223 223 kwargs.update(self.connection_options)
224 224 self.db = sqlite3.connect(self.hist_file, **kwargs)
225 225 self.db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer
226 226 primary key autoincrement, start timestamp,
227 227 end timestamp, num_cmds integer, remark text)""")
228 228 self.db.execute("""CREATE TABLE IF NOT EXISTS history
229 229 (session integer, line integer, source text, source_raw text,
230 230 PRIMARY KEY (session, line))""")
231 231 # Output history is optional, but ensure the table's there so it can be
232 232 # enabled later.
233 233 self.db.execute("""CREATE TABLE IF NOT EXISTS output_history
234 234 (session integer, line integer, output text,
235 235 PRIMARY KEY (session, line))""")
236 236 self.db.commit()
237 237
238 238 def writeout_cache(self):
239 239 """Overridden by HistoryManager to dump the cache before certain
240 240 database lookups."""
241 241 pass
242 242
243 243 ## -------------------------------
244 244 ## Methods for retrieving history:
245 245 ## -------------------------------
246 246 def _run_sql(self, sql, params, raw=True, output=False):
247 247 """Prepares and runs an SQL query for the history database.
248 248
249 249 Parameters
250 250 ----------
251 251 sql : str
252 252 Any filtering expressions to go after SELECT ... FROM ...
253 253 params : tuple
254 254 Parameters passed to the SQL query (to replace "?")
255 255 raw, output : bool
256 256 See :meth:`get_range`
257 257
258 258 Returns
259 259 -------
260 260 Tuples as :meth:`get_range`
261 261 """
262 262 toget = 'source_raw' if raw else 'source'
263 263 sqlfrom = "history"
264 264 if output:
265 265 sqlfrom = "history LEFT JOIN output_history USING (session, line)"
266 266 toget = "history.%s, output_history.output" % toget
267 267 cur = self.db.execute("SELECT session, line, %s FROM %s " %\
268 268 (toget, sqlfrom) + sql, params)
269 269 if output: # Regroup into 3-tuples, and parse JSON
270 270 return ((ses, lin, (inp, out)) for ses, lin, inp, out in cur)
271 271 return cur
272 272
273 273 @needs_sqlite
274 274 @catch_corrupt_db
275 275 def get_session_info(self, session):
276 276 """Get info about a session.
277 277
278 278 Parameters
279 279 ----------
280 280
281 281 session : int
282 282 Session number to retrieve.
283 283
284 284 Returns
285 285 -------
286 286
287 287 session_id : int
288 288 Session ID number
289 289 start : datetime
290 290 Timestamp for the start of the session.
291 291 end : datetime
292 292 Timestamp for the end of the session, or None if IPython crashed.
293 293 num_cmds : int
294 294 Number of commands run, or None if IPython crashed.
295 295 remark : unicode
296 296 A manually set description.
297 297 """
298 298 query = "SELECT * from sessions where session == ?"
299 299 return self.db.execute(query, (session,)).fetchone()
300 300
301 301 @catch_corrupt_db
302 302 def get_last_session_id(self):
303 303 """Get the last session ID currently in the database.
304 304
305 305 Within IPython, this should be the same as the value stored in
306 306 :attr:`HistoryManager.session_number`.
307 307 """
308 308 for record in self.get_tail(n=1, include_latest=True):
309 309 return record[0]
310 310
311 311 @catch_corrupt_db
312 312 def get_tail(self, n=10, raw=True, output=False, include_latest=False):
313 313 """Get the last n lines from the history database.
314 314
315 315 Parameters
316 316 ----------
317 317 n : int
318 318 The number of lines to get
319 319 raw, output : bool
320 320 See :meth:`get_range`
321 321 include_latest : bool
322 322 If False (default), n+1 lines are fetched, and the latest one
323 323 is discarded. This is intended to be used where the function
324 324 is called by a user command, which it should not return.
325 325
326 326 Returns
327 327 -------
328 328 Tuples as :meth:`get_range`
329 329 """
330 330 self.writeout_cache()
331 331 if not include_latest:
332 332 n += 1
333 333 cur = self._run_sql("ORDER BY session DESC, line DESC LIMIT ?",
334 334 (n,), raw=raw, output=output)
335 335 if not include_latest:
336 336 return reversed(list(cur)[1:])
337 337 return reversed(list(cur))
338 338
339 339 @catch_corrupt_db
340 340 def search(self, pattern="*", raw=True, search_raw=True,
341 341 output=False, n=None, unique=False):
342 342 """Search the database using unix glob-style matching (wildcards
343 343 * and ?).
344 344
345 345 Parameters
346 346 ----------
347 347 pattern : str
348 348 The wildcarded pattern to match when searching
349 349 search_raw : bool
350 350 If True, search the raw input, otherwise, the parsed input
351 351 raw, output : bool
352 352 See :meth:`get_range`
353 353 n : None or int
354 354 If an integer is given, it defines the limit of
355 355 returned entries.
356 356 unique : bool
357 357 When it is true, return only unique entries.
358 358
359 359 Returns
360 360 -------
361 361 Tuples as :meth:`get_range`
362 362 """
363 363 tosearch = "source_raw" if search_raw else "source"
364 364 if output:
365 365 tosearch = "history." + tosearch
366 366 self.writeout_cache()
367 367 sqlform = "WHERE %s GLOB ?" % tosearch
368 368 params = (pattern,)
369 369 if unique:
370 370 sqlform += ' GROUP BY {0}'.format(tosearch)
371 371 if n is not None:
372 372 sqlform += " ORDER BY session DESC, line DESC LIMIT ?"
373 373 params += (n,)
374 374 elif unique:
375 375 sqlform += " ORDER BY session, line"
376 376 cur = self._run_sql(sqlform, params, raw=raw, output=output)
377 377 if n is not None:
378 378 return reversed(list(cur))
379 379 return cur
380 380
381 381 @catch_corrupt_db
382 382 def get_range(self, session, start=1, stop=None, raw=True,output=False):
383 383 """Retrieve input by session.
384 384
385 385 Parameters
386 386 ----------
387 387 session : int
388 388 Session number to retrieve.
389 389 start : int
390 390 First line to retrieve.
391 391 stop : int
392 392 End of line range (excluded from output itself). If None, retrieve
393 393 to the end of the session.
394 394 raw : bool
395 395 If True, return untranslated input
396 396 output : bool
397 397 If True, attempt to include output. This will be 'real' Python
398 398 objects for the current session, or text reprs from previous
399 399 sessions if db_log_output was enabled at the time. Where no output
400 400 is found, None is used.
401 401
402 402 Returns
403 403 -------
404 404 entries
405 405 An iterator over the desired lines. Each line is a 3-tuple, either
406 406 (session, line, input) if output is False, or
407 407 (session, line, (input, output)) if output is True.
408 408 """
409 409 if stop:
410 410 lineclause = "line >= ? AND line < ?"
411 411 params = (session, start, stop)
412 412 else:
413 413 lineclause = "line>=?"
414 414 params = (session, start)
415 415
416 416 return self._run_sql("WHERE session==? AND %s" % lineclause,
417 417 params, raw=raw, output=output)
418 418
419 419 def get_range_by_str(self, rangestr, raw=True, output=False):
420 420 """Get lines of history from a string of ranges, as used by magic
421 421 commands %hist, %save, %macro, etc.
422 422
423 423 Parameters
424 424 ----------
425 425 rangestr : str
426 426 A string specifying ranges, e.g. "5 ~2/1-4". See
427 427 :func:`magic_history` for full details.
428 428 raw, output : bool
429 429 As :meth:`get_range`
430 430
431 431 Returns
432 432 -------
433 433 Tuples as :meth:`get_range`
434 434 """
435 435 for sess, s, e in extract_hist_ranges(rangestr):
436 436 for line in self.get_range(sess, s, e, raw=raw, output=output):
437 437 yield line
438 438
439 439
440 440 class HistoryManager(HistoryAccessor):
441 441 """A class to organize all history-related functionality in one place.
442 442 """
443 443 # Public interface
444 444
445 445 # An instance of the IPython shell we are attached to
446 446 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
447 447 allow_none=True)
448 448 # Lists to hold processed and raw history. These start with a blank entry
449 449 # so that we can index them starting from 1
450 450 input_hist_parsed = List([""])
451 451 input_hist_raw = List([""])
452 452 # A list of directories visited during session
453 453 dir_hist = List()
454 454 def _dir_hist_default(self):
455 455 try:
456 456 return [py3compat.getcwd()]
457 457 except OSError:
458 458 return []
459 459
460 460 # A dict of output history, keyed with ints from the shell's
461 461 # execution count.
462 462 output_hist = Dict()
463 463 # The text/plain repr of outputs.
464 464 output_hist_reprs = Dict()
465 465
466 466 # The number of the current session in the history database
467 467 session_number = Integer()
468 468
469 469 db_log_output = Bool(False, config=True,
470 470 help="Should the history database include output? (default: no)"
471 471 )
472 472 db_cache_size = Integer(0, config=True,
473 473 help="Write to database every x commands (higher values save disk access & power).\n"
474 474 "Values of 1 or less effectively disable caching."
475 475 )
476 476 # The input and output caches
477 477 db_input_cache = List()
478 478 db_output_cache = List()
479 479
480 480 # History saving in separate thread
481 481 save_thread = Instance('IPython.core.history.HistorySavingThread',
482 482 allow_none=True)
483 483 try: # Event is a function returning an instance of _Event...
484 484 save_flag = Instance(threading._Event, allow_none=True)
485 485 except AttributeError: # ...until Python 3.3, when it's a class.
486 486 save_flag = Instance(threading.Event, allow_none=True)
487 487
488 488 # Private interface
489 489 # Variables used to store the three last inputs from the user. On each new
490 490 # history update, we populate the user's namespace with these, shifted as
491 491 # necessary.
492 492 _i00 = Unicode(u'')
493 493 _i = Unicode(u'')
494 494 _ii = Unicode(u'')
495 495 _iii = Unicode(u'')
496 496
497 497 # A regex matching all forms of the exit command, so that we don't store
498 498 # them in the history (it's annoying to rewind the first entry and land on
499 499 # an exit call).
500 500 _exit_re = re.compile(r"(exit|quit)(\s*\(.*\))?$")
501 501
502 502 def __init__(self, shell=None, config=None, **traits):
503 503 """Create a new history manager associated with a shell instance.
504 504 """
505 505 # We need a pointer back to the shell for various tasks.
506 506 super(HistoryManager, self).__init__(shell=shell, config=config,
507 507 **traits)
508 508 self.save_flag = threading.Event()
509 509 self.db_input_cache_lock = threading.Lock()
510 510 self.db_output_cache_lock = threading.Lock()
511 511 if self.enabled and self.hist_file != ':memory:':
512 512 self.save_thread = HistorySavingThread(self)
513 513 self.save_thread.start()
514 514
515 515 self.new_session()
516 516
517 517 def _get_hist_file_name(self, profile=None):
518 518 """Get default history file name based on the Shell's profile.
519 519
520 520 The profile parameter is ignored, but must exist for compatibility with
521 521 the parent class."""
522 522 profile_dir = self.shell.profile_dir.location
523 523 return os.path.join(profile_dir, 'history.sqlite')
524 524
525 525 @needs_sqlite
526 526 def new_session(self, conn=None):
527 527 """Get a new session number."""
528 528 if conn is None:
529 529 conn = self.db
530 530
531 531 with conn:
532 532 cur = conn.execute("""INSERT INTO sessions VALUES (NULL, ?, NULL,
533 533 NULL, "") """, (datetime.datetime.now(),))
534 534 self.session_number = cur.lastrowid
535 535
536 536 def end_session(self):
537 537 """Close the database session, filling in the end time and line count."""
538 538 self.writeout_cache()
539 539 with self.db:
540 540 self.db.execute("""UPDATE sessions SET end=?, num_cmds=? WHERE
541 541 session==?""", (datetime.datetime.now(),
542 542 len(self.input_hist_parsed)-1, self.session_number))
543 543 self.session_number = 0
544 544
545 545 def name_session(self, name):
546 546 """Give the current session a name in the history database."""
547 547 with self.db:
548 548 self.db.execute("UPDATE sessions SET remark=? WHERE session==?",
549 549 (name, self.session_number))
550 550
551 551 def reset(self, new_session=True):
552 552 """Clear the session history, releasing all object references, and
553 553 optionally open a new session."""
554 554 self.output_hist.clear()
555 555 # The directory history can't be completely empty
556 556 self.dir_hist[:] = [py3compat.getcwd()]
557 557
558 558 if new_session:
559 559 if self.session_number:
560 560 self.end_session()
561 561 self.input_hist_parsed[:] = [""]
562 562 self.input_hist_raw[:] = [""]
563 563 self.new_session()
564 564
565 565 # ------------------------------
566 566 # Methods for retrieving history
567 567 # ------------------------------
568 568 def get_session_info(self, session=0):
569 569 """Get info about a session.
570 570
571 571 Parameters
572 572 ----------
573 573
574 574 session : int
575 575 Session number to retrieve. The current session is 0, and negative
576 576 numbers count back from current session, so -1 is the previous session.
577 577
578 578 Returns
579 579 -------
580 580
581 581 session_id : int
582 582 Session ID number
583 583 start : datetime
584 584 Timestamp for the start of the session.
585 585 end : datetime
586 586 Timestamp for the end of the session, or None if IPython crashed.
587 587 num_cmds : int
588 588 Number of commands run, or None if IPython crashed.
589 589 remark : unicode
590 590 A manually set description.
591 591 """
592 592 if session <= 0:
593 593 session += self.session_number
594 594
595 595 return super(HistoryManager, self).get_session_info(session=session)
596 596
597 597 def _get_range_session(self, start=1, stop=None, raw=True, output=False):
598 598 """Get input and output history from the current session. Called by
599 599 get_range, and takes similar parameters."""
600 600 input_hist = self.input_hist_raw if raw else self.input_hist_parsed
601 601
602 602 n = len(input_hist)
603 603 if start < 0:
604 604 start += n
605 605 if not stop or (stop > n):
606 606 stop = n
607 607 elif stop < 0:
608 608 stop += n
609 609
610 610 for i in range(start, stop):
611 611 if output:
612 612 line = (input_hist[i], self.output_hist_reprs.get(i))
613 613 else:
614 614 line = input_hist[i]
615 615 yield (0, i, line)
616 616
617 617 def get_range(self, session=0, start=1, stop=None, raw=True,output=False):
618 618 """Retrieve input by session.
619 619
620 620 Parameters
621 621 ----------
622 622 session : int
623 623 Session number to retrieve. The current session is 0, and negative
624 624 numbers count back from current session, so -1 is previous session.
625 625 start : int
626 626 First line to retrieve.
627 627 stop : int
628 628 End of line range (excluded from output itself). If None, retrieve
629 629 to the end of the session.
630 630 raw : bool
631 631 If True, return untranslated input
632 632 output : bool
633 633 If True, attempt to include output. This will be 'real' Python
634 634 objects for the current session, or text reprs from previous
635 635 sessions if db_log_output was enabled at the time. Where no output
636 636 is found, None is used.
637 637
638 638 Returns
639 639 -------
640 640 entries
641 641 An iterator over the desired lines. Each line is a 3-tuple, either
642 642 (session, line, input) if output is False, or
643 643 (session, line, (input, output)) if output is True.
644 644 """
645 645 if session <= 0:
646 646 session += self.session_number
647 647 if session==self.session_number: # Current session
648 648 return self._get_range_session(start, stop, raw, output)
649 649 return super(HistoryManager, self).get_range(session, start, stop, raw,
650 650 output)
651 651
652 652 ## ----------------------------
653 653 ## Methods for storing history:
654 654 ## ----------------------------
655 655 def store_inputs(self, line_num, source, source_raw=None):
656 656 """Store source and raw input in history and create input cache
657 657 variables ``_i*``.
658 658
659 659 Parameters
660 660 ----------
661 661 line_num : int
662 662 The prompt number of this input.
663 663
664 664 source : str
665 665 Python input.
666 666
667 667 source_raw : str, optional
668 668 If given, this is the raw input without any IPython transformations
669 669 applied to it. If not given, ``source`` is used.
670 670 """
671 671 if source_raw is None:
672 672 source_raw = source
673 673 source = source.rstrip('\n')
674 674 source_raw = source_raw.rstrip('\n')
675 675
676 676 # do not store exit/quit commands
677 677 if self._exit_re.match(source_raw.strip()):
678 678 return
679 679
680 680 self.input_hist_parsed.append(source)
681 681 self.input_hist_raw.append(source_raw)
682 682
683 683 with self.db_input_cache_lock:
684 684 self.db_input_cache.append((line_num, source, source_raw))
685 685 # Trigger to flush cache and write to DB.
686 686 if len(self.db_input_cache) >= self.db_cache_size:
687 687 self.save_flag.set()
688 688
689 689 # update the auto _i variables
690 690 self._iii = self._ii
691 691 self._ii = self._i
692 692 self._i = self._i00
693 693 self._i00 = source_raw
694 694
695 695 # hackish access to user namespace to create _i1,_i2... dynamically
696 696 new_i = '_i%s' % line_num
697 697 to_main = {'_i': self._i,
698 698 '_ii': self._ii,
699 699 '_iii': self._iii,
700 700 new_i : self._i00 }
701 701
702 702 if self.shell is not None:
703 703 self.shell.push(to_main, interactive=False)
704 704
705 705 def store_output(self, line_num):
706 706 """If database output logging is enabled, this saves all the
707 707 outputs from the indicated prompt number to the database. It's
708 708 called by run_cell after code has been executed.
709 709
710 710 Parameters
711 711 ----------
712 712 line_num : int
713 713 The line number from which to save outputs
714 714 """
715 715 if (not self.db_log_output) or (line_num not in self.output_hist_reprs):
716 716 return
717 717 output = self.output_hist_reprs[line_num]
718 718
719 719 with self.db_output_cache_lock:
720 720 self.db_output_cache.append((line_num, output))
721 721 if self.db_cache_size <= 1:
722 722 self.save_flag.set()
723 723
724 724 def _writeout_input_cache(self, conn):
725 725 with conn:
726 726 for line in self.db_input_cache:
727 727 conn.execute("INSERT INTO history VALUES (?, ?, ?, ?)",
728 728 (self.session_number,)+line)
729 729
730 730 def _writeout_output_cache(self, conn):
731 731 with conn:
732 732 for line in self.db_output_cache:
733 733 conn.execute("INSERT INTO output_history VALUES (?, ?, ?)",
734 734 (self.session_number,)+line)
735 735
736 736 @needs_sqlite
737 737 def writeout_cache(self, conn=None):
738 738 """Write any entries in the cache to the database."""
739 739 if conn is None:
740 740 conn = self.db
741 741
742 742 with self.db_input_cache_lock:
743 743 try:
744 744 self._writeout_input_cache(conn)
745 745 except sqlite3.IntegrityError:
746 746 self.new_session(conn)
747 747 print("ERROR! Session/line number was not unique in",
748 748 "database. History logging moved to new session",
749 749 self.session_number)
750 750 try:
751 751 # Try writing to the new session. If this fails, don't
752 752 # recurse
753 753 self._writeout_input_cache(conn)
754 754 except sqlite3.IntegrityError:
755 755 pass
756 756 finally:
757 757 self.db_input_cache = []
758 758
759 759 with self.db_output_cache_lock:
760 760 try:
761 761 self._writeout_output_cache(conn)
762 762 except sqlite3.IntegrityError:
763 763 print("!! Session/line number for output was not unique",
764 764 "in database. Output will not be stored.")
765 765 finally:
766 766 self.db_output_cache = []
767 767
768 768
769 769 class HistorySavingThread(threading.Thread):
770 770 """This thread takes care of writing history to the database, so that
771 771 the UI isn't held up while that happens.
772 772
773 773 It waits for the HistoryManager's save_flag to be set, then writes out
774 774 the history cache. The main thread is responsible for setting the flag when
775 775 the cache size reaches a defined threshold."""
776 776 daemon = True
777 777 stop_now = False
778 778 enabled = True
779 779 def __init__(self, history_manager):
780 780 super(HistorySavingThread, self).__init__(name="IPythonHistorySavingThread")
781 781 self.history_manager = history_manager
782 782 self.enabled = history_manager.enabled
783 783 atexit.register(self.stop)
784 784
785 785 @needs_sqlite
786 786 def run(self):
787 787 # We need a separate db connection per thread:
788 788 try:
789 789 self.db = sqlite3.connect(self.history_manager.hist_file,
790 790 **self.history_manager.connection_options
791 791 )
792 792 while True:
793 793 self.history_manager.save_flag.wait()
794 794 if self.stop_now:
795 795 self.db.close()
796 796 return
797 797 self.history_manager.save_flag.clear()
798 798 self.history_manager.writeout_cache(self.db)
799 799 except Exception as e:
800 800 print(("The history saving thread hit an unexpected error (%s)."
801 801 "History will not be written to the database.") % repr(e))
802 802
803 803 def stop(self):
804 804 """This can be called from the main thread to safely stop this thread.
805 805
806 806 Note that it does not attempt to write out remaining history before
807 807 exiting. That should be done by calling the HistoryManager's
808 808 end_session method."""
809 809 self.stop_now = True
810 810 self.history_manager.save_flag.set()
811 811 self.join()
812 812
813 813
814 814 # To match, e.g. ~5/8-~2/3
815 815 range_re = re.compile(r"""
816 816 ((?P<startsess>~?\d+)/)?
817 817 (?P<start>\d+)?
818 818 ((?P<sep>[\-:])
819 819 ((?P<endsess>~?\d+)/)?
820 820 (?P<end>\d+))?
821 821 $""", re.VERBOSE)
822 822
823 823
824 824 def extract_hist_ranges(ranges_str):
825 825 """Turn a string of history ranges into 3-tuples of (session, start, stop).
826 826
827 827 Examples
828 828 --------
829 829 >>> list(extract_hist_ranges("~8/5-~7/4 2"))
830 830 [(-8, 5, None), (-7, 1, 5), (0, 2, 3)]
831 831 """
832 832 for range_str in ranges_str.split():
833 833 rmatch = range_re.match(range_str)
834 834 if not rmatch:
835 835 continue
836 836 start = rmatch.group("start")
837 837 if start:
838 838 start = int(start)
839 839 end = rmatch.group("end")
840 840 # If no end specified, get (a, a + 1)
841 841 end = int(end) if end else start + 1
842 842 else: # start not specified
843 843 if not rmatch.group('startsess'): # no startsess
844 844 continue
845 845 start = 1
846 846 end = None # provide the entire session hist
847 847
848 848 if rmatch.group("sep") == "-": # 1-3 == 1:4 --> [1, 2, 3]
849 849 end += 1
850 850 startsess = rmatch.group("startsess") or "0"
851 851 endsess = rmatch.group("endsess") or startsess
852 852 startsess = int(startsess.replace("~","-"))
853 853 endsess = int(endsess.replace("~","-"))
854 854 assert endsess >= startsess, "start session must be earlier than end session"
855 855
856 856 if endsess == startsess:
857 857 yield (startsess, start, end)
858 858 continue
859 859 # Multiple sessions in one range:
860 860 yield (startsess, start, None)
861 861 for sess in range(startsess+1, endsess):
862 862 yield (sess, 1, None)
863 863 yield (endsess, 1, end)
864 864
865 865
866 866 def _format_lineno(session, line):
867 867 """Helper function to format line numbers properly."""
868 868 if session == 0:
869 869 return str(line)
870 870 return "%s#%s" % (session, line)
871 871
872 872
@@ -1,159 +1,159 b''
1 1 # encoding: utf-8
2 2 """
3 3 An application for managing IPython history.
4 4
5 5 To be invoked as the `ipython history` subcommand.
6 6 """
7 7 from __future__ import print_function
8 8
9 9 import os
10 10 import sqlite3
11 11
12 from IPython.config.application import Application
12 from traitlets.config.application import Application
13 13 from IPython.core.application import BaseIPythonApplication
14 from IPython.utils.traitlets import Bool, Int, Dict
14 from traitlets import Bool, Int, Dict
15 15 from IPython.utils.io import ask_yes_no
16 16
17 17 trim_hist_help = """Trim the IPython history database to the last 1000 entries.
18 18
19 19 This actually copies the last 1000 entries to a new database, and then replaces
20 20 the old file with the new. Use the `--keep=` argument to specify a number
21 21 other than 1000.
22 22 """
23 23
24 24 clear_hist_help = """Clear the IPython history database, deleting all entries.
25 25
26 26 Because this is a destructive operation, IPython will prompt the user if they
27 27 really want to do this. Passing a `-f` flag will force clearing without a
28 28 prompt.
29 29
30 30 This is an handy alias to `ipython history trim --keep=0`
31 31 """
32 32
33 33
34 34 class HistoryTrim(BaseIPythonApplication):
35 35 description = trim_hist_help
36 36
37 37 backup = Bool(False, config=True,
38 38 help="Keep the old history file as history.sqlite.<N>")
39 39
40 40 keep = Int(1000, config=True,
41 41 help="Number of recent lines to keep in the database.")
42 42
43 43 flags = Dict(dict(
44 44 backup = ({'HistoryTrim' : {'backup' : True}},
45 45 backup.get_metadata('help')
46 46 )
47 47 ))
48 48
49 49 aliases=Dict(dict(
50 50 keep = 'HistoryTrim.keep'
51 51 ))
52 52
53 53 def start(self):
54 54 profile_dir = self.profile_dir.location
55 55 hist_file = os.path.join(profile_dir, 'history.sqlite')
56 56 con = sqlite3.connect(hist_file)
57 57
58 58 # Grab the recent history from the current database.
59 59 inputs = list(con.execute('SELECT session, line, source, source_raw FROM '
60 60 'history ORDER BY session DESC, line DESC LIMIT ?', (self.keep+1,)))
61 61 if len(inputs) <= self.keep:
62 62 print("There are already at most %d entries in the history database." % self.keep)
63 63 print("Not doing anything. Use --keep= argument to keep fewer entries")
64 64 return
65 65
66 66 print("Trimming history to the most recent %d entries." % self.keep)
67 67
68 68 inputs.pop() # Remove the extra element we got to check the length.
69 69 inputs.reverse()
70 70 if inputs:
71 71 first_session = inputs[0][0]
72 72 outputs = list(con.execute('SELECT session, line, output FROM '
73 73 'output_history WHERE session >= ?', (first_session,)))
74 74 sessions = list(con.execute('SELECT session, start, end, num_cmds, remark FROM '
75 75 'sessions WHERE session >= ?', (first_session,)))
76 76 con.close()
77 77
78 78 # Create the new history database.
79 79 new_hist_file = os.path.join(profile_dir, 'history.sqlite.new')
80 80 i = 0
81 81 while os.path.exists(new_hist_file):
82 82 # Make sure we don't interfere with an existing file.
83 83 i += 1
84 84 new_hist_file = os.path.join(profile_dir, 'history.sqlite.new'+str(i))
85 85 new_db = sqlite3.connect(new_hist_file)
86 86 new_db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer
87 87 primary key autoincrement, start timestamp,
88 88 end timestamp, num_cmds integer, remark text)""")
89 89 new_db.execute("""CREATE TABLE IF NOT EXISTS history
90 90 (session integer, line integer, source text, source_raw text,
91 91 PRIMARY KEY (session, line))""")
92 92 new_db.execute("""CREATE TABLE IF NOT EXISTS output_history
93 93 (session integer, line integer, output text,
94 94 PRIMARY KEY (session, line))""")
95 95 new_db.commit()
96 96
97 97
98 98 if inputs:
99 99 with new_db:
100 100 # Add the recent history into the new database.
101 101 new_db.executemany('insert into sessions values (?,?,?,?,?)', sessions)
102 102 new_db.executemany('insert into history values (?,?,?,?)', inputs)
103 103 new_db.executemany('insert into output_history values (?,?,?)', outputs)
104 104 new_db.close()
105 105
106 106 if self.backup:
107 107 i = 1
108 108 backup_hist_file = os.path.join(profile_dir, 'history.sqlite.old.%d' % i)
109 109 while os.path.exists(backup_hist_file):
110 110 i += 1
111 111 backup_hist_file = os.path.join(profile_dir, 'history.sqlite.old.%d' % i)
112 112 os.rename(hist_file, backup_hist_file)
113 113 print("Backed up longer history file to", backup_hist_file)
114 114 else:
115 115 os.remove(hist_file)
116 116
117 117 os.rename(new_hist_file, hist_file)
118 118
119 119 class HistoryClear(HistoryTrim):
120 120 description = clear_hist_help
121 121 keep = Int(0, config=False,
122 122 help="Number of recent lines to keep in the database.")
123 123
124 124 force = Bool(False, config=True,
125 125 help="Don't prompt user for confirmation")
126 126
127 127 flags = Dict(dict(
128 128 force = ({'HistoryClear' : {'force' : True}},
129 129 force.get_metadata('help')),
130 130 f = ({'HistoryTrim' : {'force' : True}},
131 131 force.get_metadata('help')
132 132 )
133 133 ))
134 134 aliases = Dict()
135 135
136 136 def start(self):
137 137 if self.force or ask_yes_no("Really delete all ipython history? ",
138 138 default="no", interrupt="no"):
139 139 HistoryTrim.start(self)
140 140
141 141 class HistoryApp(Application):
142 142 name = u'ipython-history'
143 143 description = "Manage the IPython history database."
144 144
145 145 subcommands = Dict(dict(
146 146 trim = (HistoryTrim, HistoryTrim.description.splitlines()[0]),
147 147 clear = (HistoryClear, HistoryClear.description.splitlines()[0]),
148 148 ))
149 149
150 150 def start(self):
151 151 if self.subapp is None:
152 152 print("No subcommand specified. Must specify one of: %s" % \
153 153 (self.subcommands.keys()))
154 154 print()
155 155 self.print_description()
156 156 self.print_subcommands()
157 157 self.exit(1)
158 158 else:
159 159 return self.subapp.start()
@@ -1,3392 +1,3393 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Main IPython class."""
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 7 # Copyright (C) 2008-2011 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 from __future__ import absolute_import, print_function
14 14
15 15 import __future__
16 16 import abc
17 17 import ast
18 18 import atexit
19 19 import functools
20 20 import os
21 21 import re
22 22 import runpy
23 23 import sys
24 24 import tempfile
25 25 import traceback
26 26 import types
27 27 import subprocess
28 28 from io import open as io_open
29 29
30 30 from pickleshare import PickleShareDB
31 31
32 from IPython.config.configurable import SingletonConfigurable
32 from traitlets.config.configurable import SingletonConfigurable
33 33 from IPython.core import debugger, oinspect
34 34 from IPython.core import magic
35 35 from IPython.core import page
36 36 from IPython.core import prefilter
37 37 from IPython.core import shadowns
38 38 from IPython.core import ultratb
39 39 from IPython.core.alias import Alias, AliasManager
40 40 from IPython.core.autocall import ExitAutocall
41 41 from IPython.core.builtin_trap import BuiltinTrap
42 42 from IPython.core.events import EventManager, available_events
43 43 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
44 44 from IPython.core.display_trap import DisplayTrap
45 45 from IPython.core.displayhook import DisplayHook
46 46 from IPython.core.displaypub import DisplayPublisher
47 47 from IPython.core.error import InputRejected, UsageError
48 48 from IPython.core.extensions import ExtensionManager
49 49 from IPython.core.formatters import DisplayFormatter
50 50 from IPython.core.history import HistoryManager
51 51 from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC, ESC_MAGIC2
52 52 from IPython.core.logger import Logger
53 53 from IPython.core.macro import Macro
54 54 from IPython.core.payload import PayloadManager
55 55 from IPython.core.prefilter import PrefilterManager
56 56 from IPython.core.profiledir import ProfileDir
57 57 from IPython.core.prompts import PromptManager
58 58 from IPython.core.usage import default_banner
59 59 from IPython.testing.skipdoctest import skip_doctest
60 60 from IPython.utils import PyColorize
61 61 from IPython.utils import io
62 62 from IPython.utils import py3compat
63 63 from IPython.utils import openpy
64 64 from IPython.utils.decorators import undoc
65 65 from IPython.utils.io import ask_yes_no
66 66 from IPython.utils.ipstruct import Struct
67 from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename, ensure_dir_exists
67 from IPython.paths import get_ipython_dir
68 from IPython.utils.path import get_home_dir, get_py_filename, unquote_filename, ensure_dir_exists
68 69 from IPython.utils.process import system, getoutput
69 70 from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
70 71 with_metaclass, iteritems)
71 72 from IPython.utils.strdispatch import StrDispatch
72 73 from IPython.utils.syspathcontext import prepended_to_syspath
73 74 from IPython.utils.text import (format_screen, LSString, SList,
74 75 DollarFormatter)
75 from IPython.utils.traitlets import (Integer, Bool, CBool, CaselessStrEnum, Enum,
76 from traitlets import (Integer, Bool, CBool, CaselessStrEnum, Enum,
76 77 List, Dict, Unicode, Instance, Type)
77 78 from IPython.utils.warn import warn, error
78 79 import IPython.core.hooks
79 80
80 81 #-----------------------------------------------------------------------------
81 82 # Globals
82 83 #-----------------------------------------------------------------------------
83 84
84 85 # compiled regexps for autoindent management
85 86 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
86 87
87 88 #-----------------------------------------------------------------------------
88 89 # Utilities
89 90 #-----------------------------------------------------------------------------
90 91
91 92 @undoc
92 93 def softspace(file, newvalue):
93 94 """Copied from code.py, to remove the dependency"""
94 95
95 96 oldvalue = 0
96 97 try:
97 98 oldvalue = file.softspace
98 99 except AttributeError:
99 100 pass
100 101 try:
101 102 file.softspace = newvalue
102 103 except (AttributeError, TypeError):
103 104 # "attribute-less object" or "read-only attributes"
104 105 pass
105 106 return oldvalue
106 107
107 108 @undoc
108 109 def no_op(*a, **kw): pass
109 110
110 111 @undoc
111 112 class NoOpContext(object):
112 113 def __enter__(self): pass
113 114 def __exit__(self, type, value, traceback): pass
114 115 no_op_context = NoOpContext()
115 116
116 117 class SpaceInInput(Exception): pass
117 118
118 119 @undoc
119 120 class Bunch: pass
120 121
121 122
122 123 def get_default_colors():
123 124 if sys.platform=='darwin':
124 125 return "LightBG"
125 126 elif os.name=='nt':
126 127 return 'Linux'
127 128 else:
128 129 return 'Linux'
129 130
130 131
131 132 class SeparateUnicode(Unicode):
132 133 r"""A Unicode subclass to validate separate_in, separate_out, etc.
133 134
134 135 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
135 136 """
136 137
137 138 def validate(self, obj, value):
138 139 if value == '0': value = ''
139 140 value = value.replace('\\n','\n')
140 141 return super(SeparateUnicode, self).validate(obj, value)
141 142
142 143
143 144 class ReadlineNoRecord(object):
144 145 """Context manager to execute some code, then reload readline history
145 146 so that interactive input to the code doesn't appear when pressing up."""
146 147 def __init__(self, shell):
147 148 self.shell = shell
148 149 self._nested_level = 0
149 150
150 151 def __enter__(self):
151 152 if self._nested_level == 0:
152 153 try:
153 154 self.orig_length = self.current_length()
154 155 self.readline_tail = self.get_readline_tail()
155 156 except (AttributeError, IndexError): # Can fail with pyreadline
156 157 self.orig_length, self.readline_tail = 999999, []
157 158 self._nested_level += 1
158 159
159 160 def __exit__(self, type, value, traceback):
160 161 self._nested_level -= 1
161 162 if self._nested_level == 0:
162 163 # Try clipping the end if it's got longer
163 164 try:
164 165 e = self.current_length() - self.orig_length
165 166 if e > 0:
166 167 for _ in range(e):
167 168 self.shell.readline.remove_history_item(self.orig_length)
168 169
169 170 # If it still doesn't match, just reload readline history.
170 171 if self.current_length() != self.orig_length \
171 172 or self.get_readline_tail() != self.readline_tail:
172 173 self.shell.refill_readline_hist()
173 174 except (AttributeError, IndexError):
174 175 pass
175 176 # Returning False will cause exceptions to propagate
176 177 return False
177 178
178 179 def current_length(self):
179 180 return self.shell.readline.get_current_history_length()
180 181
181 182 def get_readline_tail(self, n=10):
182 183 """Get the last n items in readline history."""
183 184 end = self.shell.readline.get_current_history_length() + 1
184 185 start = max(end-n, 1)
185 186 ghi = self.shell.readline.get_history_item
186 187 return [ghi(x) for x in range(start, end)]
187 188
188 189
189 190 @undoc
190 191 class DummyMod(object):
191 192 """A dummy module used for IPython's interactive module when
192 193 a namespace must be assigned to the module's __dict__."""
193 194 pass
194 195
195 196
196 197 class ExecutionResult(object):
197 198 """The result of a call to :meth:`InteractiveShell.run_cell`
198 199
199 200 Stores information about what took place.
200 201 """
201 202 execution_count = None
202 203 error_before_exec = None
203 204 error_in_exec = None
204 205 result = None
205 206
206 207 @property
207 208 def success(self):
208 209 return (self.error_before_exec is None) and (self.error_in_exec is None)
209 210
210 211
211 212 class InteractiveShell(SingletonConfigurable):
212 213 """An enhanced, interactive shell for Python."""
213 214
214 215 _instance = None
215 216
216 217 ast_transformers = List([], config=True, help=
217 218 """
218 219 A list of ast.NodeTransformer subclass instances, which will be applied
219 220 to user input before code is run.
220 221 """
221 222 )
222 223
223 224 autocall = Enum((0,1,2), default_value=0, config=True, help=
224 225 """
225 226 Make IPython automatically call any callable object even if you didn't
226 227 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
227 228 automatically. The value can be '0' to disable the feature, '1' for
228 229 'smart' autocall, where it is not applied if there are no more
229 230 arguments on the line, and '2' for 'full' autocall, where all callable
230 231 objects are automatically called (even if no arguments are present).
231 232 """
232 233 )
233 234 # TODO: remove all autoindent logic and put into frontends.
234 235 # We can't do this yet because even runlines uses the autoindent.
235 236 autoindent = CBool(True, config=True, help=
236 237 """
237 238 Autoindent IPython code entered interactively.
238 239 """
239 240 )
240 241 automagic = CBool(True, config=True, help=
241 242 """
242 243 Enable magic commands to be called without the leading %.
243 244 """
244 245 )
245 246
246 247 banner1 = Unicode(default_banner, config=True,
247 248 help="""The part of the banner to be printed before the profile"""
248 249 )
249 250 banner2 = Unicode('', config=True,
250 251 help="""The part of the banner to be printed after the profile"""
251 252 )
252 253
253 254 cache_size = Integer(1000, config=True, help=
254 255 """
255 256 Set the size of the output cache. The default is 1000, you can
256 257 change it permanently in your config file. Setting it to 0 completely
257 258 disables the caching system, and the minimum value accepted is 20 (if
258 259 you provide a value less than 20, it is reset to 0 and a warning is
259 260 issued). This limit is defined because otherwise you'll spend more
260 261 time re-flushing a too small cache than working
261 262 """
262 263 )
263 264 color_info = CBool(True, config=True, help=
264 265 """
265 266 Use colors for displaying information about objects. Because this
266 267 information is passed through a pager (like 'less'), and some pagers
267 268 get confused with color codes, this capability can be turned off.
268 269 """
269 270 )
270 271 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
271 272 default_value=get_default_colors(), config=True,
272 273 help="Set the color scheme (NoColor, Linux, or LightBG)."
273 274 )
274 275 colors_force = CBool(False, help=
275 276 """
276 277 Force use of ANSI color codes, regardless of OS and readline
277 278 availability.
278 279 """
279 280 # FIXME: This is essentially a hack to allow ZMQShell to show colors
280 281 # without readline on Win32. When the ZMQ formatting system is
281 282 # refactored, this should be removed.
282 283 )
283 284 debug = CBool(False, config=True)
284 285 deep_reload = CBool(False, config=True, help=
285 286 """
286 287 Enable deep (recursive) reloading by default. IPython can use the
287 288 deep_reload module which reloads changes in modules recursively (it
288 289 replaces the reload() function, so you don't need to change anything to
289 290 use it). deep_reload() forces a full reload of modules whose code may
290 291 have changed, which the default reload() function does not. When
291 292 deep_reload is off, IPython will use the normal reload(), but
292 293 deep_reload will still be available as dreload().
293 294 """
294 295 )
295 296 disable_failing_post_execute = CBool(False, config=True,
296 297 help="Don't call post-execute functions that have failed in the past."
297 298 )
298 299 display_formatter = Instance(DisplayFormatter, allow_none=True)
299 300 displayhook_class = Type(DisplayHook)
300 301 display_pub_class = Type(DisplayPublisher)
301 302 data_pub_class = None
302 303
303 304 exit_now = CBool(False)
304 305 exiter = Instance(ExitAutocall)
305 306 def _exiter_default(self):
306 307 return ExitAutocall(self)
307 308 # Monotonically increasing execution counter
308 309 execution_count = Integer(1)
309 310 filename = Unicode("<ipython console>")
310 311 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
311 312
312 313 # Input splitter, to transform input line by line and detect when a block
313 314 # is ready to be executed.
314 315 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
315 316 (), {'line_input_checker': True})
316 317
317 318 # This InputSplitter instance is used to transform completed cells before
318 319 # running them. It allows cell magics to contain blank lines.
319 320 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
320 321 (), {'line_input_checker': False})
321 322
322 323 logstart = CBool(False, config=True, help=
323 324 """
324 325 Start logging to the default log file in overwrite mode.
325 326 Use `logappend` to specify a log file to **append** logs to.
326 327 """
327 328 )
328 329 logfile = Unicode('', config=True, help=
329 330 """
330 331 The name of the logfile to use.
331 332 """
332 333 )
333 334 logappend = Unicode('', config=True, help=
334 335 """
335 336 Start logging to the given file in append mode.
336 337 Use `logfile` to specify a log file to **overwrite** logs to.
337 338 """
338 339 )
339 340 object_info_string_level = Enum((0,1,2), default_value=0,
340 341 config=True)
341 342 pdb = CBool(False, config=True, help=
342 343 """
343 344 Automatically call the pdb debugger after every exception.
344 345 """
345 346 )
346 347 multiline_history = CBool(sys.platform != 'win32', config=True,
347 348 help="Save multi-line entries as one entry in readline history"
348 349 )
349 350 display_page = Bool(False, config=True,
350 351 help="""If True, anything that would be passed to the pager
351 352 will be displayed as regular output instead."""
352 353 )
353 354
354 355 # deprecated prompt traits:
355 356
356 357 prompt_in1 = Unicode('In [\\#]: ', config=True,
357 358 help="Deprecated, use PromptManager.in_template")
358 359 prompt_in2 = Unicode(' .\\D.: ', config=True,
359 360 help="Deprecated, use PromptManager.in2_template")
360 361 prompt_out = Unicode('Out[\\#]: ', config=True,
361 362 help="Deprecated, use PromptManager.out_template")
362 363 prompts_pad_left = CBool(True, config=True,
363 364 help="Deprecated, use PromptManager.justify")
364 365
365 366 def _prompt_trait_changed(self, name, old, new):
366 367 table = {
367 368 'prompt_in1' : 'in_template',
368 369 'prompt_in2' : 'in2_template',
369 370 'prompt_out' : 'out_template',
370 371 'prompts_pad_left' : 'justify',
371 372 }
372 373 warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}".format(
373 374 name=name, newname=table[name])
374 375 )
375 376 # protect against weird cases where self.config may not exist:
376 377 if self.config is not None:
377 378 # propagate to corresponding PromptManager trait
378 379 setattr(self.config.PromptManager, table[name], new)
379 380
380 381 _prompt_in1_changed = _prompt_trait_changed
381 382 _prompt_in2_changed = _prompt_trait_changed
382 383 _prompt_out_changed = _prompt_trait_changed
383 384 _prompt_pad_left_changed = _prompt_trait_changed
384 385
385 386 show_rewritten_input = CBool(True, config=True,
386 387 help="Show rewritten input, e.g. for autocall."
387 388 )
388 389
389 390 quiet = CBool(False, config=True)
390 391
391 392 history_length = Integer(10000, config=True)
392 393
393 394 # The readline stuff will eventually be moved to the terminal subclass
394 395 # but for now, we can't do that as readline is welded in everywhere.
395 396 readline_use = CBool(True, config=True)
396 397 readline_remove_delims = Unicode('-/~', config=True)
397 398 readline_delims = Unicode() # set by init_readline()
398 399 # don't use \M- bindings by default, because they
399 400 # conflict with 8-bit encodings. See gh-58,gh-88
400 401 readline_parse_and_bind = List([
401 402 'tab: complete',
402 403 '"\C-l": clear-screen',
403 404 'set show-all-if-ambiguous on',
404 405 '"\C-o": tab-insert',
405 406 '"\C-r": reverse-search-history',
406 407 '"\C-s": forward-search-history',
407 408 '"\C-p": history-search-backward',
408 409 '"\C-n": history-search-forward',
409 410 '"\e[A": history-search-backward',
410 411 '"\e[B": history-search-forward',
411 412 '"\C-k": kill-line',
412 413 '"\C-u": unix-line-discard',
413 414 ], config=True)
414 415
415 416 _custom_readline_config = False
416 417
417 418 def _readline_parse_and_bind_changed(self, name, old, new):
418 419 # notice that readline config is customized
419 420 # indicates that it should have higher priority than inputrc
420 421 self._custom_readline_config = True
421 422
422 423 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
423 424 default_value='last_expr', config=True,
424 425 help="""
425 426 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
426 427 run interactively (displaying output from expressions).""")
427 428
428 429 # TODO: this part of prompt management should be moved to the frontends.
429 430 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
430 431 separate_in = SeparateUnicode('\n', config=True)
431 432 separate_out = SeparateUnicode('', config=True)
432 433 separate_out2 = SeparateUnicode('', config=True)
433 434 wildcards_case_sensitive = CBool(True, config=True)
434 435 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
435 436 default_value='Context', config=True)
436 437
437 438 # Subcomponents of InteractiveShell
438 439 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
439 440 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
440 441 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
441 442 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
442 443 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
443 444 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
444 445 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
445 446 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
446 447
447 448 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
448 449 @property
449 450 def profile(self):
450 451 if self.profile_dir is not None:
451 452 name = os.path.basename(self.profile_dir.location)
452 453 return name.replace('profile_','')
453 454
454 455
455 456 # Private interface
456 457 _post_execute = Dict()
457 458
458 459 # Tracks any GUI loop loaded for pylab
459 460 pylab_gui_select = None
460 461
461 462 def __init__(self, ipython_dir=None, profile_dir=None,
462 463 user_module=None, user_ns=None,
463 464 custom_exceptions=((), None), **kwargs):
464 465
465 466 # This is where traits with a config_key argument are updated
466 467 # from the values on config.
467 468 super(InteractiveShell, self).__init__(**kwargs)
468 469 self.configurables = [self]
469 470
470 471 # These are relatively independent and stateless
471 472 self.init_ipython_dir(ipython_dir)
472 473 self.init_profile_dir(profile_dir)
473 474 self.init_instance_attrs()
474 475 self.init_environment()
475 476
476 477 # Check if we're in a virtualenv, and set up sys.path.
477 478 self.init_virtualenv()
478 479
479 480 # Create namespaces (user_ns, user_global_ns, etc.)
480 481 self.init_create_namespaces(user_module, user_ns)
481 482 # This has to be done after init_create_namespaces because it uses
482 483 # something in self.user_ns, but before init_sys_modules, which
483 484 # is the first thing to modify sys.
484 485 # TODO: When we override sys.stdout and sys.stderr before this class
485 486 # is created, we are saving the overridden ones here. Not sure if this
486 487 # is what we want to do.
487 488 self.save_sys_module_state()
488 489 self.init_sys_modules()
489 490
490 491 # While we're trying to have each part of the code directly access what
491 492 # it needs without keeping redundant references to objects, we have too
492 493 # much legacy code that expects ip.db to exist.
493 494 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
494 495
495 496 self.init_history()
496 497 self.init_encoding()
497 498 self.init_prefilter()
498 499
499 500 self.init_syntax_highlighting()
500 501 self.init_hooks()
501 502 self.init_events()
502 503 self.init_pushd_popd_magic()
503 504 # self.init_traceback_handlers use to be here, but we moved it below
504 505 # because it and init_io have to come after init_readline.
505 506 self.init_user_ns()
506 507 self.init_logger()
507 508 self.init_builtins()
508 509
509 510 # The following was in post_config_initialization
510 511 self.init_inspector()
511 512 # init_readline() must come before init_io(), because init_io uses
512 513 # readline related things.
513 514 self.init_readline()
514 515 # We save this here in case user code replaces raw_input, but it needs
515 516 # to be after init_readline(), because PyPy's readline works by replacing
516 517 # raw_input.
517 518 if py3compat.PY3:
518 519 self.raw_input_original = input
519 520 else:
520 521 self.raw_input_original = raw_input
521 522 # init_completer must come after init_readline, because it needs to
522 523 # know whether readline is present or not system-wide to configure the
523 524 # completers, since the completion machinery can now operate
524 525 # independently of readline (e.g. over the network)
525 526 self.init_completer()
526 527 # TODO: init_io() needs to happen before init_traceback handlers
527 528 # because the traceback handlers hardcode the stdout/stderr streams.
528 529 # This logic in in debugger.Pdb and should eventually be changed.
529 530 self.init_io()
530 531 self.init_traceback_handlers(custom_exceptions)
531 532 self.init_prompts()
532 533 self.init_display_formatter()
533 534 self.init_display_pub()
534 535 self.init_data_pub()
535 536 self.init_displayhook()
536 537 self.init_magics()
537 538 self.init_alias()
538 539 self.init_logstart()
539 540 self.init_pdb()
540 541 self.init_extension_manager()
541 542 self.init_payload()
542 543 self.hooks.late_startup_hook()
543 544 self.events.trigger('shell_initialized', self)
544 545 atexit.register(self.atexit_operations)
545 546
546 547 def get_ipython(self):
547 548 """Return the currently running IPython instance."""
548 549 return self
549 550
550 551 #-------------------------------------------------------------------------
551 552 # Trait changed handlers
552 553 #-------------------------------------------------------------------------
553 554
554 555 def _ipython_dir_changed(self, name, new):
555 556 ensure_dir_exists(new)
556 557
557 558 def set_autoindent(self,value=None):
558 559 """Set the autoindent flag, checking for readline support.
559 560
560 561 If called with no arguments, it acts as a toggle."""
561 562
562 563 if value != 0 and not self.has_readline:
563 564 if os.name == 'posix':
564 565 warn("The auto-indent feature requires the readline library")
565 566 self.autoindent = 0
566 567 return
567 568 if value is None:
568 569 self.autoindent = not self.autoindent
569 570 else:
570 571 self.autoindent = value
571 572
572 573 #-------------------------------------------------------------------------
573 574 # init_* methods called by __init__
574 575 #-------------------------------------------------------------------------
575 576
576 577 def init_ipython_dir(self, ipython_dir):
577 578 if ipython_dir is not None:
578 579 self.ipython_dir = ipython_dir
579 580 return
580 581
581 582 self.ipython_dir = get_ipython_dir()
582 583
583 584 def init_profile_dir(self, profile_dir):
584 585 if profile_dir is not None:
585 586 self.profile_dir = profile_dir
586 587 return
587 588 self.profile_dir =\
588 589 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
589 590
590 591 def init_instance_attrs(self):
591 592 self.more = False
592 593
593 594 # command compiler
594 595 self.compile = CachingCompiler()
595 596
596 597 # Make an empty namespace, which extension writers can rely on both
597 598 # existing and NEVER being used by ipython itself. This gives them a
598 599 # convenient location for storing additional information and state
599 600 # their extensions may require, without fear of collisions with other
600 601 # ipython names that may develop later.
601 602 self.meta = Struct()
602 603
603 604 # Temporary files used for various purposes. Deleted at exit.
604 605 self.tempfiles = []
605 606 self.tempdirs = []
606 607
607 608 # Keep track of readline usage (later set by init_readline)
608 609 self.has_readline = False
609 610
610 611 # keep track of where we started running (mainly for crash post-mortem)
611 612 # This is not being used anywhere currently.
612 613 self.starting_dir = py3compat.getcwd()
613 614
614 615 # Indentation management
615 616 self.indent_current_nsp = 0
616 617
617 618 # Dict to track post-execution functions that have been registered
618 619 self._post_execute = {}
619 620
620 621 def init_environment(self):
621 622 """Any changes we need to make to the user's environment."""
622 623 pass
623 624
624 625 def init_encoding(self):
625 626 # Get system encoding at startup time. Certain terminals (like Emacs
626 627 # under Win32 have it set to None, and we need to have a known valid
627 628 # encoding to use in the raw_input() method
628 629 try:
629 630 self.stdin_encoding = sys.stdin.encoding or 'ascii'
630 631 except AttributeError:
631 632 self.stdin_encoding = 'ascii'
632 633
633 634 def init_syntax_highlighting(self):
634 635 # Python source parser/formatter for syntax highlighting
635 636 pyformat = PyColorize.Parser().format
636 637 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
637 638
638 639 def init_pushd_popd_magic(self):
639 640 # for pushd/popd management
640 641 self.home_dir = get_home_dir()
641 642
642 643 self.dir_stack = []
643 644
644 645 def init_logger(self):
645 646 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
646 647 logmode='rotate')
647 648
648 649 def init_logstart(self):
649 650 """Initialize logging in case it was requested at the command line.
650 651 """
651 652 if self.logappend:
652 653 self.magic('logstart %s append' % self.logappend)
653 654 elif self.logfile:
654 655 self.magic('logstart %s' % self.logfile)
655 656 elif self.logstart:
656 657 self.magic('logstart')
657 658
658 659 def init_builtins(self):
659 660 # A single, static flag that we set to True. Its presence indicates
660 661 # that an IPython shell has been created, and we make no attempts at
661 662 # removing on exit or representing the existence of more than one
662 663 # IPython at a time.
663 664 builtin_mod.__dict__['__IPYTHON__'] = True
664 665
665 666 # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to
666 667 # manage on enter/exit, but with all our shells it's virtually
667 668 # impossible to get all the cases right. We're leaving the name in for
668 669 # those who adapted their codes to check for this flag, but will
669 670 # eventually remove it after a few more releases.
670 671 builtin_mod.__dict__['__IPYTHON__active'] = \
671 672 'Deprecated, check for __IPYTHON__'
672 673
673 674 self.builtin_trap = BuiltinTrap(shell=self)
674 675
675 676 def init_inspector(self):
676 677 # Object inspector
677 678 self.inspector = oinspect.Inspector(oinspect.InspectColors,
678 679 PyColorize.ANSICodeColors,
679 680 'NoColor',
680 681 self.object_info_string_level)
681 682
682 683 def init_io(self):
683 684 # This will just use sys.stdout and sys.stderr. If you want to
684 685 # override sys.stdout and sys.stderr themselves, you need to do that
685 686 # *before* instantiating this class, because io holds onto
686 687 # references to the underlying streams.
687 688 if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline:
688 689 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
689 690 else:
690 691 io.stdout = io.IOStream(sys.stdout)
691 692 io.stderr = io.IOStream(sys.stderr)
692 693
693 694 def init_prompts(self):
694 695 self.prompt_manager = PromptManager(shell=self, parent=self)
695 696 self.configurables.append(self.prompt_manager)
696 697 # Set system prompts, so that scripts can decide if they are running
697 698 # interactively.
698 699 sys.ps1 = 'In : '
699 700 sys.ps2 = '...: '
700 701 sys.ps3 = 'Out: '
701 702
702 703 def init_display_formatter(self):
703 704 self.display_formatter = DisplayFormatter(parent=self)
704 705 self.configurables.append(self.display_formatter)
705 706
706 707 def init_display_pub(self):
707 708 self.display_pub = self.display_pub_class(parent=self)
708 709 self.configurables.append(self.display_pub)
709 710
710 711 def init_data_pub(self):
711 712 if not self.data_pub_class:
712 713 self.data_pub = None
713 714 return
714 715 self.data_pub = self.data_pub_class(parent=self)
715 716 self.configurables.append(self.data_pub)
716 717
717 718 def init_displayhook(self):
718 719 # Initialize displayhook, set in/out prompts and printing system
719 720 self.displayhook = self.displayhook_class(
720 721 parent=self,
721 722 shell=self,
722 723 cache_size=self.cache_size,
723 724 )
724 725 self.configurables.append(self.displayhook)
725 726 # This is a context manager that installs/revmoes the displayhook at
726 727 # the appropriate time.
727 728 self.display_trap = DisplayTrap(hook=self.displayhook)
728 729
729 730 def init_virtualenv(self):
730 731 """Add a virtualenv to sys.path so the user can import modules from it.
731 732 This isn't perfect: it doesn't use the Python interpreter with which the
732 733 virtualenv was built, and it ignores the --no-site-packages option. A
733 734 warning will appear suggesting the user installs IPython in the
734 735 virtualenv, but for many cases, it probably works well enough.
735 736
736 737 Adapted from code snippets online.
737 738
738 739 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
739 740 """
740 741 if 'VIRTUAL_ENV' not in os.environ:
741 742 # Not in a virtualenv
742 743 return
743 744
744 745 # venv detection:
745 746 # stdlib venv may symlink sys.executable, so we can't use realpath.
746 747 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
747 748 # So we just check every item in the symlink tree (generally <= 3)
748 749 p = os.path.normcase(sys.executable)
749 750 paths = [p]
750 751 while os.path.islink(p):
751 752 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
752 753 paths.append(p)
753 754 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
754 755 if any(p.startswith(p_venv) for p in paths):
755 756 # Running properly in the virtualenv, don't need to do anything
756 757 return
757 758
758 759 warn("Attempting to work in a virtualenv. If you encounter problems, please "
759 760 "install IPython inside the virtualenv.")
760 761 if sys.platform == "win32":
761 762 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
762 763 else:
763 764 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
764 765 'python%d.%d' % sys.version_info[:2], 'site-packages')
765 766
766 767 import site
767 768 sys.path.insert(0, virtual_env)
768 769 site.addsitedir(virtual_env)
769 770
770 771 #-------------------------------------------------------------------------
771 772 # Things related to injections into the sys module
772 773 #-------------------------------------------------------------------------
773 774
774 775 def save_sys_module_state(self):
775 776 """Save the state of hooks in the sys module.
776 777
777 778 This has to be called after self.user_module is created.
778 779 """
779 780 self._orig_sys_module_state = {}
780 781 self._orig_sys_module_state['stdin'] = sys.stdin
781 782 self._orig_sys_module_state['stdout'] = sys.stdout
782 783 self._orig_sys_module_state['stderr'] = sys.stderr
783 784 self._orig_sys_module_state['excepthook'] = sys.excepthook
784 785 self._orig_sys_modules_main_name = self.user_module.__name__
785 786 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
786 787
787 788 def restore_sys_module_state(self):
788 789 """Restore the state of the sys module."""
789 790 try:
790 791 for k, v in iteritems(self._orig_sys_module_state):
791 792 setattr(sys, k, v)
792 793 except AttributeError:
793 794 pass
794 795 # Reset what what done in self.init_sys_modules
795 796 if self._orig_sys_modules_main_mod is not None:
796 797 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
797 798
798 799 #-------------------------------------------------------------------------
799 800 # Things related to the banner
800 801 #-------------------------------------------------------------------------
801 802
802 803 @property
803 804 def banner(self):
804 805 banner = self.banner1
805 806 if self.profile and self.profile != 'default':
806 807 banner += '\nIPython profile: %s\n' % self.profile
807 808 if self.banner2:
808 809 banner += '\n' + self.banner2
809 810 return banner
810 811
811 812 def show_banner(self, banner=None):
812 813 if banner is None:
813 814 banner = self.banner
814 815 self.write(banner)
815 816
816 817 #-------------------------------------------------------------------------
817 818 # Things related to hooks
818 819 #-------------------------------------------------------------------------
819 820
820 821 def init_hooks(self):
821 822 # hooks holds pointers used for user-side customizations
822 823 self.hooks = Struct()
823 824
824 825 self.strdispatchers = {}
825 826
826 827 # Set all default hooks, defined in the IPython.hooks module.
827 828 hooks = IPython.core.hooks
828 829 for hook_name in hooks.__all__:
829 830 # default hooks have priority 100, i.e. low; user hooks should have
830 831 # 0-100 priority
831 832 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
832 833
833 834 if self.display_page:
834 835 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
835 836
836 837 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
837 838 _warn_deprecated=True):
838 839 """set_hook(name,hook) -> sets an internal IPython hook.
839 840
840 841 IPython exposes some of its internal API as user-modifiable hooks. By
841 842 adding your function to one of these hooks, you can modify IPython's
842 843 behavior to call at runtime your own routines."""
843 844
844 845 # At some point in the future, this should validate the hook before it
845 846 # accepts it. Probably at least check that the hook takes the number
846 847 # of args it's supposed to.
847 848
848 849 f = types.MethodType(hook,self)
849 850
850 851 # check if the hook is for strdispatcher first
851 852 if str_key is not None:
852 853 sdp = self.strdispatchers.get(name, StrDispatch())
853 854 sdp.add_s(str_key, f, priority )
854 855 self.strdispatchers[name] = sdp
855 856 return
856 857 if re_key is not None:
857 858 sdp = self.strdispatchers.get(name, StrDispatch())
858 859 sdp.add_re(re.compile(re_key), f, priority )
859 860 self.strdispatchers[name] = sdp
860 861 return
861 862
862 863 dp = getattr(self.hooks, name, None)
863 864 if name not in IPython.core.hooks.__all__:
864 865 print("Warning! Hook '%s' is not one of %s" % \
865 866 (name, IPython.core.hooks.__all__ ))
866 867
867 868 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
868 869 alternative = IPython.core.hooks.deprecated[name]
869 870 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative))
870 871
871 872 if not dp:
872 873 dp = IPython.core.hooks.CommandChainDispatcher()
873 874
874 875 try:
875 876 dp.add(f,priority)
876 877 except AttributeError:
877 878 # it was not commandchain, plain old func - replace
878 879 dp = f
879 880
880 881 setattr(self.hooks,name, dp)
881 882
882 883 #-------------------------------------------------------------------------
883 884 # Things related to events
884 885 #-------------------------------------------------------------------------
885 886
886 887 def init_events(self):
887 888 self.events = EventManager(self, available_events)
888 889
889 890 self.events.register("pre_execute", self._clear_warning_registry)
890 891
891 892 def register_post_execute(self, func):
892 893 """DEPRECATED: Use ip.events.register('post_run_cell', func)
893 894
894 895 Register a function for calling after code execution.
895 896 """
896 897 warn("ip.register_post_execute is deprecated, use "
897 898 "ip.events.register('post_run_cell', func) instead.")
898 899 self.events.register('post_run_cell', func)
899 900
900 901 def _clear_warning_registry(self):
901 902 # clear the warning registry, so that different code blocks with
902 903 # overlapping line number ranges don't cause spurious suppression of
903 904 # warnings (see gh-6611 for details)
904 905 if "__warningregistry__" in self.user_global_ns:
905 906 del self.user_global_ns["__warningregistry__"]
906 907
907 908 #-------------------------------------------------------------------------
908 909 # Things related to the "main" module
909 910 #-------------------------------------------------------------------------
910 911
911 912 def new_main_mod(self, filename, modname):
912 913 """Return a new 'main' module object for user code execution.
913 914
914 915 ``filename`` should be the path of the script which will be run in the
915 916 module. Requests with the same filename will get the same module, with
916 917 its namespace cleared.
917 918
918 919 ``modname`` should be the module name - normally either '__main__' or
919 920 the basename of the file without the extension.
920 921
921 922 When scripts are executed via %run, we must keep a reference to their
922 923 __main__ module around so that Python doesn't
923 924 clear it, rendering references to module globals useless.
924 925
925 926 This method keeps said reference in a private dict, keyed by the
926 927 absolute path of the script. This way, for multiple executions of the
927 928 same script we only keep one copy of the namespace (the last one),
928 929 thus preventing memory leaks from old references while allowing the
929 930 objects from the last execution to be accessible.
930 931 """
931 932 filename = os.path.abspath(filename)
932 933 try:
933 934 main_mod = self._main_mod_cache[filename]
934 935 except KeyError:
935 936 main_mod = self._main_mod_cache[filename] = types.ModuleType(
936 937 py3compat.cast_bytes_py2(modname),
937 938 doc="Module created for script run in IPython")
938 939 else:
939 940 main_mod.__dict__.clear()
940 941 main_mod.__name__ = modname
941 942
942 943 main_mod.__file__ = filename
943 944 # It seems pydoc (and perhaps others) needs any module instance to
944 945 # implement a __nonzero__ method
945 946 main_mod.__nonzero__ = lambda : True
946 947
947 948 return main_mod
948 949
949 950 def clear_main_mod_cache(self):
950 951 """Clear the cache of main modules.
951 952
952 953 Mainly for use by utilities like %reset.
953 954
954 955 Examples
955 956 --------
956 957
957 958 In [15]: import IPython
958 959
959 960 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
960 961
961 962 In [17]: len(_ip._main_mod_cache) > 0
962 963 Out[17]: True
963 964
964 965 In [18]: _ip.clear_main_mod_cache()
965 966
966 967 In [19]: len(_ip._main_mod_cache) == 0
967 968 Out[19]: True
968 969 """
969 970 self._main_mod_cache.clear()
970 971
971 972 #-------------------------------------------------------------------------
972 973 # Things related to debugging
973 974 #-------------------------------------------------------------------------
974 975
975 976 def init_pdb(self):
976 977 # Set calling of pdb on exceptions
977 978 # self.call_pdb is a property
978 979 self.call_pdb = self.pdb
979 980
980 981 def _get_call_pdb(self):
981 982 return self._call_pdb
982 983
983 984 def _set_call_pdb(self,val):
984 985
985 986 if val not in (0,1,False,True):
986 987 raise ValueError('new call_pdb value must be boolean')
987 988
988 989 # store value in instance
989 990 self._call_pdb = val
990 991
991 992 # notify the actual exception handlers
992 993 self.InteractiveTB.call_pdb = val
993 994
994 995 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
995 996 'Control auto-activation of pdb at exceptions')
996 997
997 998 def debugger(self,force=False):
998 999 """Call the pydb/pdb debugger.
999 1000
1000 1001 Keywords:
1001 1002
1002 1003 - force(False): by default, this routine checks the instance call_pdb
1003 1004 flag and does not actually invoke the debugger if the flag is false.
1004 1005 The 'force' option forces the debugger to activate even if the flag
1005 1006 is false.
1006 1007 """
1007 1008
1008 1009 if not (force or self.call_pdb):
1009 1010 return
1010 1011
1011 1012 if not hasattr(sys,'last_traceback'):
1012 1013 error('No traceback has been produced, nothing to debug.')
1013 1014 return
1014 1015
1015 1016 # use pydb if available
1016 1017 if debugger.has_pydb:
1017 1018 from pydb import pm
1018 1019 else:
1019 1020 # fallback to our internal debugger
1020 1021 pm = lambda : self.InteractiveTB.debugger(force=True)
1021 1022
1022 1023 with self.readline_no_record:
1023 1024 pm()
1024 1025
1025 1026 #-------------------------------------------------------------------------
1026 1027 # Things related to IPython's various namespaces
1027 1028 #-------------------------------------------------------------------------
1028 1029 default_user_namespaces = True
1029 1030
1030 1031 def init_create_namespaces(self, user_module=None, user_ns=None):
1031 1032 # Create the namespace where the user will operate. user_ns is
1032 1033 # normally the only one used, and it is passed to the exec calls as
1033 1034 # the locals argument. But we do carry a user_global_ns namespace
1034 1035 # given as the exec 'globals' argument, This is useful in embedding
1035 1036 # situations where the ipython shell opens in a context where the
1036 1037 # distinction between locals and globals is meaningful. For
1037 1038 # non-embedded contexts, it is just the same object as the user_ns dict.
1038 1039
1039 1040 # FIXME. For some strange reason, __builtins__ is showing up at user
1040 1041 # level as a dict instead of a module. This is a manual fix, but I
1041 1042 # should really track down where the problem is coming from. Alex
1042 1043 # Schmolck reported this problem first.
1043 1044
1044 1045 # A useful post by Alex Martelli on this topic:
1045 1046 # Re: inconsistent value from __builtins__
1046 1047 # Von: Alex Martelli <aleaxit@yahoo.com>
1047 1048 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1048 1049 # Gruppen: comp.lang.python
1049 1050
1050 1051 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1051 1052 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1052 1053 # > <type 'dict'>
1053 1054 # > >>> print type(__builtins__)
1054 1055 # > <type 'module'>
1055 1056 # > Is this difference in return value intentional?
1056 1057
1057 1058 # Well, it's documented that '__builtins__' can be either a dictionary
1058 1059 # or a module, and it's been that way for a long time. Whether it's
1059 1060 # intentional (or sensible), I don't know. In any case, the idea is
1060 1061 # that if you need to access the built-in namespace directly, you
1061 1062 # should start with "import __builtin__" (note, no 's') which will
1062 1063 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1063 1064
1064 1065 # These routines return a properly built module and dict as needed by
1065 1066 # the rest of the code, and can also be used by extension writers to
1066 1067 # generate properly initialized namespaces.
1067 1068 if (user_ns is not None) or (user_module is not None):
1068 1069 self.default_user_namespaces = False
1069 1070 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1070 1071
1071 1072 # A record of hidden variables we have added to the user namespace, so
1072 1073 # we can list later only variables defined in actual interactive use.
1073 1074 self.user_ns_hidden = {}
1074 1075
1075 1076 # Now that FakeModule produces a real module, we've run into a nasty
1076 1077 # problem: after script execution (via %run), the module where the user
1077 1078 # code ran is deleted. Now that this object is a true module (needed
1078 1079 # so docetst and other tools work correctly), the Python module
1079 1080 # teardown mechanism runs over it, and sets to None every variable
1080 1081 # present in that module. Top-level references to objects from the
1081 1082 # script survive, because the user_ns is updated with them. However,
1082 1083 # calling functions defined in the script that use other things from
1083 1084 # the script will fail, because the function's closure had references
1084 1085 # to the original objects, which are now all None. So we must protect
1085 1086 # these modules from deletion by keeping a cache.
1086 1087 #
1087 1088 # To avoid keeping stale modules around (we only need the one from the
1088 1089 # last run), we use a dict keyed with the full path to the script, so
1089 1090 # only the last version of the module is held in the cache. Note,
1090 1091 # however, that we must cache the module *namespace contents* (their
1091 1092 # __dict__). Because if we try to cache the actual modules, old ones
1092 1093 # (uncached) could be destroyed while still holding references (such as
1093 1094 # those held by GUI objects that tend to be long-lived)>
1094 1095 #
1095 1096 # The %reset command will flush this cache. See the cache_main_mod()
1096 1097 # and clear_main_mod_cache() methods for details on use.
1097 1098
1098 1099 # This is the cache used for 'main' namespaces
1099 1100 self._main_mod_cache = {}
1100 1101
1101 1102 # A table holding all the namespaces IPython deals with, so that
1102 1103 # introspection facilities can search easily.
1103 1104 self.ns_table = {'user_global':self.user_module.__dict__,
1104 1105 'user_local':self.user_ns,
1105 1106 'builtin':builtin_mod.__dict__
1106 1107 }
1107 1108
1108 1109 @property
1109 1110 def user_global_ns(self):
1110 1111 return self.user_module.__dict__
1111 1112
1112 1113 def prepare_user_module(self, user_module=None, user_ns=None):
1113 1114 """Prepare the module and namespace in which user code will be run.
1114 1115
1115 1116 When IPython is started normally, both parameters are None: a new module
1116 1117 is created automatically, and its __dict__ used as the namespace.
1117 1118
1118 1119 If only user_module is provided, its __dict__ is used as the namespace.
1119 1120 If only user_ns is provided, a dummy module is created, and user_ns
1120 1121 becomes the global namespace. If both are provided (as they may be
1121 1122 when embedding), user_ns is the local namespace, and user_module
1122 1123 provides the global namespace.
1123 1124
1124 1125 Parameters
1125 1126 ----------
1126 1127 user_module : module, optional
1127 1128 The current user module in which IPython is being run. If None,
1128 1129 a clean module will be created.
1129 1130 user_ns : dict, optional
1130 1131 A namespace in which to run interactive commands.
1131 1132
1132 1133 Returns
1133 1134 -------
1134 1135 A tuple of user_module and user_ns, each properly initialised.
1135 1136 """
1136 1137 if user_module is None and user_ns is not None:
1137 1138 user_ns.setdefault("__name__", "__main__")
1138 1139 user_module = DummyMod()
1139 1140 user_module.__dict__ = user_ns
1140 1141
1141 1142 if user_module is None:
1142 1143 user_module = types.ModuleType("__main__",
1143 1144 doc="Automatically created module for IPython interactive environment")
1144 1145
1145 1146 # We must ensure that __builtin__ (without the final 's') is always
1146 1147 # available and pointing to the __builtin__ *module*. For more details:
1147 1148 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1148 1149 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1149 1150 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1150 1151
1151 1152 if user_ns is None:
1152 1153 user_ns = user_module.__dict__
1153 1154
1154 1155 return user_module, user_ns
1155 1156
1156 1157 def init_sys_modules(self):
1157 1158 # We need to insert into sys.modules something that looks like a
1158 1159 # module but which accesses the IPython namespace, for shelve and
1159 1160 # pickle to work interactively. Normally they rely on getting
1160 1161 # everything out of __main__, but for embedding purposes each IPython
1161 1162 # instance has its own private namespace, so we can't go shoving
1162 1163 # everything into __main__.
1163 1164
1164 1165 # note, however, that we should only do this for non-embedded
1165 1166 # ipythons, which really mimic the __main__.__dict__ with their own
1166 1167 # namespace. Embedded instances, on the other hand, should not do
1167 1168 # this because they need to manage the user local/global namespaces
1168 1169 # only, but they live within a 'normal' __main__ (meaning, they
1169 1170 # shouldn't overtake the execution environment of the script they're
1170 1171 # embedded in).
1171 1172
1172 1173 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1173 1174 main_name = self.user_module.__name__
1174 1175 sys.modules[main_name] = self.user_module
1175 1176
1176 1177 def init_user_ns(self):
1177 1178 """Initialize all user-visible namespaces to their minimum defaults.
1178 1179
1179 1180 Certain history lists are also initialized here, as they effectively
1180 1181 act as user namespaces.
1181 1182
1182 1183 Notes
1183 1184 -----
1184 1185 All data structures here are only filled in, they are NOT reset by this
1185 1186 method. If they were not empty before, data will simply be added to
1186 1187 therm.
1187 1188 """
1188 1189 # This function works in two parts: first we put a few things in
1189 1190 # user_ns, and we sync that contents into user_ns_hidden so that these
1190 1191 # initial variables aren't shown by %who. After the sync, we add the
1191 1192 # rest of what we *do* want the user to see with %who even on a new
1192 1193 # session (probably nothing, so theye really only see their own stuff)
1193 1194
1194 1195 # The user dict must *always* have a __builtin__ reference to the
1195 1196 # Python standard __builtin__ namespace, which must be imported.
1196 1197 # This is so that certain operations in prompt evaluation can be
1197 1198 # reliably executed with builtins. Note that we can NOT use
1198 1199 # __builtins__ (note the 's'), because that can either be a dict or a
1199 1200 # module, and can even mutate at runtime, depending on the context
1200 1201 # (Python makes no guarantees on it). In contrast, __builtin__ is
1201 1202 # always a module object, though it must be explicitly imported.
1202 1203
1203 1204 # For more details:
1204 1205 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1205 1206 ns = dict()
1206 1207
1207 1208 # make global variables for user access to the histories
1208 1209 ns['_ih'] = self.history_manager.input_hist_parsed
1209 1210 ns['_oh'] = self.history_manager.output_hist
1210 1211 ns['_dh'] = self.history_manager.dir_hist
1211 1212
1212 1213 ns['_sh'] = shadowns
1213 1214
1214 1215 # user aliases to input and output histories. These shouldn't show up
1215 1216 # in %who, as they can have very large reprs.
1216 1217 ns['In'] = self.history_manager.input_hist_parsed
1217 1218 ns['Out'] = self.history_manager.output_hist
1218 1219
1219 1220 # Store myself as the public api!!!
1220 1221 ns['get_ipython'] = self.get_ipython
1221 1222
1222 1223 ns['exit'] = self.exiter
1223 1224 ns['quit'] = self.exiter
1224 1225
1225 1226 # Sync what we've added so far to user_ns_hidden so these aren't seen
1226 1227 # by %who
1227 1228 self.user_ns_hidden.update(ns)
1228 1229
1229 1230 # Anything put into ns now would show up in %who. Think twice before
1230 1231 # putting anything here, as we really want %who to show the user their
1231 1232 # stuff, not our variables.
1232 1233
1233 1234 # Finally, update the real user's namespace
1234 1235 self.user_ns.update(ns)
1235 1236
1236 1237 @property
1237 1238 def all_ns_refs(self):
1238 1239 """Get a list of references to all the namespace dictionaries in which
1239 1240 IPython might store a user-created object.
1240 1241
1241 1242 Note that this does not include the displayhook, which also caches
1242 1243 objects from the output."""
1243 1244 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1244 1245 [m.__dict__ for m in self._main_mod_cache.values()]
1245 1246
1246 1247 def reset(self, new_session=True):
1247 1248 """Clear all internal namespaces, and attempt to release references to
1248 1249 user objects.
1249 1250
1250 1251 If new_session is True, a new history session will be opened.
1251 1252 """
1252 1253 # Clear histories
1253 1254 self.history_manager.reset(new_session)
1254 1255 # Reset counter used to index all histories
1255 1256 if new_session:
1256 1257 self.execution_count = 1
1257 1258
1258 1259 # Flush cached output items
1259 1260 if self.displayhook.do_full_cache:
1260 1261 self.displayhook.flush()
1261 1262
1262 1263 # The main execution namespaces must be cleared very carefully,
1263 1264 # skipping the deletion of the builtin-related keys, because doing so
1264 1265 # would cause errors in many object's __del__ methods.
1265 1266 if self.user_ns is not self.user_global_ns:
1266 1267 self.user_ns.clear()
1267 1268 ns = self.user_global_ns
1268 1269 drop_keys = set(ns.keys())
1269 1270 drop_keys.discard('__builtin__')
1270 1271 drop_keys.discard('__builtins__')
1271 1272 drop_keys.discard('__name__')
1272 1273 for k in drop_keys:
1273 1274 del ns[k]
1274 1275
1275 1276 self.user_ns_hidden.clear()
1276 1277
1277 1278 # Restore the user namespaces to minimal usability
1278 1279 self.init_user_ns()
1279 1280
1280 1281 # Restore the default and user aliases
1281 1282 self.alias_manager.clear_aliases()
1282 1283 self.alias_manager.init_aliases()
1283 1284
1284 1285 # Flush the private list of module references kept for script
1285 1286 # execution protection
1286 1287 self.clear_main_mod_cache()
1287 1288
1288 1289 def del_var(self, varname, by_name=False):
1289 1290 """Delete a variable from the various namespaces, so that, as
1290 1291 far as possible, we're not keeping any hidden references to it.
1291 1292
1292 1293 Parameters
1293 1294 ----------
1294 1295 varname : str
1295 1296 The name of the variable to delete.
1296 1297 by_name : bool
1297 1298 If True, delete variables with the given name in each
1298 1299 namespace. If False (default), find the variable in the user
1299 1300 namespace, and delete references to it.
1300 1301 """
1301 1302 if varname in ('__builtin__', '__builtins__'):
1302 1303 raise ValueError("Refusing to delete %s" % varname)
1303 1304
1304 1305 ns_refs = self.all_ns_refs
1305 1306
1306 1307 if by_name: # Delete by name
1307 1308 for ns in ns_refs:
1308 1309 try:
1309 1310 del ns[varname]
1310 1311 except KeyError:
1311 1312 pass
1312 1313 else: # Delete by object
1313 1314 try:
1314 1315 obj = self.user_ns[varname]
1315 1316 except KeyError:
1316 1317 raise NameError("name '%s' is not defined" % varname)
1317 1318 # Also check in output history
1318 1319 ns_refs.append(self.history_manager.output_hist)
1319 1320 for ns in ns_refs:
1320 1321 to_delete = [n for n, o in iteritems(ns) if o is obj]
1321 1322 for name in to_delete:
1322 1323 del ns[name]
1323 1324
1324 1325 # displayhook keeps extra references, but not in a dictionary
1325 1326 for name in ('_', '__', '___'):
1326 1327 if getattr(self.displayhook, name) is obj:
1327 1328 setattr(self.displayhook, name, None)
1328 1329
1329 1330 def reset_selective(self, regex=None):
1330 1331 """Clear selective variables from internal namespaces based on a
1331 1332 specified regular expression.
1332 1333
1333 1334 Parameters
1334 1335 ----------
1335 1336 regex : string or compiled pattern, optional
1336 1337 A regular expression pattern that will be used in searching
1337 1338 variable names in the users namespaces.
1338 1339 """
1339 1340 if regex is not None:
1340 1341 try:
1341 1342 m = re.compile(regex)
1342 1343 except TypeError:
1343 1344 raise TypeError('regex must be a string or compiled pattern')
1344 1345 # Search for keys in each namespace that match the given regex
1345 1346 # If a match is found, delete the key/value pair.
1346 1347 for ns in self.all_ns_refs:
1347 1348 for var in ns:
1348 1349 if m.search(var):
1349 1350 del ns[var]
1350 1351
1351 1352 def push(self, variables, interactive=True):
1352 1353 """Inject a group of variables into the IPython user namespace.
1353 1354
1354 1355 Parameters
1355 1356 ----------
1356 1357 variables : dict, str or list/tuple of str
1357 1358 The variables to inject into the user's namespace. If a dict, a
1358 1359 simple update is done. If a str, the string is assumed to have
1359 1360 variable names separated by spaces. A list/tuple of str can also
1360 1361 be used to give the variable names. If just the variable names are
1361 1362 give (list/tuple/str) then the variable values looked up in the
1362 1363 callers frame.
1363 1364 interactive : bool
1364 1365 If True (default), the variables will be listed with the ``who``
1365 1366 magic.
1366 1367 """
1367 1368 vdict = None
1368 1369
1369 1370 # We need a dict of name/value pairs to do namespace updates.
1370 1371 if isinstance(variables, dict):
1371 1372 vdict = variables
1372 1373 elif isinstance(variables, string_types+(list, tuple)):
1373 1374 if isinstance(variables, string_types):
1374 1375 vlist = variables.split()
1375 1376 else:
1376 1377 vlist = variables
1377 1378 vdict = {}
1378 1379 cf = sys._getframe(1)
1379 1380 for name in vlist:
1380 1381 try:
1381 1382 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1382 1383 except:
1383 1384 print('Could not get variable %s from %s' %
1384 1385 (name,cf.f_code.co_name))
1385 1386 else:
1386 1387 raise ValueError('variables must be a dict/str/list/tuple')
1387 1388
1388 1389 # Propagate variables to user namespace
1389 1390 self.user_ns.update(vdict)
1390 1391
1391 1392 # And configure interactive visibility
1392 1393 user_ns_hidden = self.user_ns_hidden
1393 1394 if interactive:
1394 1395 for name in vdict:
1395 1396 user_ns_hidden.pop(name, None)
1396 1397 else:
1397 1398 user_ns_hidden.update(vdict)
1398 1399
1399 1400 def drop_by_id(self, variables):
1400 1401 """Remove a dict of variables from the user namespace, if they are the
1401 1402 same as the values in the dictionary.
1402 1403
1403 1404 This is intended for use by extensions: variables that they've added can
1404 1405 be taken back out if they are unloaded, without removing any that the
1405 1406 user has overwritten.
1406 1407
1407 1408 Parameters
1408 1409 ----------
1409 1410 variables : dict
1410 1411 A dictionary mapping object names (as strings) to the objects.
1411 1412 """
1412 1413 for name, obj in iteritems(variables):
1413 1414 if name in self.user_ns and self.user_ns[name] is obj:
1414 1415 del self.user_ns[name]
1415 1416 self.user_ns_hidden.pop(name, None)
1416 1417
1417 1418 #-------------------------------------------------------------------------
1418 1419 # Things related to object introspection
1419 1420 #-------------------------------------------------------------------------
1420 1421
1421 1422 def _ofind(self, oname, namespaces=None):
1422 1423 """Find an object in the available namespaces.
1423 1424
1424 1425 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1425 1426
1426 1427 Has special code to detect magic functions.
1427 1428 """
1428 1429 oname = oname.strip()
1429 1430 #print '1- oname: <%r>' % oname # dbg
1430 1431 if not oname.startswith(ESC_MAGIC) and \
1431 1432 not oname.startswith(ESC_MAGIC2) and \
1432 1433 not py3compat.isidentifier(oname, dotted=True):
1433 1434 return dict(found=False)
1434 1435
1435 1436 alias_ns = None
1436 1437 if namespaces is None:
1437 1438 # Namespaces to search in:
1438 1439 # Put them in a list. The order is important so that we
1439 1440 # find things in the same order that Python finds them.
1440 1441 namespaces = [ ('Interactive', self.user_ns),
1441 1442 ('Interactive (global)', self.user_global_ns),
1442 1443 ('Python builtin', builtin_mod.__dict__),
1443 1444 ]
1444 1445
1445 1446 # initialize results to 'null'
1446 1447 found = False; obj = None; ospace = None; ds = None;
1447 1448 ismagic = False; isalias = False; parent = None
1448 1449
1449 1450 # We need to special-case 'print', which as of python2.6 registers as a
1450 1451 # function but should only be treated as one if print_function was
1451 1452 # loaded with a future import. In this case, just bail.
1452 1453 if (oname == 'print' and not py3compat.PY3 and not \
1453 1454 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1454 1455 return {'found':found, 'obj':obj, 'namespace':ospace,
1455 1456 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1456 1457
1457 1458 # Look for the given name by splitting it in parts. If the head is
1458 1459 # found, then we look for all the remaining parts as members, and only
1459 1460 # declare success if we can find them all.
1460 1461 oname_parts = oname.split('.')
1461 1462 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1462 1463 for nsname,ns in namespaces:
1463 1464 try:
1464 1465 obj = ns[oname_head]
1465 1466 except KeyError:
1466 1467 continue
1467 1468 else:
1468 1469 #print 'oname_rest:', oname_rest # dbg
1469 1470 for idx, part in enumerate(oname_rest):
1470 1471 try:
1471 1472 parent = obj
1472 1473 # The last part is looked up in a special way to avoid
1473 1474 # descriptor invocation as it may raise or have side
1474 1475 # effects.
1475 1476 if idx == len(oname_rest) - 1:
1476 1477 obj = self._getattr_property(obj, part)
1477 1478 else:
1478 1479 obj = getattr(obj, part)
1479 1480 except:
1480 1481 # Blanket except b/c some badly implemented objects
1481 1482 # allow __getattr__ to raise exceptions other than
1482 1483 # AttributeError, which then crashes IPython.
1483 1484 break
1484 1485 else:
1485 1486 # If we finish the for loop (no break), we got all members
1486 1487 found = True
1487 1488 ospace = nsname
1488 1489 break # namespace loop
1489 1490
1490 1491 # Try to see if it's magic
1491 1492 if not found:
1492 1493 obj = None
1493 1494 if oname.startswith(ESC_MAGIC2):
1494 1495 oname = oname.lstrip(ESC_MAGIC2)
1495 1496 obj = self.find_cell_magic(oname)
1496 1497 elif oname.startswith(ESC_MAGIC):
1497 1498 oname = oname.lstrip(ESC_MAGIC)
1498 1499 obj = self.find_line_magic(oname)
1499 1500 else:
1500 1501 # search without prefix, so run? will find %run?
1501 1502 obj = self.find_line_magic(oname)
1502 1503 if obj is None:
1503 1504 obj = self.find_cell_magic(oname)
1504 1505 if obj is not None:
1505 1506 found = True
1506 1507 ospace = 'IPython internal'
1507 1508 ismagic = True
1508 1509 isalias = isinstance(obj, Alias)
1509 1510
1510 1511 # Last try: special-case some literals like '', [], {}, etc:
1511 1512 if not found and oname_head in ["''",'""','[]','{}','()']:
1512 1513 obj = eval(oname_head)
1513 1514 found = True
1514 1515 ospace = 'Interactive'
1515 1516
1516 1517 return {'found':found, 'obj':obj, 'namespace':ospace,
1517 1518 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1518 1519
1519 1520 @staticmethod
1520 1521 def _getattr_property(obj, attrname):
1521 1522 """Property-aware getattr to use in object finding.
1522 1523
1523 1524 If attrname represents a property, return it unevaluated (in case it has
1524 1525 side effects or raises an error.
1525 1526
1526 1527 """
1527 1528 if not isinstance(obj, type):
1528 1529 try:
1529 1530 # `getattr(type(obj), attrname)` is not guaranteed to return
1530 1531 # `obj`, but does so for property:
1531 1532 #
1532 1533 # property.__get__(self, None, cls) -> self
1533 1534 #
1534 1535 # The universal alternative is to traverse the mro manually
1535 1536 # searching for attrname in class dicts.
1536 1537 attr = getattr(type(obj), attrname)
1537 1538 except AttributeError:
1538 1539 pass
1539 1540 else:
1540 1541 # This relies on the fact that data descriptors (with both
1541 1542 # __get__ & __set__ magic methods) take precedence over
1542 1543 # instance-level attributes:
1543 1544 #
1544 1545 # class A(object):
1545 1546 # @property
1546 1547 # def foobar(self): return 123
1547 1548 # a = A()
1548 1549 # a.__dict__['foobar'] = 345
1549 1550 # a.foobar # == 123
1550 1551 #
1551 1552 # So, a property may be returned right away.
1552 1553 if isinstance(attr, property):
1553 1554 return attr
1554 1555
1555 1556 # Nothing helped, fall back.
1556 1557 return getattr(obj, attrname)
1557 1558
1558 1559 def _object_find(self, oname, namespaces=None):
1559 1560 """Find an object and return a struct with info about it."""
1560 1561 return Struct(self._ofind(oname, namespaces))
1561 1562
1562 1563 def _inspect(self, meth, oname, namespaces=None, **kw):
1563 1564 """Generic interface to the inspector system.
1564 1565
1565 1566 This function is meant to be called by pdef, pdoc & friends."""
1566 1567 info = self._object_find(oname, namespaces)
1567 1568 if info.found:
1568 1569 pmethod = getattr(self.inspector, meth)
1569 1570 formatter = format_screen if info.ismagic else None
1570 1571 if meth == 'pdoc':
1571 1572 pmethod(info.obj, oname, formatter)
1572 1573 elif meth == 'pinfo':
1573 1574 pmethod(info.obj, oname, formatter, info, **kw)
1574 1575 else:
1575 1576 pmethod(info.obj, oname)
1576 1577 else:
1577 1578 print('Object `%s` not found.' % oname)
1578 1579 return 'not found' # so callers can take other action
1579 1580
1580 1581 def object_inspect(self, oname, detail_level=0):
1581 1582 """Get object info about oname"""
1582 1583 with self.builtin_trap:
1583 1584 info = self._object_find(oname)
1584 1585 if info.found:
1585 1586 return self.inspector.info(info.obj, oname, info=info,
1586 1587 detail_level=detail_level
1587 1588 )
1588 1589 else:
1589 1590 return oinspect.object_info(name=oname, found=False)
1590 1591
1591 1592 def object_inspect_text(self, oname, detail_level=0):
1592 1593 """Get object info as formatted text"""
1593 1594 with self.builtin_trap:
1594 1595 info = self._object_find(oname)
1595 1596 if info.found:
1596 1597 return self.inspector._format_info(info.obj, oname, info=info,
1597 1598 detail_level=detail_level
1598 1599 )
1599 1600 else:
1600 1601 raise KeyError(oname)
1601 1602
1602 1603 #-------------------------------------------------------------------------
1603 1604 # Things related to history management
1604 1605 #-------------------------------------------------------------------------
1605 1606
1606 1607 def init_history(self):
1607 1608 """Sets up the command history, and starts regular autosaves."""
1608 1609 self.history_manager = HistoryManager(shell=self, parent=self)
1609 1610 self.configurables.append(self.history_manager)
1610 1611
1611 1612 #-------------------------------------------------------------------------
1612 1613 # Things related to exception handling and tracebacks (not debugging)
1613 1614 #-------------------------------------------------------------------------
1614 1615
1615 1616 def init_traceback_handlers(self, custom_exceptions):
1616 1617 # Syntax error handler.
1617 1618 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1618 1619
1619 1620 # The interactive one is initialized with an offset, meaning we always
1620 1621 # want to remove the topmost item in the traceback, which is our own
1621 1622 # internal code. Valid modes: ['Plain','Context','Verbose']
1622 1623 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1623 1624 color_scheme='NoColor',
1624 1625 tb_offset = 1,
1625 1626 check_cache=check_linecache_ipython)
1626 1627
1627 1628 # The instance will store a pointer to the system-wide exception hook,
1628 1629 # so that runtime code (such as magics) can access it. This is because
1629 1630 # during the read-eval loop, it may get temporarily overwritten.
1630 1631 self.sys_excepthook = sys.excepthook
1631 1632
1632 1633 # and add any custom exception handlers the user may have specified
1633 1634 self.set_custom_exc(*custom_exceptions)
1634 1635
1635 1636 # Set the exception mode
1636 1637 self.InteractiveTB.set_mode(mode=self.xmode)
1637 1638
1638 1639 def set_custom_exc(self, exc_tuple, handler):
1639 1640 """set_custom_exc(exc_tuple,handler)
1640 1641
1641 1642 Set a custom exception handler, which will be called if any of the
1642 1643 exceptions in exc_tuple occur in the mainloop (specifically, in the
1643 1644 run_code() method).
1644 1645
1645 1646 Parameters
1646 1647 ----------
1647 1648
1648 1649 exc_tuple : tuple of exception classes
1649 1650 A *tuple* of exception classes, for which to call the defined
1650 1651 handler. It is very important that you use a tuple, and NOT A
1651 1652 LIST here, because of the way Python's except statement works. If
1652 1653 you only want to trap a single exception, use a singleton tuple::
1653 1654
1654 1655 exc_tuple == (MyCustomException,)
1655 1656
1656 1657 handler : callable
1657 1658 handler must have the following signature::
1658 1659
1659 1660 def my_handler(self, etype, value, tb, tb_offset=None):
1660 1661 ...
1661 1662 return structured_traceback
1662 1663
1663 1664 Your handler must return a structured traceback (a list of strings),
1664 1665 or None.
1665 1666
1666 1667 This will be made into an instance method (via types.MethodType)
1667 1668 of IPython itself, and it will be called if any of the exceptions
1668 1669 listed in the exc_tuple are caught. If the handler is None, an
1669 1670 internal basic one is used, which just prints basic info.
1670 1671
1671 1672 To protect IPython from crashes, if your handler ever raises an
1672 1673 exception or returns an invalid result, it will be immediately
1673 1674 disabled.
1674 1675
1675 1676 WARNING: by putting in your own exception handler into IPython's main
1676 1677 execution loop, you run a very good chance of nasty crashes. This
1677 1678 facility should only be used if you really know what you are doing."""
1678 1679
1679 1680 assert type(exc_tuple)==type(()) , \
1680 1681 "The custom exceptions must be given AS A TUPLE."
1681 1682
1682 1683 def dummy_handler(self,etype,value,tb,tb_offset=None):
1683 1684 print('*** Simple custom exception handler ***')
1684 1685 print('Exception type :',etype)
1685 1686 print('Exception value:',value)
1686 1687 print('Traceback :',tb)
1687 1688 #print 'Source code :','\n'.join(self.buffer)
1688 1689
1689 1690 def validate_stb(stb):
1690 1691 """validate structured traceback return type
1691 1692
1692 1693 return type of CustomTB *should* be a list of strings, but allow
1693 1694 single strings or None, which are harmless.
1694 1695
1695 1696 This function will *always* return a list of strings,
1696 1697 and will raise a TypeError if stb is inappropriate.
1697 1698 """
1698 1699 msg = "CustomTB must return list of strings, not %r" % stb
1699 1700 if stb is None:
1700 1701 return []
1701 1702 elif isinstance(stb, string_types):
1702 1703 return [stb]
1703 1704 elif not isinstance(stb, list):
1704 1705 raise TypeError(msg)
1705 1706 # it's a list
1706 1707 for line in stb:
1707 1708 # check every element
1708 1709 if not isinstance(line, string_types):
1709 1710 raise TypeError(msg)
1710 1711 return stb
1711 1712
1712 1713 if handler is None:
1713 1714 wrapped = dummy_handler
1714 1715 else:
1715 1716 def wrapped(self,etype,value,tb,tb_offset=None):
1716 1717 """wrap CustomTB handler, to protect IPython from user code
1717 1718
1718 1719 This makes it harder (but not impossible) for custom exception
1719 1720 handlers to crash IPython.
1720 1721 """
1721 1722 try:
1722 1723 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1723 1724 return validate_stb(stb)
1724 1725 except:
1725 1726 # clear custom handler immediately
1726 1727 self.set_custom_exc((), None)
1727 1728 print("Custom TB Handler failed, unregistering", file=io.stderr)
1728 1729 # show the exception in handler first
1729 1730 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1730 1731 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1731 1732 print("The original exception:", file=io.stdout)
1732 1733 stb = self.InteractiveTB.structured_traceback(
1733 1734 (etype,value,tb), tb_offset=tb_offset
1734 1735 )
1735 1736 return stb
1736 1737
1737 1738 self.CustomTB = types.MethodType(wrapped,self)
1738 1739 self.custom_exceptions = exc_tuple
1739 1740
1740 1741 def excepthook(self, etype, value, tb):
1741 1742 """One more defense for GUI apps that call sys.excepthook.
1742 1743
1743 1744 GUI frameworks like wxPython trap exceptions and call
1744 1745 sys.excepthook themselves. I guess this is a feature that
1745 1746 enables them to keep running after exceptions that would
1746 1747 otherwise kill their mainloop. This is a bother for IPython
1747 1748 which excepts to catch all of the program exceptions with a try:
1748 1749 except: statement.
1749 1750
1750 1751 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1751 1752 any app directly invokes sys.excepthook, it will look to the user like
1752 1753 IPython crashed. In order to work around this, we can disable the
1753 1754 CrashHandler and replace it with this excepthook instead, which prints a
1754 1755 regular traceback using our InteractiveTB. In this fashion, apps which
1755 1756 call sys.excepthook will generate a regular-looking exception from
1756 1757 IPython, and the CrashHandler will only be triggered by real IPython
1757 1758 crashes.
1758 1759
1759 1760 This hook should be used sparingly, only in places which are not likely
1760 1761 to be true IPython errors.
1761 1762 """
1762 1763 self.showtraceback((etype, value, tb), tb_offset=0)
1763 1764
1764 1765 def _get_exc_info(self, exc_tuple=None):
1765 1766 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1766 1767
1767 1768 Ensures sys.last_type,value,traceback hold the exc_info we found,
1768 1769 from whichever source.
1769 1770
1770 1771 raises ValueError if none of these contain any information
1771 1772 """
1772 1773 if exc_tuple is None:
1773 1774 etype, value, tb = sys.exc_info()
1774 1775 else:
1775 1776 etype, value, tb = exc_tuple
1776 1777
1777 1778 if etype is None:
1778 1779 if hasattr(sys, 'last_type'):
1779 1780 etype, value, tb = sys.last_type, sys.last_value, \
1780 1781 sys.last_traceback
1781 1782
1782 1783 if etype is None:
1783 1784 raise ValueError("No exception to find")
1784 1785
1785 1786 # Now store the exception info in sys.last_type etc.
1786 1787 # WARNING: these variables are somewhat deprecated and not
1787 1788 # necessarily safe to use in a threaded environment, but tools
1788 1789 # like pdb depend on their existence, so let's set them. If we
1789 1790 # find problems in the field, we'll need to revisit their use.
1790 1791 sys.last_type = etype
1791 1792 sys.last_value = value
1792 1793 sys.last_traceback = tb
1793 1794
1794 1795 return etype, value, tb
1795 1796
1796 1797 def show_usage_error(self, exc):
1797 1798 """Show a short message for UsageErrors
1798 1799
1799 1800 These are special exceptions that shouldn't show a traceback.
1800 1801 """
1801 1802 self.write_err("UsageError: %s" % exc)
1802 1803
1803 1804 def get_exception_only(self, exc_tuple=None):
1804 1805 """
1805 1806 Return as a string (ending with a newline) the exception that
1806 1807 just occurred, without any traceback.
1807 1808 """
1808 1809 etype, value, tb = self._get_exc_info(exc_tuple)
1809 1810 msg = traceback.format_exception_only(etype, value)
1810 1811 return ''.join(msg)
1811 1812
1812 1813 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1813 1814 exception_only=False):
1814 1815 """Display the exception that just occurred.
1815 1816
1816 1817 If nothing is known about the exception, this is the method which
1817 1818 should be used throughout the code for presenting user tracebacks,
1818 1819 rather than directly invoking the InteractiveTB object.
1819 1820
1820 1821 A specific showsyntaxerror() also exists, but this method can take
1821 1822 care of calling it if needed, so unless you are explicitly catching a
1822 1823 SyntaxError exception, don't try to analyze the stack manually and
1823 1824 simply call this method."""
1824 1825
1825 1826 try:
1826 1827 try:
1827 1828 etype, value, tb = self._get_exc_info(exc_tuple)
1828 1829 except ValueError:
1829 1830 self.write_err('No traceback available to show.\n')
1830 1831 return
1831 1832
1832 1833 if issubclass(etype, SyntaxError):
1833 1834 # Though this won't be called by syntax errors in the input
1834 1835 # line, there may be SyntaxError cases with imported code.
1835 1836 self.showsyntaxerror(filename)
1836 1837 elif etype is UsageError:
1837 1838 self.show_usage_error(value)
1838 1839 else:
1839 1840 if exception_only:
1840 1841 stb = ['An exception has occurred, use %tb to see '
1841 1842 'the full traceback.\n']
1842 1843 stb.extend(self.InteractiveTB.get_exception_only(etype,
1843 1844 value))
1844 1845 else:
1845 1846 try:
1846 1847 # Exception classes can customise their traceback - we
1847 1848 # use this in IPython.parallel for exceptions occurring
1848 1849 # in the engines. This should return a list of strings.
1849 1850 stb = value._render_traceback_()
1850 1851 except Exception:
1851 1852 stb = self.InteractiveTB.structured_traceback(etype,
1852 1853 value, tb, tb_offset=tb_offset)
1853 1854
1854 1855 self._showtraceback(etype, value, stb)
1855 1856 if self.call_pdb:
1856 1857 # drop into debugger
1857 1858 self.debugger(force=True)
1858 1859 return
1859 1860
1860 1861 # Actually show the traceback
1861 1862 self._showtraceback(etype, value, stb)
1862 1863
1863 1864 except KeyboardInterrupt:
1864 1865 self.write_err('\n' + self.get_exception_only())
1865 1866
1866 1867 def _showtraceback(self, etype, evalue, stb):
1867 1868 """Actually show a traceback.
1868 1869
1869 1870 Subclasses may override this method to put the traceback on a different
1870 1871 place, like a side channel.
1871 1872 """
1872 1873 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1873 1874
1874 1875 def showsyntaxerror(self, filename=None):
1875 1876 """Display the syntax error that just occurred.
1876 1877
1877 1878 This doesn't display a stack trace because there isn't one.
1878 1879
1879 1880 If a filename is given, it is stuffed in the exception instead
1880 1881 of what was there before (because Python's parser always uses
1881 1882 "<string>" when reading from a string).
1882 1883 """
1883 1884 etype, value, last_traceback = self._get_exc_info()
1884 1885
1885 1886 if filename and issubclass(etype, SyntaxError):
1886 1887 try:
1887 1888 value.filename = filename
1888 1889 except:
1889 1890 # Not the format we expect; leave it alone
1890 1891 pass
1891 1892
1892 1893 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1893 1894 self._showtraceback(etype, value, stb)
1894 1895
1895 1896 # This is overridden in TerminalInteractiveShell to show a message about
1896 1897 # the %paste magic.
1897 1898 def showindentationerror(self):
1898 1899 """Called by run_cell when there's an IndentationError in code entered
1899 1900 at the prompt.
1900 1901
1901 1902 This is overridden in TerminalInteractiveShell to show a message about
1902 1903 the %paste magic."""
1903 1904 self.showsyntaxerror()
1904 1905
1905 1906 #-------------------------------------------------------------------------
1906 1907 # Things related to readline
1907 1908 #-------------------------------------------------------------------------
1908 1909
1909 1910 def init_readline(self):
1910 1911 """Command history completion/saving/reloading."""
1911 1912
1912 1913 if self.readline_use:
1913 1914 import IPython.utils.rlineimpl as readline
1914 1915
1915 1916 self.rl_next_input = None
1916 1917 self.rl_do_indent = False
1917 1918
1918 1919 if not self.readline_use or not readline.have_readline:
1919 1920 self.has_readline = False
1920 1921 self.readline = None
1921 1922 # Set a number of methods that depend on readline to be no-op
1922 1923 self.readline_no_record = no_op_context
1923 1924 self.set_readline_completer = no_op
1924 1925 self.set_custom_completer = no_op
1925 1926 if self.readline_use:
1926 1927 warn('Readline services not available or not loaded.')
1927 1928 else:
1928 1929 self.has_readline = True
1929 1930 self.readline = readline
1930 1931 sys.modules['readline'] = readline
1931 1932
1932 1933 # Platform-specific configuration
1933 1934 if os.name == 'nt':
1934 1935 # FIXME - check with Frederick to see if we can harmonize
1935 1936 # naming conventions with pyreadline to avoid this
1936 1937 # platform-dependent check
1937 1938 self.readline_startup_hook = readline.set_pre_input_hook
1938 1939 else:
1939 1940 self.readline_startup_hook = readline.set_startup_hook
1940 1941
1941 1942 # Readline config order:
1942 1943 # - IPython config (default value)
1943 1944 # - custom inputrc
1944 1945 # - IPython config (user customized)
1945 1946
1946 1947 # load IPython config before inputrc if default
1947 1948 # skip if libedit because parse_and_bind syntax is different
1948 1949 if not self._custom_readline_config and not readline.uses_libedit:
1949 1950 for rlcommand in self.readline_parse_and_bind:
1950 1951 readline.parse_and_bind(rlcommand)
1951 1952
1952 1953 # Load user's initrc file (readline config)
1953 1954 # Or if libedit is used, load editrc.
1954 1955 inputrc_name = os.environ.get('INPUTRC')
1955 1956 if inputrc_name is None:
1956 1957 inputrc_name = '.inputrc'
1957 1958 if readline.uses_libedit:
1958 1959 inputrc_name = '.editrc'
1959 1960 inputrc_name = os.path.join(self.home_dir, inputrc_name)
1960 1961 if os.path.isfile(inputrc_name):
1961 1962 try:
1962 1963 readline.read_init_file(inputrc_name)
1963 1964 except:
1964 1965 warn('Problems reading readline initialization file <%s>'
1965 1966 % inputrc_name)
1966 1967
1967 1968 # load IPython config after inputrc if user has customized
1968 1969 if self._custom_readline_config:
1969 1970 for rlcommand in self.readline_parse_and_bind:
1970 1971 readline.parse_and_bind(rlcommand)
1971 1972
1972 1973 # Remove some chars from the delimiters list. If we encounter
1973 1974 # unicode chars, discard them.
1974 1975 delims = readline.get_completer_delims()
1975 1976 if not py3compat.PY3:
1976 1977 delims = delims.encode("ascii", "ignore")
1977 1978 for d in self.readline_remove_delims:
1978 1979 delims = delims.replace(d, "")
1979 1980 delims = delims.replace(ESC_MAGIC, '')
1980 1981 readline.set_completer_delims(delims)
1981 1982 # Store these so we can restore them if something like rpy2 modifies
1982 1983 # them.
1983 1984 self.readline_delims = delims
1984 1985 # otherwise we end up with a monster history after a while:
1985 1986 readline.set_history_length(self.history_length)
1986 1987
1987 1988 self.refill_readline_hist()
1988 1989 self.readline_no_record = ReadlineNoRecord(self)
1989 1990
1990 1991 # Configure auto-indent for all platforms
1991 1992 self.set_autoindent(self.autoindent)
1992 1993
1993 1994 def refill_readline_hist(self):
1994 1995 # Load the last 1000 lines from history
1995 1996 self.readline.clear_history()
1996 1997 stdin_encoding = sys.stdin.encoding or "utf-8"
1997 1998 last_cell = u""
1998 1999 for _, _, cell in self.history_manager.get_tail(1000,
1999 2000 include_latest=True):
2000 2001 # Ignore blank lines and consecutive duplicates
2001 2002 cell = cell.rstrip()
2002 2003 if cell and (cell != last_cell):
2003 2004 try:
2004 2005 if self.multiline_history:
2005 2006 self.readline.add_history(py3compat.unicode_to_str(cell,
2006 2007 stdin_encoding))
2007 2008 else:
2008 2009 for line in cell.splitlines():
2009 2010 self.readline.add_history(py3compat.unicode_to_str(line,
2010 2011 stdin_encoding))
2011 2012 last_cell = cell
2012 2013
2013 2014 except TypeError:
2014 2015 # The history DB can get corrupted so it returns strings
2015 2016 # containing null bytes, which readline objects to.
2016 2017 continue
2017 2018
2018 2019 @skip_doctest
2019 2020 def set_next_input(self, s, replace=False):
2020 2021 """ Sets the 'default' input string for the next command line.
2021 2022
2022 2023 Requires readline.
2023 2024
2024 2025 Example::
2025 2026
2026 2027 In [1]: _ip.set_next_input("Hello Word")
2027 2028 In [2]: Hello Word_ # cursor is here
2028 2029 """
2029 2030 self.rl_next_input = py3compat.cast_bytes_py2(s)
2030 2031
2031 2032 # Maybe move this to the terminal subclass?
2032 2033 def pre_readline(self):
2033 2034 """readline hook to be used at the start of each line.
2034 2035
2035 2036 Currently it handles auto-indent only."""
2036 2037
2037 2038 if self.rl_do_indent:
2038 2039 self.readline.insert_text(self._indent_current_str())
2039 2040 if self.rl_next_input is not None:
2040 2041 self.readline.insert_text(self.rl_next_input)
2041 2042 self.rl_next_input = None
2042 2043
2043 2044 def _indent_current_str(self):
2044 2045 """return the current level of indentation as a string"""
2045 2046 return self.input_splitter.indent_spaces * ' '
2046 2047
2047 2048 #-------------------------------------------------------------------------
2048 2049 # Things related to text completion
2049 2050 #-------------------------------------------------------------------------
2050 2051
2051 2052 def init_completer(self):
2052 2053 """Initialize the completion machinery.
2053 2054
2054 2055 This creates completion machinery that can be used by client code,
2055 2056 either interactively in-process (typically triggered by the readline
2056 2057 library), programatically (such as in test suites) or out-of-prcess
2057 2058 (typically over the network by remote frontends).
2058 2059 """
2059 2060 from IPython.core.completer import IPCompleter
2060 2061 from IPython.core.completerlib import (module_completer,
2061 2062 magic_run_completer, cd_completer, reset_completer)
2062 2063
2063 2064 self.Completer = IPCompleter(shell=self,
2064 2065 namespace=self.user_ns,
2065 2066 global_namespace=self.user_global_ns,
2066 2067 use_readline=self.has_readline,
2067 2068 parent=self,
2068 2069 )
2069 2070 self.configurables.append(self.Completer)
2070 2071
2071 2072 # Add custom completers to the basic ones built into IPCompleter
2072 2073 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
2073 2074 self.strdispatchers['complete_command'] = sdisp
2074 2075 self.Completer.custom_completers = sdisp
2075 2076
2076 2077 self.set_hook('complete_command', module_completer, str_key = 'import')
2077 2078 self.set_hook('complete_command', module_completer, str_key = 'from')
2078 2079 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
2079 2080 self.set_hook('complete_command', cd_completer, str_key = '%cd')
2080 2081 self.set_hook('complete_command', reset_completer, str_key = '%reset')
2081 2082
2082 2083 # Only configure readline if we truly are using readline. IPython can
2083 2084 # do tab-completion over the network, in GUIs, etc, where readline
2084 2085 # itself may be absent
2085 2086 if self.has_readline:
2086 2087 self.set_readline_completer()
2087 2088
2088 2089 def complete(self, text, line=None, cursor_pos=None):
2089 2090 """Return the completed text and a list of completions.
2090 2091
2091 2092 Parameters
2092 2093 ----------
2093 2094
2094 2095 text : string
2095 2096 A string of text to be completed on. It can be given as empty and
2096 2097 instead a line/position pair are given. In this case, the
2097 2098 completer itself will split the line like readline does.
2098 2099
2099 2100 line : string, optional
2100 2101 The complete line that text is part of.
2101 2102
2102 2103 cursor_pos : int, optional
2103 2104 The position of the cursor on the input line.
2104 2105
2105 2106 Returns
2106 2107 -------
2107 2108 text : string
2108 2109 The actual text that was completed.
2109 2110
2110 2111 matches : list
2111 2112 A sorted list with all possible completions.
2112 2113
2113 2114 The optional arguments allow the completion to take more context into
2114 2115 account, and are part of the low-level completion API.
2115 2116
2116 2117 This is a wrapper around the completion mechanism, similar to what
2117 2118 readline does at the command line when the TAB key is hit. By
2118 2119 exposing it as a method, it can be used by other non-readline
2119 2120 environments (such as GUIs) for text completion.
2120 2121
2121 2122 Simple usage example:
2122 2123
2123 2124 In [1]: x = 'hello'
2124 2125
2125 2126 In [2]: _ip.complete('x.l')
2126 2127 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
2127 2128 """
2128 2129
2129 2130 # Inject names into __builtin__ so we can complete on the added names.
2130 2131 with self.builtin_trap:
2131 2132 return self.Completer.complete(text, line, cursor_pos)
2132 2133
2133 2134 def set_custom_completer(self, completer, pos=0):
2134 2135 """Adds a new custom completer function.
2135 2136
2136 2137 The position argument (defaults to 0) is the index in the completers
2137 2138 list where you want the completer to be inserted."""
2138 2139
2139 2140 newcomp = types.MethodType(completer,self.Completer)
2140 2141 self.Completer.matchers.insert(pos,newcomp)
2141 2142
2142 2143 def set_readline_completer(self):
2143 2144 """Reset readline's completer to be our own."""
2144 2145 self.readline.set_completer(self.Completer.rlcomplete)
2145 2146
2146 2147 def set_completer_frame(self, frame=None):
2147 2148 """Set the frame of the completer."""
2148 2149 if frame:
2149 2150 self.Completer.namespace = frame.f_locals
2150 2151 self.Completer.global_namespace = frame.f_globals
2151 2152 else:
2152 2153 self.Completer.namespace = self.user_ns
2153 2154 self.Completer.global_namespace = self.user_global_ns
2154 2155
2155 2156 #-------------------------------------------------------------------------
2156 2157 # Things related to magics
2157 2158 #-------------------------------------------------------------------------
2158 2159
2159 2160 def init_magics(self):
2160 2161 from IPython.core import magics as m
2161 2162 self.magics_manager = magic.MagicsManager(shell=self,
2162 2163 parent=self,
2163 2164 user_magics=m.UserMagics(self))
2164 2165 self.configurables.append(self.magics_manager)
2165 2166
2166 2167 # Expose as public API from the magics manager
2167 2168 self.register_magics = self.magics_manager.register
2168 2169 self.define_magic = self.magics_manager.define_magic
2169 2170
2170 2171 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2171 2172 m.ConfigMagics, m.DeprecatedMagics, m.DisplayMagics, m.ExecutionMagics,
2172 2173 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2173 2174 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2174 2175 )
2175 2176
2176 2177 # Register Magic Aliases
2177 2178 mman = self.magics_manager
2178 2179 # FIXME: magic aliases should be defined by the Magics classes
2179 2180 # or in MagicsManager, not here
2180 2181 mman.register_alias('ed', 'edit')
2181 2182 mman.register_alias('hist', 'history')
2182 2183 mman.register_alias('rep', 'recall')
2183 2184 mman.register_alias('SVG', 'svg', 'cell')
2184 2185 mman.register_alias('HTML', 'html', 'cell')
2185 2186 mman.register_alias('file', 'writefile', 'cell')
2186 2187
2187 2188 # FIXME: Move the color initialization to the DisplayHook, which
2188 2189 # should be split into a prompt manager and displayhook. We probably
2189 2190 # even need a centralize colors management object.
2190 2191 self.magic('colors %s' % self.colors)
2191 2192
2192 2193 # Defined here so that it's included in the documentation
2193 2194 @functools.wraps(magic.MagicsManager.register_function)
2194 2195 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2195 2196 self.magics_manager.register_function(func,
2196 2197 magic_kind=magic_kind, magic_name=magic_name)
2197 2198
2198 2199 def run_line_magic(self, magic_name, line):
2199 2200 """Execute the given line magic.
2200 2201
2201 2202 Parameters
2202 2203 ----------
2203 2204 magic_name : str
2204 2205 Name of the desired magic function, without '%' prefix.
2205 2206
2206 2207 line : str
2207 2208 The rest of the input line as a single string.
2208 2209 """
2209 2210 fn = self.find_line_magic(magic_name)
2210 2211 if fn is None:
2211 2212 cm = self.find_cell_magic(magic_name)
2212 2213 etpl = "Line magic function `%%%s` not found%s."
2213 2214 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2214 2215 'did you mean that instead?)' % magic_name )
2215 2216 error(etpl % (magic_name, extra))
2216 2217 else:
2217 2218 # Note: this is the distance in the stack to the user's frame.
2218 2219 # This will need to be updated if the internal calling logic gets
2219 2220 # refactored, or else we'll be expanding the wrong variables.
2220 2221 stack_depth = 2
2221 2222 magic_arg_s = self.var_expand(line, stack_depth)
2222 2223 # Put magic args in a list so we can call with f(*a) syntax
2223 2224 args = [magic_arg_s]
2224 2225 kwargs = {}
2225 2226 # Grab local namespace if we need it:
2226 2227 if getattr(fn, "needs_local_scope", False):
2227 2228 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2228 2229 with self.builtin_trap:
2229 2230 result = fn(*args,**kwargs)
2230 2231 return result
2231 2232
2232 2233 def run_cell_magic(self, magic_name, line, cell):
2233 2234 """Execute the given cell magic.
2234 2235
2235 2236 Parameters
2236 2237 ----------
2237 2238 magic_name : str
2238 2239 Name of the desired magic function, without '%' prefix.
2239 2240
2240 2241 line : str
2241 2242 The rest of the first input line as a single string.
2242 2243
2243 2244 cell : str
2244 2245 The body of the cell as a (possibly multiline) string.
2245 2246 """
2246 2247 fn = self.find_cell_magic(magic_name)
2247 2248 if fn is None:
2248 2249 lm = self.find_line_magic(magic_name)
2249 2250 etpl = "Cell magic `%%{0}` not found{1}."
2250 2251 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2251 2252 'did you mean that instead?)'.format(magic_name))
2252 2253 error(etpl.format(magic_name, extra))
2253 2254 elif cell == '':
2254 2255 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2255 2256 if self.find_line_magic(magic_name) is not None:
2256 2257 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2257 2258 raise UsageError(message)
2258 2259 else:
2259 2260 # Note: this is the distance in the stack to the user's frame.
2260 2261 # This will need to be updated if the internal calling logic gets
2261 2262 # refactored, or else we'll be expanding the wrong variables.
2262 2263 stack_depth = 2
2263 2264 magic_arg_s = self.var_expand(line, stack_depth)
2264 2265 with self.builtin_trap:
2265 2266 result = fn(magic_arg_s, cell)
2266 2267 return result
2267 2268
2268 2269 def find_line_magic(self, magic_name):
2269 2270 """Find and return a line magic by name.
2270 2271
2271 2272 Returns None if the magic isn't found."""
2272 2273 return self.magics_manager.magics['line'].get(magic_name)
2273 2274
2274 2275 def find_cell_magic(self, magic_name):
2275 2276 """Find and return a cell magic by name.
2276 2277
2277 2278 Returns None if the magic isn't found."""
2278 2279 return self.magics_manager.magics['cell'].get(magic_name)
2279 2280
2280 2281 def find_magic(self, magic_name, magic_kind='line'):
2281 2282 """Find and return a magic of the given type by name.
2282 2283
2283 2284 Returns None if the magic isn't found."""
2284 2285 return self.magics_manager.magics[magic_kind].get(magic_name)
2285 2286
2286 2287 def magic(self, arg_s):
2287 2288 """DEPRECATED. Use run_line_magic() instead.
2288 2289
2289 2290 Call a magic function by name.
2290 2291
2291 2292 Input: a string containing the name of the magic function to call and
2292 2293 any additional arguments to be passed to the magic.
2293 2294
2294 2295 magic('name -opt foo bar') is equivalent to typing at the ipython
2295 2296 prompt:
2296 2297
2297 2298 In[1]: %name -opt foo bar
2298 2299
2299 2300 To call a magic without arguments, simply use magic('name').
2300 2301
2301 2302 This provides a proper Python function to call IPython's magics in any
2302 2303 valid Python code you can type at the interpreter, including loops and
2303 2304 compound statements.
2304 2305 """
2305 2306 # TODO: should we issue a loud deprecation warning here?
2306 2307 magic_name, _, magic_arg_s = arg_s.partition(' ')
2307 2308 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2308 2309 return self.run_line_magic(magic_name, magic_arg_s)
2309 2310
2310 2311 #-------------------------------------------------------------------------
2311 2312 # Things related to macros
2312 2313 #-------------------------------------------------------------------------
2313 2314
2314 2315 def define_macro(self, name, themacro):
2315 2316 """Define a new macro
2316 2317
2317 2318 Parameters
2318 2319 ----------
2319 2320 name : str
2320 2321 The name of the macro.
2321 2322 themacro : str or Macro
2322 2323 The action to do upon invoking the macro. If a string, a new
2323 2324 Macro object is created by passing the string to it.
2324 2325 """
2325 2326
2326 2327 from IPython.core import macro
2327 2328
2328 2329 if isinstance(themacro, string_types):
2329 2330 themacro = macro.Macro(themacro)
2330 2331 if not isinstance(themacro, macro.Macro):
2331 2332 raise ValueError('A macro must be a string or a Macro instance.')
2332 2333 self.user_ns[name] = themacro
2333 2334
2334 2335 #-------------------------------------------------------------------------
2335 2336 # Things related to the running of system commands
2336 2337 #-------------------------------------------------------------------------
2337 2338
2338 2339 def system_piped(self, cmd):
2339 2340 """Call the given cmd in a subprocess, piping stdout/err
2340 2341
2341 2342 Parameters
2342 2343 ----------
2343 2344 cmd : str
2344 2345 Command to execute (can not end in '&', as background processes are
2345 2346 not supported. Should not be a command that expects input
2346 2347 other than simple text.
2347 2348 """
2348 2349 if cmd.rstrip().endswith('&'):
2349 2350 # this is *far* from a rigorous test
2350 2351 # We do not support backgrounding processes because we either use
2351 2352 # pexpect or pipes to read from. Users can always just call
2352 2353 # os.system() or use ip.system=ip.system_raw
2353 2354 # if they really want a background process.
2354 2355 raise OSError("Background processes not supported.")
2355 2356
2356 2357 # we explicitly do NOT return the subprocess status code, because
2357 2358 # a non-None value would trigger :func:`sys.displayhook` calls.
2358 2359 # Instead, we store the exit_code in user_ns.
2359 2360 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2360 2361
2361 2362 def system_raw(self, cmd):
2362 2363 """Call the given cmd in a subprocess using os.system on Windows or
2363 2364 subprocess.call using the system shell on other platforms.
2364 2365
2365 2366 Parameters
2366 2367 ----------
2367 2368 cmd : str
2368 2369 Command to execute.
2369 2370 """
2370 2371 cmd = self.var_expand(cmd, depth=1)
2371 2372 # protect os.system from UNC paths on Windows, which it can't handle:
2372 2373 if sys.platform == 'win32':
2373 2374 from IPython.utils._process_win32 import AvoidUNCPath
2374 2375 with AvoidUNCPath() as path:
2375 2376 if path is not None:
2376 2377 cmd = '"pushd %s &&"%s' % (path, cmd)
2377 2378 cmd = py3compat.unicode_to_str(cmd)
2378 2379 try:
2379 2380 ec = os.system(cmd)
2380 2381 except KeyboardInterrupt:
2381 2382 self.write_err('\n' + self.get_exception_only())
2382 2383 ec = -2
2383 2384 else:
2384 2385 cmd = py3compat.unicode_to_str(cmd)
2385 2386 # For posix the result of the subprocess.call() below is an exit
2386 2387 # code, which by convention is zero for success, positive for
2387 2388 # program failure. Exit codes above 128 are reserved for signals,
2388 2389 # and the formula for converting a signal to an exit code is usually
2389 2390 # signal_number+128. To more easily differentiate between exit
2390 2391 # codes and signals, ipython uses negative numbers. For instance
2391 2392 # since control-c is signal 2 but exit code 130, ipython's
2392 2393 # _exit_code variable will read -2. Note that some shells like
2393 2394 # csh and fish don't follow sh/bash conventions for exit codes.
2394 2395 executable = os.environ.get('SHELL', None)
2395 2396 try:
2396 2397 # Use env shell instead of default /bin/sh
2397 2398 ec = subprocess.call(cmd, shell=True, executable=executable)
2398 2399 except KeyboardInterrupt:
2399 2400 # intercept control-C; a long traceback is not useful here
2400 2401 self.write_err('\n' + self.get_exception_only())
2401 2402 ec = 130
2402 2403 if ec > 128:
2403 2404 ec = -(ec - 128)
2404 2405
2405 2406 # We explicitly do NOT return the subprocess status code, because
2406 2407 # a non-None value would trigger :func:`sys.displayhook` calls.
2407 2408 # Instead, we store the exit_code in user_ns. Note the semantics
2408 2409 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2409 2410 # but raising SystemExit(_exit_code) will give status 254!
2410 2411 self.user_ns['_exit_code'] = ec
2411 2412
2412 2413 # use piped system by default, because it is better behaved
2413 2414 system = system_piped
2414 2415
2415 2416 def getoutput(self, cmd, split=True, depth=0):
2416 2417 """Get output (possibly including stderr) from a subprocess.
2417 2418
2418 2419 Parameters
2419 2420 ----------
2420 2421 cmd : str
2421 2422 Command to execute (can not end in '&', as background processes are
2422 2423 not supported.
2423 2424 split : bool, optional
2424 2425 If True, split the output into an IPython SList. Otherwise, an
2425 2426 IPython LSString is returned. These are objects similar to normal
2426 2427 lists and strings, with a few convenience attributes for easier
2427 2428 manipulation of line-based output. You can use '?' on them for
2428 2429 details.
2429 2430 depth : int, optional
2430 2431 How many frames above the caller are the local variables which should
2431 2432 be expanded in the command string? The default (0) assumes that the
2432 2433 expansion variables are in the stack frame calling this function.
2433 2434 """
2434 2435 if cmd.rstrip().endswith('&'):
2435 2436 # this is *far* from a rigorous test
2436 2437 raise OSError("Background processes not supported.")
2437 2438 out = getoutput(self.var_expand(cmd, depth=depth+1))
2438 2439 if split:
2439 2440 out = SList(out.splitlines())
2440 2441 else:
2441 2442 out = LSString(out)
2442 2443 return out
2443 2444
2444 2445 #-------------------------------------------------------------------------
2445 2446 # Things related to aliases
2446 2447 #-------------------------------------------------------------------------
2447 2448
2448 2449 def init_alias(self):
2449 2450 self.alias_manager = AliasManager(shell=self, parent=self)
2450 2451 self.configurables.append(self.alias_manager)
2451 2452
2452 2453 #-------------------------------------------------------------------------
2453 2454 # Things related to extensions
2454 2455 #-------------------------------------------------------------------------
2455 2456
2456 2457 def init_extension_manager(self):
2457 2458 self.extension_manager = ExtensionManager(shell=self, parent=self)
2458 2459 self.configurables.append(self.extension_manager)
2459 2460
2460 2461 #-------------------------------------------------------------------------
2461 2462 # Things related to payloads
2462 2463 #-------------------------------------------------------------------------
2463 2464
2464 2465 def init_payload(self):
2465 2466 self.payload_manager = PayloadManager(parent=self)
2466 2467 self.configurables.append(self.payload_manager)
2467 2468
2468 2469 #-------------------------------------------------------------------------
2469 2470 # Things related to the prefilter
2470 2471 #-------------------------------------------------------------------------
2471 2472
2472 2473 def init_prefilter(self):
2473 2474 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2474 2475 self.configurables.append(self.prefilter_manager)
2475 2476 # Ultimately this will be refactored in the new interpreter code, but
2476 2477 # for now, we should expose the main prefilter method (there's legacy
2477 2478 # code out there that may rely on this).
2478 2479 self.prefilter = self.prefilter_manager.prefilter_lines
2479 2480
2480 2481 def auto_rewrite_input(self, cmd):
2481 2482 """Print to the screen the rewritten form of the user's command.
2482 2483
2483 2484 This shows visual feedback by rewriting input lines that cause
2484 2485 automatic calling to kick in, like::
2485 2486
2486 2487 /f x
2487 2488
2488 2489 into::
2489 2490
2490 2491 ------> f(x)
2491 2492
2492 2493 after the user's input prompt. This helps the user understand that the
2493 2494 input line was transformed automatically by IPython.
2494 2495 """
2495 2496 if not self.show_rewritten_input:
2496 2497 return
2497 2498
2498 2499 rw = self.prompt_manager.render('rewrite') + cmd
2499 2500
2500 2501 try:
2501 2502 # plain ascii works better w/ pyreadline, on some machines, so
2502 2503 # we use it and only print uncolored rewrite if we have unicode
2503 2504 rw = str(rw)
2504 2505 print(rw, file=io.stdout)
2505 2506 except UnicodeEncodeError:
2506 2507 print("------> " + cmd)
2507 2508
2508 2509 #-------------------------------------------------------------------------
2509 2510 # Things related to extracting values/expressions from kernel and user_ns
2510 2511 #-------------------------------------------------------------------------
2511 2512
2512 2513 def _user_obj_error(self):
2513 2514 """return simple exception dict
2514 2515
2515 2516 for use in user_expressions
2516 2517 """
2517 2518
2518 2519 etype, evalue, tb = self._get_exc_info()
2519 2520 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2520 2521
2521 2522 exc_info = {
2522 2523 u'status' : 'error',
2523 2524 u'traceback' : stb,
2524 2525 u'ename' : unicode_type(etype.__name__),
2525 2526 u'evalue' : py3compat.safe_unicode(evalue),
2526 2527 }
2527 2528
2528 2529 return exc_info
2529 2530
2530 2531 def _format_user_obj(self, obj):
2531 2532 """format a user object to display dict
2532 2533
2533 2534 for use in user_expressions
2534 2535 """
2535 2536
2536 2537 data, md = self.display_formatter.format(obj)
2537 2538 value = {
2538 2539 'status' : 'ok',
2539 2540 'data' : data,
2540 2541 'metadata' : md,
2541 2542 }
2542 2543 return value
2543 2544
2544 2545 def user_expressions(self, expressions):
2545 2546 """Evaluate a dict of expressions in the user's namespace.
2546 2547
2547 2548 Parameters
2548 2549 ----------
2549 2550 expressions : dict
2550 2551 A dict with string keys and string values. The expression values
2551 2552 should be valid Python expressions, each of which will be evaluated
2552 2553 in the user namespace.
2553 2554
2554 2555 Returns
2555 2556 -------
2556 2557 A dict, keyed like the input expressions dict, with the rich mime-typed
2557 2558 display_data of each value.
2558 2559 """
2559 2560 out = {}
2560 2561 user_ns = self.user_ns
2561 2562 global_ns = self.user_global_ns
2562 2563
2563 2564 for key, expr in iteritems(expressions):
2564 2565 try:
2565 2566 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2566 2567 except:
2567 2568 value = self._user_obj_error()
2568 2569 out[key] = value
2569 2570 return out
2570 2571
2571 2572 #-------------------------------------------------------------------------
2572 2573 # Things related to the running of code
2573 2574 #-------------------------------------------------------------------------
2574 2575
2575 2576 def ex(self, cmd):
2576 2577 """Execute a normal python statement in user namespace."""
2577 2578 with self.builtin_trap:
2578 2579 exec(cmd, self.user_global_ns, self.user_ns)
2579 2580
2580 2581 def ev(self, expr):
2581 2582 """Evaluate python expression expr in user namespace.
2582 2583
2583 2584 Returns the result of evaluation
2584 2585 """
2585 2586 with self.builtin_trap:
2586 2587 return eval(expr, self.user_global_ns, self.user_ns)
2587 2588
2588 2589 def safe_execfile(self, fname, *where, **kw):
2589 2590 """A safe version of the builtin execfile().
2590 2591
2591 2592 This version will never throw an exception, but instead print
2592 2593 helpful error messages to the screen. This only works on pure
2593 2594 Python files with the .py extension.
2594 2595
2595 2596 Parameters
2596 2597 ----------
2597 2598 fname : string
2598 2599 The name of the file to be executed.
2599 2600 where : tuple
2600 2601 One or two namespaces, passed to execfile() as (globals,locals).
2601 2602 If only one is given, it is passed as both.
2602 2603 exit_ignore : bool (False)
2603 2604 If True, then silence SystemExit for non-zero status (it is always
2604 2605 silenced for zero status, as it is so common).
2605 2606 raise_exceptions : bool (False)
2606 2607 If True raise exceptions everywhere. Meant for testing.
2607 2608 shell_futures : bool (False)
2608 2609 If True, the code will share future statements with the interactive
2609 2610 shell. It will both be affected by previous __future__ imports, and
2610 2611 any __future__ imports in the code will affect the shell. If False,
2611 2612 __future__ imports are not shared in either direction.
2612 2613
2613 2614 """
2614 2615 kw.setdefault('exit_ignore', False)
2615 2616 kw.setdefault('raise_exceptions', False)
2616 2617 kw.setdefault('shell_futures', False)
2617 2618
2618 2619 fname = os.path.abspath(os.path.expanduser(fname))
2619 2620
2620 2621 # Make sure we can open the file
2621 2622 try:
2622 2623 with open(fname) as thefile:
2623 2624 pass
2624 2625 except:
2625 2626 warn('Could not open file <%s> for safe execution.' % fname)
2626 2627 return
2627 2628
2628 2629 # Find things also in current directory. This is needed to mimic the
2629 2630 # behavior of running a script from the system command line, where
2630 2631 # Python inserts the script's directory into sys.path
2631 2632 dname = os.path.dirname(fname)
2632 2633
2633 2634 with prepended_to_syspath(dname):
2634 2635 try:
2635 2636 glob, loc = (where + (None, ))[:2]
2636 2637 py3compat.execfile(
2637 2638 fname, glob, loc,
2638 2639 self.compile if kw['shell_futures'] else None)
2639 2640 except SystemExit as status:
2640 2641 # If the call was made with 0 or None exit status (sys.exit(0)
2641 2642 # or sys.exit() ), don't bother showing a traceback, as both of
2642 2643 # these are considered normal by the OS:
2643 2644 # > python -c'import sys;sys.exit(0)'; echo $?
2644 2645 # 0
2645 2646 # > python -c'import sys;sys.exit()'; echo $?
2646 2647 # 0
2647 2648 # For other exit status, we show the exception unless
2648 2649 # explicitly silenced, but only in short form.
2649 2650 if kw['raise_exceptions']:
2650 2651 raise
2651 2652 if status.code and not kw['exit_ignore']:
2652 2653 self.showtraceback(exception_only=True)
2653 2654 except:
2654 2655 if kw['raise_exceptions']:
2655 2656 raise
2656 2657 # tb offset is 2 because we wrap execfile
2657 2658 self.showtraceback(tb_offset=2)
2658 2659
2659 2660 def safe_execfile_ipy(self, fname, shell_futures=False):
2660 2661 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2661 2662
2662 2663 Parameters
2663 2664 ----------
2664 2665 fname : str
2665 2666 The name of the file to execute. The filename must have a
2666 2667 .ipy or .ipynb extension.
2667 2668 shell_futures : bool (False)
2668 2669 If True, the code will share future statements with the interactive
2669 2670 shell. It will both be affected by previous __future__ imports, and
2670 2671 any __future__ imports in the code will affect the shell. If False,
2671 2672 __future__ imports are not shared in either direction.
2672 2673 """
2673 2674 fname = os.path.abspath(os.path.expanduser(fname))
2674 2675
2675 2676 # Make sure we can open the file
2676 2677 try:
2677 2678 with open(fname) as thefile:
2678 2679 pass
2679 2680 except:
2680 2681 warn('Could not open file <%s> for safe execution.' % fname)
2681 2682 return
2682 2683
2683 2684 # Find things also in current directory. This is needed to mimic the
2684 2685 # behavior of running a script from the system command line, where
2685 2686 # Python inserts the script's directory into sys.path
2686 2687 dname = os.path.dirname(fname)
2687 2688
2688 2689 def get_cells():
2689 2690 """generator for sequence of code blocks to run"""
2690 2691 if fname.endswith('.ipynb'):
2691 from IPython.nbformat import read
2692 from jupyter_nbformat import read
2692 2693 with io_open(fname) as f:
2693 2694 nb = read(f, as_version=4)
2694 2695 if not nb.cells:
2695 2696 return
2696 2697 for cell in nb.cells:
2697 2698 if cell.cell_type == 'code':
2698 2699 yield cell.source
2699 2700 else:
2700 2701 with open(fname) as f:
2701 2702 yield f.read()
2702 2703
2703 2704 with prepended_to_syspath(dname):
2704 2705 try:
2705 2706 for cell in get_cells():
2706 2707 # self.run_cell currently captures all exceptions
2707 2708 # raised in user code. It would be nice if there were
2708 2709 # versions of run_cell that did raise, so
2709 2710 # we could catch the errors.
2710 2711 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2711 2712 if not result.success:
2712 2713 break
2713 2714 except:
2714 2715 self.showtraceback()
2715 2716 warn('Unknown failure executing file: <%s>' % fname)
2716 2717
2717 2718 def safe_run_module(self, mod_name, where):
2718 2719 """A safe version of runpy.run_module().
2719 2720
2720 2721 This version will never throw an exception, but instead print
2721 2722 helpful error messages to the screen.
2722 2723
2723 2724 `SystemExit` exceptions with status code 0 or None are ignored.
2724 2725
2725 2726 Parameters
2726 2727 ----------
2727 2728 mod_name : string
2728 2729 The name of the module to be executed.
2729 2730 where : dict
2730 2731 The globals namespace.
2731 2732 """
2732 2733 try:
2733 2734 try:
2734 2735 where.update(
2735 2736 runpy.run_module(str(mod_name), run_name="__main__",
2736 2737 alter_sys=True)
2737 2738 )
2738 2739 except SystemExit as status:
2739 2740 if status.code:
2740 2741 raise
2741 2742 except:
2742 2743 self.showtraceback()
2743 2744 warn('Unknown failure executing module: <%s>' % mod_name)
2744 2745
2745 2746 def _run_cached_cell_magic(self, magic_name, line):
2746 2747 """Special method to call a cell magic with the data stored in self.
2747 2748 """
2748 2749 cell = self._current_cell_magic_body
2749 2750 self._current_cell_magic_body = None
2750 2751 return self.run_cell_magic(magic_name, line, cell)
2751 2752
2752 2753 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2753 2754 """Run a complete IPython cell.
2754 2755
2755 2756 Parameters
2756 2757 ----------
2757 2758 raw_cell : str
2758 2759 The code (including IPython code such as %magic functions) to run.
2759 2760 store_history : bool
2760 2761 If True, the raw and translated cell will be stored in IPython's
2761 2762 history. For user code calling back into IPython's machinery, this
2762 2763 should be set to False.
2763 2764 silent : bool
2764 2765 If True, avoid side-effects, such as implicit displayhooks and
2765 2766 and logging. silent=True forces store_history=False.
2766 2767 shell_futures : bool
2767 2768 If True, the code will share future statements with the interactive
2768 2769 shell. It will both be affected by previous __future__ imports, and
2769 2770 any __future__ imports in the code will affect the shell. If False,
2770 2771 __future__ imports are not shared in either direction.
2771 2772
2772 2773 Returns
2773 2774 -------
2774 2775 result : :class:`ExecutionResult`
2775 2776 """
2776 2777 result = ExecutionResult()
2777 2778
2778 2779 if (not raw_cell) or raw_cell.isspace():
2779 2780 return result
2780 2781
2781 2782 if silent:
2782 2783 store_history = False
2783 2784
2784 2785 if store_history:
2785 2786 result.execution_count = self.execution_count
2786 2787
2787 2788 def error_before_exec(value):
2788 2789 result.error_before_exec = value
2789 2790 return result
2790 2791
2791 2792 self.events.trigger('pre_execute')
2792 2793 if not silent:
2793 2794 self.events.trigger('pre_run_cell')
2794 2795
2795 2796 # If any of our input transformation (input_transformer_manager or
2796 2797 # prefilter_manager) raises an exception, we store it in this variable
2797 2798 # so that we can display the error after logging the input and storing
2798 2799 # it in the history.
2799 2800 preprocessing_exc_tuple = None
2800 2801 try:
2801 2802 # Static input transformations
2802 2803 cell = self.input_transformer_manager.transform_cell(raw_cell)
2803 2804 except SyntaxError:
2804 2805 preprocessing_exc_tuple = sys.exc_info()
2805 2806 cell = raw_cell # cell has to exist so it can be stored/logged
2806 2807 else:
2807 2808 if len(cell.splitlines()) == 1:
2808 2809 # Dynamic transformations - only applied for single line commands
2809 2810 with self.builtin_trap:
2810 2811 try:
2811 2812 # use prefilter_lines to handle trailing newlines
2812 2813 # restore trailing newline for ast.parse
2813 2814 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2814 2815 except Exception:
2815 2816 # don't allow prefilter errors to crash IPython
2816 2817 preprocessing_exc_tuple = sys.exc_info()
2817 2818
2818 2819 # Store raw and processed history
2819 2820 if store_history:
2820 2821 self.history_manager.store_inputs(self.execution_count,
2821 2822 cell, raw_cell)
2822 2823 if not silent:
2823 2824 self.logger.log(cell, raw_cell)
2824 2825
2825 2826 # Display the exception if input processing failed.
2826 2827 if preprocessing_exc_tuple is not None:
2827 2828 self.showtraceback(preprocessing_exc_tuple)
2828 2829 if store_history:
2829 2830 self.execution_count += 1
2830 2831 return error_before_exec(preprocessing_exc_tuple[2])
2831 2832
2832 2833 # Our own compiler remembers the __future__ environment. If we want to
2833 2834 # run code with a separate __future__ environment, use the default
2834 2835 # compiler
2835 2836 compiler = self.compile if shell_futures else CachingCompiler()
2836 2837
2837 2838 with self.builtin_trap:
2838 2839 cell_name = self.compile.cache(cell, self.execution_count)
2839 2840
2840 2841 with self.display_trap:
2841 2842 # Compile to bytecode
2842 2843 try:
2843 2844 code_ast = compiler.ast_parse(cell, filename=cell_name)
2844 2845 except IndentationError as e:
2845 2846 self.showindentationerror()
2846 2847 if store_history:
2847 2848 self.execution_count += 1
2848 2849 return error_before_exec(e)
2849 2850 except (OverflowError, SyntaxError, ValueError, TypeError,
2850 2851 MemoryError) as e:
2851 2852 self.showsyntaxerror()
2852 2853 if store_history:
2853 2854 self.execution_count += 1
2854 2855 return error_before_exec(e)
2855 2856
2856 2857 # Apply AST transformations
2857 2858 try:
2858 2859 code_ast = self.transform_ast(code_ast)
2859 2860 except InputRejected as e:
2860 2861 self.showtraceback()
2861 2862 if store_history:
2862 2863 self.execution_count += 1
2863 2864 return error_before_exec(e)
2864 2865
2865 2866 # Give the displayhook a reference to our ExecutionResult so it
2866 2867 # can fill in the output value.
2867 2868 self.displayhook.exec_result = result
2868 2869
2869 2870 # Execute the user code
2870 2871 interactivity = "none" if silent else self.ast_node_interactivity
2871 2872 self.run_ast_nodes(code_ast.body, cell_name,
2872 2873 interactivity=interactivity, compiler=compiler, result=result)
2873 2874
2874 2875 # Reset this so later displayed values do not modify the
2875 2876 # ExecutionResult
2876 2877 self.displayhook.exec_result = None
2877 2878
2878 2879 self.events.trigger('post_execute')
2879 2880 if not silent:
2880 2881 self.events.trigger('post_run_cell')
2881 2882
2882 2883 if store_history:
2883 2884 # Write output to the database. Does nothing unless
2884 2885 # history output logging is enabled.
2885 2886 self.history_manager.store_output(self.execution_count)
2886 2887 # Each cell is a *single* input, regardless of how many lines it has
2887 2888 self.execution_count += 1
2888 2889
2889 2890 return result
2890 2891
2891 2892 def transform_ast(self, node):
2892 2893 """Apply the AST transformations from self.ast_transformers
2893 2894
2894 2895 Parameters
2895 2896 ----------
2896 2897 node : ast.Node
2897 2898 The root node to be transformed. Typically called with the ast.Module
2898 2899 produced by parsing user input.
2899 2900
2900 2901 Returns
2901 2902 -------
2902 2903 An ast.Node corresponding to the node it was called with. Note that it
2903 2904 may also modify the passed object, so don't rely on references to the
2904 2905 original AST.
2905 2906 """
2906 2907 for transformer in self.ast_transformers:
2907 2908 try:
2908 2909 node = transformer.visit(node)
2909 2910 except InputRejected:
2910 2911 # User-supplied AST transformers can reject an input by raising
2911 2912 # an InputRejected. Short-circuit in this case so that we
2912 2913 # don't unregister the transform.
2913 2914 raise
2914 2915 except Exception:
2915 2916 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2916 2917 self.ast_transformers.remove(transformer)
2917 2918
2918 2919 if self.ast_transformers:
2919 2920 ast.fix_missing_locations(node)
2920 2921 return node
2921 2922
2922 2923
2923 2924 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2924 2925 compiler=compile, result=None):
2925 2926 """Run a sequence of AST nodes. The execution mode depends on the
2926 2927 interactivity parameter.
2927 2928
2928 2929 Parameters
2929 2930 ----------
2930 2931 nodelist : list
2931 2932 A sequence of AST nodes to run.
2932 2933 cell_name : str
2933 2934 Will be passed to the compiler as the filename of the cell. Typically
2934 2935 the value returned by ip.compile.cache(cell).
2935 2936 interactivity : str
2936 2937 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2937 2938 run interactively (displaying output from expressions). 'last_expr'
2938 2939 will run the last node interactively only if it is an expression (i.e.
2939 2940 expressions in loops or other blocks are not displayed. Other values
2940 2941 for this parameter will raise a ValueError.
2941 2942 compiler : callable
2942 2943 A function with the same interface as the built-in compile(), to turn
2943 2944 the AST nodes into code objects. Default is the built-in compile().
2944 2945 result : ExecutionResult, optional
2945 2946 An object to store exceptions that occur during execution.
2946 2947
2947 2948 Returns
2948 2949 -------
2949 2950 True if an exception occurred while running code, False if it finished
2950 2951 running.
2951 2952 """
2952 2953 if not nodelist:
2953 2954 return
2954 2955
2955 2956 if interactivity == 'last_expr':
2956 2957 if isinstance(nodelist[-1], ast.Expr):
2957 2958 interactivity = "last"
2958 2959 else:
2959 2960 interactivity = "none"
2960 2961
2961 2962 if interactivity == 'none':
2962 2963 to_run_exec, to_run_interactive = nodelist, []
2963 2964 elif interactivity == 'last':
2964 2965 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2965 2966 elif interactivity == 'all':
2966 2967 to_run_exec, to_run_interactive = [], nodelist
2967 2968 else:
2968 2969 raise ValueError("Interactivity was %r" % interactivity)
2969 2970
2970 2971 exec_count = self.execution_count
2971 2972
2972 2973 try:
2973 2974 for i, node in enumerate(to_run_exec):
2974 2975 mod = ast.Module([node])
2975 2976 code = compiler(mod, cell_name, "exec")
2976 2977 if self.run_code(code, result):
2977 2978 return True
2978 2979
2979 2980 for i, node in enumerate(to_run_interactive):
2980 2981 mod = ast.Interactive([node])
2981 2982 code = compiler(mod, cell_name, "single")
2982 2983 if self.run_code(code, result):
2983 2984 return True
2984 2985
2985 2986 # Flush softspace
2986 2987 if softspace(sys.stdout, 0):
2987 2988 print()
2988 2989
2989 2990 except:
2990 2991 # It's possible to have exceptions raised here, typically by
2991 2992 # compilation of odd code (such as a naked 'return' outside a
2992 2993 # function) that did parse but isn't valid. Typically the exception
2993 2994 # is a SyntaxError, but it's safest just to catch anything and show
2994 2995 # the user a traceback.
2995 2996
2996 2997 # We do only one try/except outside the loop to minimize the impact
2997 2998 # on runtime, and also because if any node in the node list is
2998 2999 # broken, we should stop execution completely.
2999 3000 if result:
3000 3001 result.error_before_exec = sys.exc_info()[1]
3001 3002 self.showtraceback()
3002 3003 return True
3003 3004
3004 3005 return False
3005 3006
3006 3007 def run_code(self, code_obj, result=None):
3007 3008 """Execute a code object.
3008 3009
3009 3010 When an exception occurs, self.showtraceback() is called to display a
3010 3011 traceback.
3011 3012
3012 3013 Parameters
3013 3014 ----------
3014 3015 code_obj : code object
3015 3016 A compiled code object, to be executed
3016 3017 result : ExecutionResult, optional
3017 3018 An object to store exceptions that occur during execution.
3018 3019
3019 3020 Returns
3020 3021 -------
3021 3022 False : successful execution.
3022 3023 True : an error occurred.
3023 3024 """
3024 3025 # Set our own excepthook in case the user code tries to call it
3025 3026 # directly, so that the IPython crash handler doesn't get triggered
3026 3027 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
3027 3028
3028 3029 # we save the original sys.excepthook in the instance, in case config
3029 3030 # code (such as magics) needs access to it.
3030 3031 self.sys_excepthook = old_excepthook
3031 3032 outflag = 1 # happens in more places, so it's easier as default
3032 3033 try:
3033 3034 try:
3034 3035 self.hooks.pre_run_code_hook()
3035 3036 #rprint('Running code', repr(code_obj)) # dbg
3036 3037 exec(code_obj, self.user_global_ns, self.user_ns)
3037 3038 finally:
3038 3039 # Reset our crash handler in place
3039 3040 sys.excepthook = old_excepthook
3040 3041 except SystemExit as e:
3041 3042 if result is not None:
3042 3043 result.error_in_exec = e
3043 3044 self.showtraceback(exception_only=True)
3044 3045 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
3045 3046 except self.custom_exceptions:
3046 3047 etype, value, tb = sys.exc_info()
3047 3048 if result is not None:
3048 3049 result.error_in_exec = value
3049 3050 self.CustomTB(etype, value, tb)
3050 3051 except:
3051 3052 if result is not None:
3052 3053 result.error_in_exec = sys.exc_info()[1]
3053 3054 self.showtraceback()
3054 3055 else:
3055 3056 outflag = 0
3056 3057 return outflag
3057 3058
3058 3059 # For backwards compatibility
3059 3060 runcode = run_code
3060 3061
3061 3062 #-------------------------------------------------------------------------
3062 3063 # Things related to GUI support and pylab
3063 3064 #-------------------------------------------------------------------------
3064 3065
3065 3066 def enable_gui(self, gui=None):
3066 3067 raise NotImplementedError('Implement enable_gui in a subclass')
3067 3068
3068 3069 def enable_matplotlib(self, gui=None):
3069 3070 """Enable interactive matplotlib and inline figure support.
3070 3071
3071 3072 This takes the following steps:
3072 3073
3073 3074 1. select the appropriate eventloop and matplotlib backend
3074 3075 2. set up matplotlib for interactive use with that backend
3075 3076 3. configure formatters for inline figure display
3076 3077 4. enable the selected gui eventloop
3077 3078
3078 3079 Parameters
3079 3080 ----------
3080 3081 gui : optional, string
3081 3082 If given, dictates the choice of matplotlib GUI backend to use
3082 3083 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3083 3084 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3084 3085 matplotlib (as dictated by the matplotlib build-time options plus the
3085 3086 user's matplotlibrc configuration file). Note that not all backends
3086 3087 make sense in all contexts, for example a terminal ipython can't
3087 3088 display figures inline.
3088 3089 """
3089 3090 from IPython.core import pylabtools as pt
3090 3091 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
3091 3092
3092 3093 if gui != 'inline':
3093 3094 # If we have our first gui selection, store it
3094 3095 if self.pylab_gui_select is None:
3095 3096 self.pylab_gui_select = gui
3096 3097 # Otherwise if they are different
3097 3098 elif gui != self.pylab_gui_select:
3098 3099 print ('Warning: Cannot change to a different GUI toolkit: %s.'
3099 3100 ' Using %s instead.' % (gui, self.pylab_gui_select))
3100 3101 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
3101 3102
3102 3103 pt.activate_matplotlib(backend)
3103 3104 pt.configure_inline_support(self, backend)
3104 3105
3105 3106 # Now we must activate the gui pylab wants to use, and fix %run to take
3106 3107 # plot updates into account
3107 3108 self.enable_gui(gui)
3108 3109 self.magics_manager.registry['ExecutionMagics'].default_runner = \
3109 3110 pt.mpl_runner(self.safe_execfile)
3110 3111
3111 3112 return gui, backend
3112 3113
3113 3114 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
3114 3115 """Activate pylab support at runtime.
3115 3116
3116 3117 This turns on support for matplotlib, preloads into the interactive
3117 3118 namespace all of numpy and pylab, and configures IPython to correctly
3118 3119 interact with the GUI event loop. The GUI backend to be used can be
3119 3120 optionally selected with the optional ``gui`` argument.
3120 3121
3121 3122 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
3122 3123
3123 3124 Parameters
3124 3125 ----------
3125 3126 gui : optional, string
3126 3127 If given, dictates the choice of matplotlib GUI backend to use
3127 3128 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3128 3129 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3129 3130 matplotlib (as dictated by the matplotlib build-time options plus the
3130 3131 user's matplotlibrc configuration file). Note that not all backends
3131 3132 make sense in all contexts, for example a terminal ipython can't
3132 3133 display figures inline.
3133 3134 import_all : optional, bool, default: True
3134 3135 Whether to do `from numpy import *` and `from pylab import *`
3135 3136 in addition to module imports.
3136 3137 welcome_message : deprecated
3137 3138 This argument is ignored, no welcome message will be displayed.
3138 3139 """
3139 3140 from IPython.core.pylabtools import import_pylab
3140 3141
3141 3142 gui, backend = self.enable_matplotlib(gui)
3142 3143
3143 3144 # We want to prevent the loading of pylab to pollute the user's
3144 3145 # namespace as shown by the %who* magics, so we execute the activation
3145 3146 # code in an empty namespace, and we update *both* user_ns and
3146 3147 # user_ns_hidden with this information.
3147 3148 ns = {}
3148 3149 import_pylab(ns, import_all)
3149 3150 # warn about clobbered names
3150 3151 ignored = set(["__builtins__"])
3151 3152 both = set(ns).intersection(self.user_ns).difference(ignored)
3152 3153 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3153 3154 self.user_ns.update(ns)
3154 3155 self.user_ns_hidden.update(ns)
3155 3156 return gui, backend, clobbered
3156 3157
3157 3158 #-------------------------------------------------------------------------
3158 3159 # Utilities
3159 3160 #-------------------------------------------------------------------------
3160 3161
3161 3162 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3162 3163 """Expand python variables in a string.
3163 3164
3164 3165 The depth argument indicates how many frames above the caller should
3165 3166 be walked to look for the local namespace where to expand variables.
3166 3167
3167 3168 The global namespace for expansion is always the user's interactive
3168 3169 namespace.
3169 3170 """
3170 3171 ns = self.user_ns.copy()
3171 3172 try:
3172 3173 frame = sys._getframe(depth+1)
3173 3174 except ValueError:
3174 3175 # This is thrown if there aren't that many frames on the stack,
3175 3176 # e.g. if a script called run_line_magic() directly.
3176 3177 pass
3177 3178 else:
3178 3179 ns.update(frame.f_locals)
3179 3180
3180 3181 try:
3181 3182 # We have to use .vformat() here, because 'self' is a valid and common
3182 3183 # name, and expanding **ns for .format() would make it collide with
3183 3184 # the 'self' argument of the method.
3184 3185 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3185 3186 except Exception:
3186 3187 # if formatter couldn't format, just let it go untransformed
3187 3188 pass
3188 3189 return cmd
3189 3190
3190 3191 def mktempfile(self, data=None, prefix='ipython_edit_'):
3191 3192 """Make a new tempfile and return its filename.
3192 3193
3193 3194 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3194 3195 but it registers the created filename internally so ipython cleans it up
3195 3196 at exit time.
3196 3197
3197 3198 Optional inputs:
3198 3199
3199 3200 - data(None): if data is given, it gets written out to the temp file
3200 3201 immediately, and the file is closed again."""
3201 3202
3202 3203 dirname = tempfile.mkdtemp(prefix=prefix)
3203 3204 self.tempdirs.append(dirname)
3204 3205
3205 3206 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3206 3207 os.close(handle) # On Windows, there can only be one open handle on a file
3207 3208 self.tempfiles.append(filename)
3208 3209
3209 3210 if data:
3210 3211 tmp_file = open(filename,'w')
3211 3212 tmp_file.write(data)
3212 3213 tmp_file.close()
3213 3214 return filename
3214 3215
3215 3216 # TODO: This should be removed when Term is refactored.
3216 3217 def write(self,data):
3217 3218 """Write a string to the default output"""
3218 3219 io.stdout.write(data)
3219 3220
3220 3221 # TODO: This should be removed when Term is refactored.
3221 3222 def write_err(self,data):
3222 3223 """Write a string to the default error output"""
3223 3224 io.stderr.write(data)
3224 3225
3225 3226 def ask_yes_no(self, prompt, default=None):
3226 3227 if self.quiet:
3227 3228 return True
3228 3229 return ask_yes_no(prompt,default)
3229 3230
3230 3231 def show_usage(self):
3231 3232 """Show a usage message"""
3232 3233 page.page(IPython.core.usage.interactive_usage)
3233 3234
3234 3235 def extract_input_lines(self, range_str, raw=False):
3235 3236 """Return as a string a set of input history slices.
3236 3237
3237 3238 Parameters
3238 3239 ----------
3239 3240 range_str : string
3240 3241 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3241 3242 since this function is for use by magic functions which get their
3242 3243 arguments as strings. The number before the / is the session
3243 3244 number: ~n goes n back from the current session.
3244 3245
3245 3246 raw : bool, optional
3246 3247 By default, the processed input is used. If this is true, the raw
3247 3248 input history is used instead.
3248 3249
3249 3250 Notes
3250 3251 -----
3251 3252
3252 3253 Slices can be described with two notations:
3253 3254
3254 3255 * ``N:M`` -> standard python form, means including items N...(M-1).
3255 3256 * ``N-M`` -> include items N..M (closed endpoint).
3256 3257 """
3257 3258 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3258 3259 return "\n".join(x for _, _, x in lines)
3259 3260
3260 3261 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3261 3262 """Get a code string from history, file, url, or a string or macro.
3262 3263
3263 3264 This is mainly used by magic functions.
3264 3265
3265 3266 Parameters
3266 3267 ----------
3267 3268
3268 3269 target : str
3269 3270
3270 3271 A string specifying code to retrieve. This will be tried respectively
3271 3272 as: ranges of input history (see %history for syntax), url,
3272 3273 correspnding .py file, filename, or an expression evaluating to a
3273 3274 string or Macro in the user namespace.
3274 3275
3275 3276 raw : bool
3276 3277 If true (default), retrieve raw history. Has no effect on the other
3277 3278 retrieval mechanisms.
3278 3279
3279 3280 py_only : bool (default False)
3280 3281 Only try to fetch python code, do not try alternative methods to decode file
3281 3282 if unicode fails.
3282 3283
3283 3284 Returns
3284 3285 -------
3285 3286 A string of code.
3286 3287
3287 3288 ValueError is raised if nothing is found, and TypeError if it evaluates
3288 3289 to an object of another type. In each case, .args[0] is a printable
3289 3290 message.
3290 3291 """
3291 3292 code = self.extract_input_lines(target, raw=raw) # Grab history
3292 3293 if code:
3293 3294 return code
3294 3295 utarget = unquote_filename(target)
3295 3296 try:
3296 3297 if utarget.startswith(('http://', 'https://')):
3297 3298 return openpy.read_py_url(utarget, skip_encoding_cookie=skip_encoding_cookie)
3298 3299 except UnicodeDecodeError:
3299 3300 if not py_only :
3300 3301 # Deferred import
3301 3302 try:
3302 3303 from urllib.request import urlopen # Py3
3303 3304 except ImportError:
3304 3305 from urllib import urlopen
3305 3306 response = urlopen(target)
3306 3307 return response.read().decode('latin1')
3307 3308 raise ValueError(("'%s' seem to be unreadable.") % utarget)
3308 3309
3309 3310 potential_target = [target]
3310 3311 try :
3311 3312 potential_target.insert(0,get_py_filename(target))
3312 3313 except IOError:
3313 3314 pass
3314 3315
3315 3316 for tgt in potential_target :
3316 3317 if os.path.isfile(tgt): # Read file
3317 3318 try :
3318 3319 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3319 3320 except UnicodeDecodeError :
3320 3321 if not py_only :
3321 3322 with io_open(tgt,'r', encoding='latin1') as f :
3322 3323 return f.read()
3323 3324 raise ValueError(("'%s' seem to be unreadable.") % target)
3324 3325 elif os.path.isdir(os.path.expanduser(tgt)):
3325 3326 raise ValueError("'%s' is a directory, not a regular file." % target)
3326 3327
3327 3328 if search_ns:
3328 3329 # Inspect namespace to load object source
3329 3330 object_info = self.object_inspect(target, detail_level=1)
3330 3331 if object_info['found'] and object_info['source']:
3331 3332 return object_info['source']
3332 3333
3333 3334 try: # User namespace
3334 3335 codeobj = eval(target, self.user_ns)
3335 3336 except Exception:
3336 3337 raise ValueError(("'%s' was not found in history, as a file, url, "
3337 3338 "nor in the user namespace.") % target)
3338 3339
3339 3340 if isinstance(codeobj, string_types):
3340 3341 return codeobj
3341 3342 elif isinstance(codeobj, Macro):
3342 3343 return codeobj.value
3343 3344
3344 3345 raise TypeError("%s is neither a string nor a macro." % target,
3345 3346 codeobj)
3346 3347
3347 3348 #-------------------------------------------------------------------------
3348 3349 # Things related to IPython exiting
3349 3350 #-------------------------------------------------------------------------
3350 3351 def atexit_operations(self):
3351 3352 """This will be executed at the time of exit.
3352 3353
3353 3354 Cleanup operations and saving of persistent data that is done
3354 3355 unconditionally by IPython should be performed here.
3355 3356
3356 3357 For things that may depend on startup flags or platform specifics (such
3357 3358 as having readline or not), register a separate atexit function in the
3358 3359 code that has the appropriate information, rather than trying to
3359 3360 clutter
3360 3361 """
3361 3362 # Close the history session (this stores the end time and line count)
3362 3363 # this must be *before* the tempfile cleanup, in case of temporary
3363 3364 # history db
3364 3365 self.history_manager.end_session()
3365 3366
3366 3367 # Cleanup all tempfiles and folders left around
3367 3368 for tfile in self.tempfiles:
3368 3369 try:
3369 3370 os.unlink(tfile)
3370 3371 except OSError:
3371 3372 pass
3372 3373
3373 3374 for tdir in self.tempdirs:
3374 3375 try:
3375 3376 os.rmdir(tdir)
3376 3377 except OSError:
3377 3378 pass
3378 3379
3379 3380 # Clear all user namespaces to release all references cleanly.
3380 3381 self.reset(new_session=False)
3381 3382
3382 3383 # Run user hooks
3383 3384 self.hooks.shutdown_hook()
3384 3385
3385 3386 def cleanup(self):
3386 3387 self.restore_sys_module_state()
3387 3388
3388 3389
3389 3390 class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
3390 3391 """An abstract base class for InteractiveShell."""
3391 3392
3392 3393 InteractiveShellABC.register(InteractiveShell)
@@ -1,702 +1,702 b''
1 1 # encoding: utf-8
2 2 """Magic functions for InteractiveShell.
3 3 """
4 4 from __future__ import print_function
5 5
6 6 #-----------------------------------------------------------------------------
7 7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 8 # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu>
9 9 # Copyright (C) 2008 The IPython Development Team
10 10
11 11 # Distributed under the terms of the BSD License. The full license is in
12 12 # the file COPYING, distributed as part of this software.
13 13 #-----------------------------------------------------------------------------
14 14
15 15 #-----------------------------------------------------------------------------
16 16 # Imports
17 17 #-----------------------------------------------------------------------------
18 18 # Stdlib
19 19 import os
20 20 import re
21 21 import sys
22 22 import types
23 23 from getopt import getopt, GetoptError
24 24
25 25 # Our own
26 from IPython.config.configurable import Configurable
26 from traitlets.config.configurable import Configurable
27 27 from IPython.core import oinspect
28 28 from IPython.core.error import UsageError
29 29 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
30 30 from decorator import decorator
31 31 from IPython.utils.ipstruct import Struct
32 32 from IPython.utils.process import arg_split
33 33 from IPython.utils.py3compat import string_types, iteritems
34 34 from IPython.utils.text import dedent
35 from IPython.utils.traitlets import Bool, Dict, Instance, MetaHasTraits
35 from traitlets import Bool, Dict, Instance, MetaHasTraits
36 36 from IPython.utils.warn import error
37 37
38 38 #-----------------------------------------------------------------------------
39 39 # Globals
40 40 #-----------------------------------------------------------------------------
41 41
42 42 # A dict we'll use for each class that has magics, used as temporary storage to
43 43 # pass information between the @line/cell_magic method decorators and the
44 44 # @magics_class class decorator, because the method decorators have no
45 45 # access to the class when they run. See for more details:
46 46 # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class
47 47
48 48 magics = dict(line={}, cell={})
49 49
50 50 magic_kinds = ('line', 'cell')
51 51 magic_spec = ('line', 'cell', 'line_cell')
52 52 magic_escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC2)
53 53
54 54 #-----------------------------------------------------------------------------
55 55 # Utility classes and functions
56 56 #-----------------------------------------------------------------------------
57 57
58 58 class Bunch: pass
59 59
60 60
61 61 def on_off(tag):
62 62 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
63 63 return ['OFF','ON'][tag]
64 64
65 65
66 66 def compress_dhist(dh):
67 67 """Compress a directory history into a new one with at most 20 entries.
68 68
69 69 Return a new list made from the first and last 10 elements of dhist after
70 70 removal of duplicates.
71 71 """
72 72 head, tail = dh[:-10], dh[-10:]
73 73
74 74 newhead = []
75 75 done = set()
76 76 for h in head:
77 77 if h in done:
78 78 continue
79 79 newhead.append(h)
80 80 done.add(h)
81 81
82 82 return newhead + tail
83 83
84 84
85 85 def needs_local_scope(func):
86 86 """Decorator to mark magic functions which need to local scope to run."""
87 87 func.needs_local_scope = True
88 88 return func
89 89
90 90 #-----------------------------------------------------------------------------
91 91 # Class and method decorators for registering magics
92 92 #-----------------------------------------------------------------------------
93 93
94 94 def magics_class(cls):
95 95 """Class decorator for all subclasses of the main Magics class.
96 96
97 97 Any class that subclasses Magics *must* also apply this decorator, to
98 98 ensure that all the methods that have been decorated as line/cell magics
99 99 get correctly registered in the class instance. This is necessary because
100 100 when method decorators run, the class does not exist yet, so they
101 101 temporarily store their information into a module global. Application of
102 102 this class decorator copies that global data to the class instance and
103 103 clears the global.
104 104
105 105 Obviously, this mechanism is not thread-safe, which means that the
106 106 *creation* of subclasses of Magic should only be done in a single-thread
107 107 context. Instantiation of the classes has no restrictions. Given that
108 108 these classes are typically created at IPython startup time and before user
109 109 application code becomes active, in practice this should not pose any
110 110 problems.
111 111 """
112 112 cls.registered = True
113 113 cls.magics = dict(line = magics['line'],
114 114 cell = magics['cell'])
115 115 magics['line'] = {}
116 116 magics['cell'] = {}
117 117 return cls
118 118
119 119
120 120 def record_magic(dct, magic_kind, magic_name, func):
121 121 """Utility function to store a function as a magic of a specific kind.
122 122
123 123 Parameters
124 124 ----------
125 125 dct : dict
126 126 A dictionary with 'line' and 'cell' subdicts.
127 127
128 128 magic_kind : str
129 129 Kind of magic to be stored.
130 130
131 131 magic_name : str
132 132 Key to store the magic as.
133 133
134 134 func : function
135 135 Callable object to store.
136 136 """
137 137 if magic_kind == 'line_cell':
138 138 dct['line'][magic_name] = dct['cell'][magic_name] = func
139 139 else:
140 140 dct[magic_kind][magic_name] = func
141 141
142 142
143 143 def validate_type(magic_kind):
144 144 """Ensure that the given magic_kind is valid.
145 145
146 146 Check that the given magic_kind is one of the accepted spec types (stored
147 147 in the global `magic_spec`), raise ValueError otherwise.
148 148 """
149 149 if magic_kind not in magic_spec:
150 150 raise ValueError('magic_kind must be one of %s, %s given' %
151 151 magic_kinds, magic_kind)
152 152
153 153
154 154 # The docstrings for the decorator below will be fairly similar for the two
155 155 # types (method and function), so we generate them here once and reuse the
156 156 # templates below.
157 157 _docstring_template = \
158 158 """Decorate the given {0} as {1} magic.
159 159
160 160 The decorator can be used with or without arguments, as follows.
161 161
162 162 i) without arguments: it will create a {1} magic named as the {0} being
163 163 decorated::
164 164
165 165 @deco
166 166 def foo(...)
167 167
168 168 will create a {1} magic named `foo`.
169 169
170 170 ii) with one string argument: which will be used as the actual name of the
171 171 resulting magic::
172 172
173 173 @deco('bar')
174 174 def foo(...)
175 175
176 176 will create a {1} magic named `bar`.
177 177 """
178 178
179 179 # These two are decorator factories. While they are conceptually very similar,
180 180 # there are enough differences in the details that it's simpler to have them
181 181 # written as completely standalone functions rather than trying to share code
182 182 # and make a single one with convoluted logic.
183 183
184 184 def _method_magic_marker(magic_kind):
185 185 """Decorator factory for methods in Magics subclasses.
186 186 """
187 187
188 188 validate_type(magic_kind)
189 189
190 190 # This is a closure to capture the magic_kind. We could also use a class,
191 191 # but it's overkill for just that one bit of state.
192 192 def magic_deco(arg):
193 193 call = lambda f, *a, **k: f(*a, **k)
194 194
195 195 if callable(arg):
196 196 # "Naked" decorator call (just @foo, no args)
197 197 func = arg
198 198 name = func.__name__
199 199 retval = decorator(call, func)
200 200 record_magic(magics, magic_kind, name, name)
201 201 elif isinstance(arg, string_types):
202 202 # Decorator called with arguments (@foo('bar'))
203 203 name = arg
204 204 def mark(func, *a, **kw):
205 205 record_magic(magics, magic_kind, name, func.__name__)
206 206 return decorator(call, func)
207 207 retval = mark
208 208 else:
209 209 raise TypeError("Decorator can only be called with "
210 210 "string or function")
211 211 return retval
212 212
213 213 # Ensure the resulting decorator has a usable docstring
214 214 magic_deco.__doc__ = _docstring_template.format('method', magic_kind)
215 215 return magic_deco
216 216
217 217
218 218 def _function_magic_marker(magic_kind):
219 219 """Decorator factory for standalone functions.
220 220 """
221 221 validate_type(magic_kind)
222 222
223 223 # This is a closure to capture the magic_kind. We could also use a class,
224 224 # but it's overkill for just that one bit of state.
225 225 def magic_deco(arg):
226 226 call = lambda f, *a, **k: f(*a, **k)
227 227
228 228 # Find get_ipython() in the caller's namespace
229 229 caller = sys._getframe(1)
230 230 for ns in ['f_locals', 'f_globals', 'f_builtins']:
231 231 get_ipython = getattr(caller, ns).get('get_ipython')
232 232 if get_ipython is not None:
233 233 break
234 234 else:
235 235 raise NameError('Decorator can only run in context where '
236 236 '`get_ipython` exists')
237 237
238 238 ip = get_ipython()
239 239
240 240 if callable(arg):
241 241 # "Naked" decorator call (just @foo, no args)
242 242 func = arg
243 243 name = func.__name__
244 244 ip.register_magic_function(func, magic_kind, name)
245 245 retval = decorator(call, func)
246 246 elif isinstance(arg, string_types):
247 247 # Decorator called with arguments (@foo('bar'))
248 248 name = arg
249 249 def mark(func, *a, **kw):
250 250 ip.register_magic_function(func, magic_kind, name)
251 251 return decorator(call, func)
252 252 retval = mark
253 253 else:
254 254 raise TypeError("Decorator can only be called with "
255 255 "string or function")
256 256 return retval
257 257
258 258 # Ensure the resulting decorator has a usable docstring
259 259 ds = _docstring_template.format('function', magic_kind)
260 260
261 261 ds += dedent("""
262 262 Note: this decorator can only be used in a context where IPython is already
263 263 active, so that the `get_ipython()` call succeeds. You can therefore use
264 264 it in your startup files loaded after IPython initializes, but *not* in the
265 265 IPython configuration file itself, which is executed before IPython is
266 266 fully up and running. Any file located in the `startup` subdirectory of
267 267 your configuration profile will be OK in this sense.
268 268 """)
269 269
270 270 magic_deco.__doc__ = ds
271 271 return magic_deco
272 272
273 273
274 274 # Create the actual decorators for public use
275 275
276 276 # These three are used to decorate methods in class definitions
277 277 line_magic = _method_magic_marker('line')
278 278 cell_magic = _method_magic_marker('cell')
279 279 line_cell_magic = _method_magic_marker('line_cell')
280 280
281 281 # These three decorate standalone functions and perform the decoration
282 282 # immediately. They can only run where get_ipython() works
283 283 register_line_magic = _function_magic_marker('line')
284 284 register_cell_magic = _function_magic_marker('cell')
285 285 register_line_cell_magic = _function_magic_marker('line_cell')
286 286
287 287 #-----------------------------------------------------------------------------
288 288 # Core Magic classes
289 289 #-----------------------------------------------------------------------------
290 290
291 291 class MagicsManager(Configurable):
292 292 """Object that handles all magic-related functionality for IPython.
293 293 """
294 294 # Non-configurable class attributes
295 295
296 296 # A two-level dict, first keyed by magic type, then by magic function, and
297 297 # holding the actual callable object as value. This is the dict used for
298 298 # magic function dispatch
299 299 magics = Dict
300 300
301 301 # A registry of the original objects that we've been given holding magics.
302 302 registry = Dict
303 303
304 304 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
305 305
306 306 auto_magic = Bool(True, config=True, help=
307 307 "Automatically call line magics without requiring explicit % prefix")
308 308
309 309 def _auto_magic_changed(self, name, value):
310 310 self.shell.automagic = value
311 311
312 312 _auto_status = [
313 313 'Automagic is OFF, % prefix IS needed for line magics.',
314 314 'Automagic is ON, % prefix IS NOT needed for line magics.']
315 315
316 316 user_magics = Instance('IPython.core.magics.UserMagics', allow_none=True)
317 317
318 318 def __init__(self, shell=None, config=None, user_magics=None, **traits):
319 319
320 320 super(MagicsManager, self).__init__(shell=shell, config=config,
321 321 user_magics=user_magics, **traits)
322 322 self.magics = dict(line={}, cell={})
323 323 # Let's add the user_magics to the registry for uniformity, so *all*
324 324 # registered magic containers can be found there.
325 325 self.registry[user_magics.__class__.__name__] = user_magics
326 326
327 327 def auto_status(self):
328 328 """Return descriptive string with automagic status."""
329 329 return self._auto_status[self.auto_magic]
330 330
331 331 def lsmagic(self):
332 332 """Return a dict of currently available magic functions.
333 333
334 334 The return dict has the keys 'line' and 'cell', corresponding to the
335 335 two types of magics we support. Each value is a list of names.
336 336 """
337 337 return self.magics
338 338
339 339 def lsmagic_docs(self, brief=False, missing=''):
340 340 """Return dict of documentation of magic functions.
341 341
342 342 The return dict has the keys 'line' and 'cell', corresponding to the
343 343 two types of magics we support. Each value is a dict keyed by magic
344 344 name whose value is the function docstring. If a docstring is
345 345 unavailable, the value of `missing` is used instead.
346 346
347 347 If brief is True, only the first line of each docstring will be returned.
348 348 """
349 349 docs = {}
350 350 for m_type in self.magics:
351 351 m_docs = {}
352 352 for m_name, m_func in iteritems(self.magics[m_type]):
353 353 if m_func.__doc__:
354 354 if brief:
355 355 m_docs[m_name] = m_func.__doc__.split('\n', 1)[0]
356 356 else:
357 357 m_docs[m_name] = m_func.__doc__.rstrip()
358 358 else:
359 359 m_docs[m_name] = missing
360 360 docs[m_type] = m_docs
361 361 return docs
362 362
363 363 def register(self, *magic_objects):
364 364 """Register one or more instances of Magics.
365 365
366 366 Take one or more classes or instances of classes that subclass the main
367 367 `core.Magic` class, and register them with IPython to use the magic
368 368 functions they provide. The registration process will then ensure that
369 369 any methods that have decorated to provide line and/or cell magics will
370 370 be recognized with the `%x`/`%%x` syntax as a line/cell magic
371 371 respectively.
372 372
373 373 If classes are given, they will be instantiated with the default
374 374 constructor. If your classes need a custom constructor, you should
375 375 instanitate them first and pass the instance.
376 376
377 377 The provided arguments can be an arbitrary mix of classes and instances.
378 378
379 379 Parameters
380 380 ----------
381 381 magic_objects : one or more classes or instances
382 382 """
383 383 # Start by validating them to ensure they have all had their magic
384 384 # methods registered at the instance level
385 385 for m in magic_objects:
386 386 if not m.registered:
387 387 raise ValueError("Class of magics %r was constructed without "
388 388 "the @register_magics class decorator")
389 389 if type(m) in (type, MetaHasTraits):
390 390 # If we're given an uninstantiated class
391 391 m = m(shell=self.shell)
392 392
393 393 # Now that we have an instance, we can register it and update the
394 394 # table of callables
395 395 self.registry[m.__class__.__name__] = m
396 396 for mtype in magic_kinds:
397 397 self.magics[mtype].update(m.magics[mtype])
398 398
399 399 def register_function(self, func, magic_kind='line', magic_name=None):
400 400 """Expose a standalone function as magic function for IPython.
401 401
402 402 This will create an IPython magic (line, cell or both) from a
403 403 standalone function. The functions should have the following
404 404 signatures:
405 405
406 406 * For line magics: `def f(line)`
407 407 * For cell magics: `def f(line, cell)`
408 408 * For a function that does both: `def f(line, cell=None)`
409 409
410 410 In the latter case, the function will be called with `cell==None` when
411 411 invoked as `%f`, and with cell as a string when invoked as `%%f`.
412 412
413 413 Parameters
414 414 ----------
415 415 func : callable
416 416 Function to be registered as a magic.
417 417
418 418 magic_kind : str
419 419 Kind of magic, one of 'line', 'cell' or 'line_cell'
420 420
421 421 magic_name : optional str
422 422 If given, the name the magic will have in the IPython namespace. By
423 423 default, the name of the function itself is used.
424 424 """
425 425
426 426 # Create the new method in the user_magics and register it in the
427 427 # global table
428 428 validate_type(magic_kind)
429 429 magic_name = func.__name__ if magic_name is None else magic_name
430 430 setattr(self.user_magics, magic_name, func)
431 431 record_magic(self.magics, magic_kind, magic_name, func)
432 432
433 433 def define_magic(self, name, func):
434 434 """[Deprecated] Expose own function as magic function for IPython.
435 435
436 436 Example::
437 437
438 438 def foo_impl(self, parameter_s=''):
439 439 'My very own magic!. (Use docstrings, IPython reads them).'
440 440 print 'Magic function. Passed parameter is between < >:'
441 441 print '<%s>' % parameter_s
442 442 print 'The self object is:', self
443 443
444 444 ip.define_magic('foo',foo_impl)
445 445 """
446 446 meth = types.MethodType(func, self.user_magics)
447 447 setattr(self.user_magics, name, meth)
448 448 record_magic(self.magics, 'line', name, meth)
449 449
450 450 def register_alias(self, alias_name, magic_name, magic_kind='line'):
451 451 """Register an alias to a magic function.
452 452
453 453 The alias is an instance of :class:`MagicAlias`, which holds the
454 454 name and kind of the magic it should call. Binding is done at
455 455 call time, so if the underlying magic function is changed the alias
456 456 will call the new function.
457 457
458 458 Parameters
459 459 ----------
460 460 alias_name : str
461 461 The name of the magic to be registered.
462 462
463 463 magic_name : str
464 464 The name of an existing magic.
465 465
466 466 magic_kind : str
467 467 Kind of magic, one of 'line' or 'cell'
468 468 """
469 469
470 470 # `validate_type` is too permissive, as it allows 'line_cell'
471 471 # which we do not handle.
472 472 if magic_kind not in magic_kinds:
473 473 raise ValueError('magic_kind must be one of %s, %s given' %
474 474 magic_kinds, magic_kind)
475 475
476 476 alias = MagicAlias(self.shell, magic_name, magic_kind)
477 477 setattr(self.user_magics, alias_name, alias)
478 478 record_magic(self.magics, magic_kind, alias_name, alias)
479 479
480 480 # Key base class that provides the central functionality for magics.
481 481
482 482
483 483 class Magics(Configurable):
484 484 """Base class for implementing magic functions.
485 485
486 486 Shell functions which can be reached as %function_name. All magic
487 487 functions should accept a string, which they can parse for their own
488 488 needs. This can make some functions easier to type, eg `%cd ../`
489 489 vs. `%cd("../")`
490 490
491 491 Classes providing magic functions need to subclass this class, and they
492 492 MUST:
493 493
494 494 - Use the method decorators `@line_magic` and `@cell_magic` to decorate
495 495 individual methods as magic functions, AND
496 496
497 497 - Use the class decorator `@magics_class` to ensure that the magic
498 498 methods are properly registered at the instance level upon instance
499 499 initialization.
500 500
501 501 See :mod:`magic_functions` for examples of actual implementation classes.
502 502 """
503 503 # Dict holding all command-line options for each magic.
504 504 options_table = None
505 505 # Dict for the mapping of magic names to methods, set by class decorator
506 506 magics = None
507 507 # Flag to check that the class decorator was properly applied
508 508 registered = False
509 509 # Instance of IPython shell
510 510 shell = None
511 511
512 512 def __init__(self, shell=None, **kwargs):
513 513 if not(self.__class__.registered):
514 514 raise ValueError('Magics subclass without registration - '
515 515 'did you forget to apply @magics_class?')
516 516 if shell is not None:
517 517 if hasattr(shell, 'configurables'):
518 518 shell.configurables.append(self)
519 519 if hasattr(shell, 'config'):
520 520 kwargs.setdefault('parent', shell)
521 521 kwargs['shell'] = shell
522 522
523 523 self.shell = shell
524 524 self.options_table = {}
525 525 # The method decorators are run when the instance doesn't exist yet, so
526 526 # they can only record the names of the methods they are supposed to
527 527 # grab. Only now, that the instance exists, can we create the proper
528 528 # mapping to bound methods. So we read the info off the original names
529 529 # table and replace each method name by the actual bound method.
530 530 # But we mustn't clobber the *class* mapping, in case of multiple instances.
531 531 class_magics = self.magics
532 532 self.magics = {}
533 533 for mtype in magic_kinds:
534 534 tab = self.magics[mtype] = {}
535 535 cls_tab = class_magics[mtype]
536 536 for magic_name, meth_name in iteritems(cls_tab):
537 537 if isinstance(meth_name, string_types):
538 538 # it's a method name, grab it
539 539 tab[magic_name] = getattr(self, meth_name)
540 540 else:
541 541 # it's the real thing
542 542 tab[magic_name] = meth_name
543 543 # Configurable **needs** to be initiated at the end or the config
544 544 # magics get screwed up.
545 545 super(Magics, self).__init__(**kwargs)
546 546
547 547 def arg_err(self,func):
548 548 """Print docstring if incorrect arguments were passed"""
549 549 print('Error in arguments:')
550 550 print(oinspect.getdoc(func))
551 551
552 552 def format_latex(self, strng):
553 553 """Format a string for latex inclusion."""
554 554
555 555 # Characters that need to be escaped for latex:
556 556 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
557 557 # Magic command names as headers:
558 558 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
559 559 re.MULTILINE)
560 560 # Magic commands
561 561 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
562 562 re.MULTILINE)
563 563 # Paragraph continue
564 564 par_re = re.compile(r'\\$',re.MULTILINE)
565 565
566 566 # The "\n" symbol
567 567 newline_re = re.compile(r'\\n')
568 568
569 569 # Now build the string for output:
570 570 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
571 571 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
572 572 strng)
573 573 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
574 574 strng = par_re.sub(r'\\\\',strng)
575 575 strng = escape_re.sub(r'\\\1',strng)
576 576 strng = newline_re.sub(r'\\textbackslash{}n',strng)
577 577 return strng
578 578
579 579 def parse_options(self, arg_str, opt_str, *long_opts, **kw):
580 580 """Parse options passed to an argument string.
581 581
582 582 The interface is similar to that of :func:`getopt.getopt`, but it
583 583 returns a :class:`~IPython.utils.struct.Struct` with the options as keys
584 584 and the stripped argument string still as a string.
585 585
586 586 arg_str is quoted as a true sys.argv vector by using shlex.split.
587 587 This allows us to easily expand variables, glob files, quote
588 588 arguments, etc.
589 589
590 590 Parameters
591 591 ----------
592 592
593 593 arg_str : str
594 594 The arguments to parse.
595 595
596 596 opt_str : str
597 597 The options specification.
598 598
599 599 mode : str, default 'string'
600 600 If given as 'list', the argument string is returned as a list (split
601 601 on whitespace) instead of a string.
602 602
603 603 list_all : bool, default False
604 604 Put all option values in lists. Normally only options
605 605 appearing more than once are put in a list.
606 606
607 607 posix : bool, default True
608 608 Whether to split the input line in POSIX mode or not, as per the
609 609 conventions outlined in the :mod:`shlex` module from the standard
610 610 library.
611 611 """
612 612
613 613 # inject default options at the beginning of the input line
614 614 caller = sys._getframe(1).f_code.co_name
615 615 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
616 616
617 617 mode = kw.get('mode','string')
618 618 if mode not in ['string','list']:
619 619 raise ValueError('incorrect mode given: %s' % mode)
620 620 # Get options
621 621 list_all = kw.get('list_all',0)
622 622 posix = kw.get('posix', os.name == 'posix')
623 623 strict = kw.get('strict', True)
624 624
625 625 # Check if we have more than one argument to warrant extra processing:
626 626 odict = {} # Dictionary with options
627 627 args = arg_str.split()
628 628 if len(args) >= 1:
629 629 # If the list of inputs only has 0 or 1 thing in it, there's no
630 630 # need to look for options
631 631 argv = arg_split(arg_str, posix, strict)
632 632 # Do regular option processing
633 633 try:
634 634 opts,args = getopt(argv, opt_str, long_opts)
635 635 except GetoptError as e:
636 636 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
637 637 " ".join(long_opts)))
638 638 for o,a in opts:
639 639 if o.startswith('--'):
640 640 o = o[2:]
641 641 else:
642 642 o = o[1:]
643 643 try:
644 644 odict[o].append(a)
645 645 except AttributeError:
646 646 odict[o] = [odict[o],a]
647 647 except KeyError:
648 648 if list_all:
649 649 odict[o] = [a]
650 650 else:
651 651 odict[o] = a
652 652
653 653 # Prepare opts,args for return
654 654 opts = Struct(odict)
655 655 if mode == 'string':
656 656 args = ' '.join(args)
657 657
658 658 return opts,args
659 659
660 660 def default_option(self, fn, optstr):
661 661 """Make an entry in the options_table for fn, with value optstr"""
662 662
663 663 if fn not in self.lsmagic():
664 664 error("%s is not a magic function" % fn)
665 665 self.options_table[fn] = optstr
666 666
667 667
668 668 class MagicAlias(object):
669 669 """An alias to another magic function.
670 670
671 671 An alias is determined by its magic name and magic kind. Lookup
672 672 is done at call time, so if the underlying magic changes the alias
673 673 will call the new function.
674 674
675 675 Use the :meth:`MagicsManager.register_alias` method or the
676 676 `%alias_magic` magic function to create and register a new alias.
677 677 """
678 678 def __init__(self, shell, magic_name, magic_kind):
679 679 self.shell = shell
680 680 self.magic_name = magic_name
681 681 self.magic_kind = magic_kind
682 682
683 683 self.pretty_target = '%s%s' % (magic_escapes[self.magic_kind], self.magic_name)
684 684 self.__doc__ = "Alias for `%s`." % self.pretty_target
685 685
686 686 self._in_call = False
687 687
688 688 def __call__(self, *args, **kwargs):
689 689 """Call the magic alias."""
690 690 fn = self.shell.find_magic(self.magic_name, self.magic_kind)
691 691 if fn is None:
692 692 raise UsageError("Magic `%s` not found." % self.pretty_target)
693 693
694 694 # Protect against infinite recursion.
695 695 if self._in_call:
696 696 raise UsageError("Infinite recursion detected; "
697 697 "magic aliases cannot call themselves.")
698 698 self._in_call = True
699 699 try:
700 700 return fn(*args, **kwargs)
701 701 finally:
702 702 self._in_call = False
@@ -1,613 +1,613 b''
1 1 """Implementation of basic magic functions."""
2 2
3 3 from __future__ import print_function
4 4
5 5 import io
6 6 import json
7 7 import sys
8 8 from pprint import pformat
9 9
10 10 from IPython.core import magic_arguments, page
11 11 from IPython.core.error import UsageError
12 12 from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes
13 13 from IPython.utils.text import format_screen, dedent, indent
14 14 from IPython.testing.skipdoctest import skip_doctest
15 15 from IPython.utils.ipstruct import Struct
16 16 from IPython.utils.path import unquote_filename
17 17 from IPython.utils.py3compat import unicode_type
18 18 from IPython.utils.warn import warn, error
19 19
20 20
21 21 class MagicsDisplay(object):
22 22 def __init__(self, magics_manager):
23 23 self.magics_manager = magics_manager
24 24
25 25 def _lsmagic(self):
26 26 """The main implementation of the %lsmagic"""
27 27 mesc = magic_escapes['line']
28 28 cesc = magic_escapes['cell']
29 29 mman = self.magics_manager
30 30 magics = mman.lsmagic()
31 31 out = ['Available line magics:',
32 32 mesc + (' '+mesc).join(sorted(magics['line'])),
33 33 '',
34 34 'Available cell magics:',
35 35 cesc + (' '+cesc).join(sorted(magics['cell'])),
36 36 '',
37 37 mman.auto_status()]
38 38 return '\n'.join(out)
39 39
40 40 def _repr_pretty_(self, p, cycle):
41 41 p.text(self._lsmagic())
42 42
43 43 def __str__(self):
44 44 return self._lsmagic()
45 45
46 46 def _jsonable(self):
47 47 """turn magics dict into jsonable dict of the same structure
48 48
49 49 replaces object instances with their class names as strings
50 50 """
51 51 magic_dict = {}
52 52 mman = self.magics_manager
53 53 magics = mman.lsmagic()
54 54 for key, subdict in magics.items():
55 55 d = {}
56 56 magic_dict[key] = d
57 57 for name, obj in subdict.items():
58 58 try:
59 59 classname = obj.__self__.__class__.__name__
60 60 except AttributeError:
61 61 classname = 'Other'
62 62
63 63 d[name] = classname
64 64 return magic_dict
65 65
66 66 def _repr_json_(self):
67 67 return self._jsonable()
68 68
69 69
70 70 @magics_class
71 71 class BasicMagics(Magics):
72 72 """Magics that provide central IPython functionality.
73 73
74 74 These are various magics that don't fit into specific categories but that
75 75 are all part of the base 'IPython experience'."""
76 76
77 77 @magic_arguments.magic_arguments()
78 78 @magic_arguments.argument(
79 79 '-l', '--line', action='store_true',
80 80 help="""Create a line magic alias."""
81 81 )
82 82 @magic_arguments.argument(
83 83 '-c', '--cell', action='store_true',
84 84 help="""Create a cell magic alias."""
85 85 )
86 86 @magic_arguments.argument(
87 87 'name',
88 88 help="""Name of the magic to be created."""
89 89 )
90 90 @magic_arguments.argument(
91 91 'target',
92 92 help="""Name of the existing line or cell magic."""
93 93 )
94 94 @line_magic
95 95 def alias_magic(self, line=''):
96 96 """Create an alias for an existing line or cell magic.
97 97
98 98 Examples
99 99 --------
100 100 ::
101 101
102 102 In [1]: %alias_magic t timeit
103 103 Created `%t` as an alias for `%timeit`.
104 104 Created `%%t` as an alias for `%%timeit`.
105 105
106 106 In [2]: %t -n1 pass
107 107 1 loops, best of 3: 954 ns per loop
108 108
109 109 In [3]: %%t -n1
110 110 ...: pass
111 111 ...:
112 112 1 loops, best of 3: 954 ns per loop
113 113
114 114 In [4]: %alias_magic --cell whereami pwd
115 115 UsageError: Cell magic function `%%pwd` not found.
116 116 In [5]: %alias_magic --line whereami pwd
117 117 Created `%whereami` as an alias for `%pwd`.
118 118
119 119 In [6]: %whereami
120 120 Out[6]: u'/home/testuser'
121 121 """
122 122 args = magic_arguments.parse_argstring(self.alias_magic, line)
123 123 shell = self.shell
124 124 mman = self.shell.magics_manager
125 125 escs = ''.join(magic_escapes.values())
126 126
127 127 target = args.target.lstrip(escs)
128 128 name = args.name.lstrip(escs)
129 129
130 130 # Find the requested magics.
131 131 m_line = shell.find_magic(target, 'line')
132 132 m_cell = shell.find_magic(target, 'cell')
133 133 if args.line and m_line is None:
134 134 raise UsageError('Line magic function `%s%s` not found.' %
135 135 (magic_escapes['line'], target))
136 136 if args.cell and m_cell is None:
137 137 raise UsageError('Cell magic function `%s%s` not found.' %
138 138 (magic_escapes['cell'], target))
139 139
140 140 # If --line and --cell are not specified, default to the ones
141 141 # that are available.
142 142 if not args.line and not args.cell:
143 143 if not m_line and not m_cell:
144 144 raise UsageError(
145 145 'No line or cell magic with name `%s` found.' % target
146 146 )
147 147 args.line = bool(m_line)
148 148 args.cell = bool(m_cell)
149 149
150 150 if args.line:
151 151 mman.register_alias(name, target, 'line')
152 152 print('Created `%s%s` as an alias for `%s%s`.' % (
153 153 magic_escapes['line'], name,
154 154 magic_escapes['line'], target))
155 155
156 156 if args.cell:
157 157 mman.register_alias(name, target, 'cell')
158 158 print('Created `%s%s` as an alias for `%s%s`.' % (
159 159 magic_escapes['cell'], name,
160 160 magic_escapes['cell'], target))
161 161
162 162 @line_magic
163 163 def lsmagic(self, parameter_s=''):
164 164 """List currently available magic functions."""
165 165 return MagicsDisplay(self.shell.magics_manager)
166 166
167 167 def _magic_docs(self, brief=False, rest=False):
168 168 """Return docstrings from magic functions."""
169 169 mman = self.shell.magics_manager
170 170 docs = mman.lsmagic_docs(brief, missing='No documentation')
171 171
172 172 if rest:
173 173 format_string = '**%s%s**::\n\n%s\n\n'
174 174 else:
175 175 format_string = '%s%s:\n%s\n'
176 176
177 177 return ''.join(
178 178 [format_string % (magic_escapes['line'], fname,
179 179 indent(dedent(fndoc)))
180 180 for fname, fndoc in sorted(docs['line'].items())]
181 181 +
182 182 [format_string % (magic_escapes['cell'], fname,
183 183 indent(dedent(fndoc)))
184 184 for fname, fndoc in sorted(docs['cell'].items())]
185 185 )
186 186
187 187 @line_magic
188 188 def magic(self, parameter_s=''):
189 189 """Print information about the magic function system.
190 190
191 191 Supported formats: -latex, -brief, -rest
192 192 """
193 193
194 194 mode = ''
195 195 try:
196 196 mode = parameter_s.split()[0][1:]
197 197 if mode == 'rest':
198 198 rest_docs = []
199 199 except IndexError:
200 200 pass
201 201
202 202 brief = (mode == 'brief')
203 203 rest = (mode == 'rest')
204 204 magic_docs = self._magic_docs(brief, rest)
205 205
206 206 if mode == 'latex':
207 207 print(self.format_latex(magic_docs))
208 208 return
209 209 else:
210 210 magic_docs = format_screen(magic_docs)
211 211
212 212 out = ["""
213 213 IPython's 'magic' functions
214 214 ===========================
215 215
216 216 The magic function system provides a series of functions which allow you to
217 217 control the behavior of IPython itself, plus a lot of system-type
218 218 features. There are two kinds of magics, line-oriented and cell-oriented.
219 219
220 220 Line magics are prefixed with the % character and work much like OS
221 221 command-line calls: they get as an argument the rest of the line, where
222 222 arguments are passed without parentheses or quotes. For example, this will
223 223 time the given statement::
224 224
225 225 %timeit range(1000)
226 226
227 227 Cell magics are prefixed with a double %%, and they are functions that get as
228 228 an argument not only the rest of the line, but also the lines below it in a
229 229 separate argument. These magics are called with two arguments: the rest of the
230 230 call line and the body of the cell, consisting of the lines below the first.
231 231 For example::
232 232
233 233 %%timeit x = numpy.random.randn((100, 100))
234 234 numpy.linalg.svd(x)
235 235
236 236 will time the execution of the numpy svd routine, running the assignment of x
237 237 as part of the setup phase, which is not timed.
238 238
239 239 In a line-oriented client (the terminal or Qt console IPython), starting a new
240 240 input with %% will automatically enter cell mode, and IPython will continue
241 241 reading input until a blank line is given. In the notebook, simply type the
242 242 whole cell as one entity, but keep in mind that the %% escape can only be at
243 243 the very start of the cell.
244 244
245 245 NOTE: If you have 'automagic' enabled (via the command line option or with the
246 246 %automagic function), you don't need to type in the % explicitly for line
247 247 magics; cell magics always require an explicit '%%' escape. By default,
248 248 IPython ships with automagic on, so you should only rarely need the % escape.
249 249
250 250 Example: typing '%cd mydir' (without the quotes) changes you working directory
251 251 to 'mydir', if it exists.
252 252
253 253 For a list of the available magic functions, use %lsmagic. For a description
254 254 of any of them, type %magic_name?, e.g. '%cd?'.
255 255
256 256 Currently the magic system has the following functions:""",
257 257 magic_docs,
258 258 "Summary of magic functions (from %slsmagic):" % magic_escapes['line'],
259 259 str(self.lsmagic()),
260 260 ]
261 261 page.page('\n'.join(out))
262 262
263 263
264 264 @line_magic
265 265 def page(self, parameter_s=''):
266 266 """Pretty print the object and display it through a pager.
267 267
268 268 %page [options] OBJECT
269 269
270 270 If no object is given, use _ (last output).
271 271
272 272 Options:
273 273
274 274 -r: page str(object), don't pretty-print it."""
275 275
276 276 # After a function contributed by Olivier Aubert, slightly modified.
277 277
278 278 # Process options/args
279 279 opts, args = self.parse_options(parameter_s, 'r')
280 280 raw = 'r' in opts
281 281
282 282 oname = args and args or '_'
283 283 info = self.shell._ofind(oname)
284 284 if info['found']:
285 285 txt = (raw and str or pformat)( info['obj'] )
286 286 page.page(txt)
287 287 else:
288 288 print('Object `%s` not found' % oname)
289 289
290 290 @line_magic
291 291 def profile(self, parameter_s=''):
292 292 """Print your currently active IPython profile.
293 293
294 294 See Also
295 295 --------
296 296 prun : run code using the Python profiler
297 297 (:meth:`~IPython.core.magics.execution.ExecutionMagics.prun`)
298 298 """
299 299 warn("%profile is now deprecated. Please use get_ipython().profile instead.")
300 300 from IPython.core.application import BaseIPythonApplication
301 301 if BaseIPythonApplication.initialized():
302 302 print(BaseIPythonApplication.instance().profile)
303 303 else:
304 304 error("profile is an application-level value, but you don't appear to be in an IPython application")
305 305
306 306 @line_magic
307 307 def pprint(self, parameter_s=''):
308 308 """Toggle pretty printing on/off."""
309 309 ptformatter = self.shell.display_formatter.formatters['text/plain']
310 310 ptformatter.pprint = bool(1 - ptformatter.pprint)
311 311 print('Pretty printing has been turned',
312 312 ['OFF','ON'][ptformatter.pprint])
313 313
314 314 @line_magic
315 315 def colors(self, parameter_s=''):
316 316 """Switch color scheme for prompts, info system and exception handlers.
317 317
318 318 Currently implemented schemes: NoColor, Linux, LightBG.
319 319
320 320 Color scheme names are not case-sensitive.
321 321
322 322 Examples
323 323 --------
324 324 To get a plain black and white terminal::
325 325
326 326 %colors nocolor
327 327 """
328 328 def color_switch_err(name):
329 329 warn('Error changing %s color schemes.\n%s' %
330 330 (name, sys.exc_info()[1]))
331 331
332 332
333 333 new_scheme = parameter_s.strip()
334 334 if not new_scheme:
335 335 raise UsageError(
336 336 "%colors: you must specify a color scheme. See '%colors?'")
337 337 # local shortcut
338 338 shell = self.shell
339 339
340 340 import IPython.utils.rlineimpl as readline
341 341
342 342 if not shell.colors_force and \
343 343 not readline.have_readline and \
344 344 (sys.platform == "win32" or sys.platform == "cli"):
345 345 msg = """\
346 346 Proper color support under MS Windows requires the pyreadline library.
347 347 You can find it at:
348 348 http://ipython.org/pyreadline.html
349 349
350 350 Defaulting color scheme to 'NoColor'"""
351 351 new_scheme = 'NoColor'
352 352 warn(msg)
353 353
354 354 # readline option is 0
355 355 if not shell.colors_force and not shell.has_readline:
356 356 new_scheme = 'NoColor'
357 357
358 358 # Set prompt colors
359 359 try:
360 360 shell.prompt_manager.color_scheme = new_scheme
361 361 except:
362 362 color_switch_err('prompt')
363 363 else:
364 364 shell.colors = \
365 365 shell.prompt_manager.color_scheme_table.active_scheme_name
366 366 # Set exception colors
367 367 try:
368 368 shell.InteractiveTB.set_colors(scheme = new_scheme)
369 369 shell.SyntaxTB.set_colors(scheme = new_scheme)
370 370 except:
371 371 color_switch_err('exception')
372 372
373 373 # Set info (for 'object?') colors
374 374 if shell.color_info:
375 375 try:
376 376 shell.inspector.set_active_scheme(new_scheme)
377 377 except:
378 378 color_switch_err('object inspector')
379 379 else:
380 380 shell.inspector.set_active_scheme('NoColor')
381 381
382 382 @line_magic
383 383 def xmode(self, parameter_s=''):
384 384 """Switch modes for the exception handlers.
385 385
386 386 Valid modes: Plain, Context and Verbose.
387 387
388 388 If called without arguments, acts as a toggle."""
389 389
390 390 def xmode_switch_err(name):
391 391 warn('Error changing %s exception modes.\n%s' %
392 392 (name,sys.exc_info()[1]))
393 393
394 394 shell = self.shell
395 395 new_mode = parameter_s.strip().capitalize()
396 396 try:
397 397 shell.InteractiveTB.set_mode(mode=new_mode)
398 398 print('Exception reporting mode:',shell.InteractiveTB.mode)
399 399 except:
400 400 xmode_switch_err('user')
401 401
402 402 @line_magic
403 403 def quickref(self,arg):
404 404 """ Show a quick reference sheet """
405 405 from IPython.core.usage import quick_reference
406 406 qr = quick_reference + self._magic_docs(brief=True)
407 407 page.page(qr)
408 408
409 409 @line_magic
410 410 def doctest_mode(self, parameter_s=''):
411 411 """Toggle doctest mode on and off.
412 412
413 413 This mode is intended to make IPython behave as much as possible like a
414 414 plain Python shell, from the perspective of how its prompts, exceptions
415 415 and output look. This makes it easy to copy and paste parts of a
416 416 session into doctests. It does so by:
417 417
418 418 - Changing the prompts to the classic ``>>>`` ones.
419 419 - Changing the exception reporting mode to 'Plain'.
420 420 - Disabling pretty-printing of output.
421 421
422 422 Note that IPython also supports the pasting of code snippets that have
423 423 leading '>>>' and '...' prompts in them. This means that you can paste
424 424 doctests from files or docstrings (even if they have leading
425 425 whitespace), and the code will execute correctly. You can then use
426 426 '%history -t' to see the translated history; this will give you the
427 427 input after removal of all the leading prompts and whitespace, which
428 428 can be pasted back into an editor.
429 429
430 430 With these features, you can switch into this mode easily whenever you
431 431 need to do testing and changes to doctests, without having to leave
432 432 your existing IPython session.
433 433 """
434 434
435 435 # Shorthands
436 436 shell = self.shell
437 437 pm = shell.prompt_manager
438 438 meta = shell.meta
439 439 disp_formatter = self.shell.display_formatter
440 440 ptformatter = disp_formatter.formatters['text/plain']
441 441 # dstore is a data store kept in the instance metadata bag to track any
442 442 # changes we make, so we can undo them later.
443 443 dstore = meta.setdefault('doctest_mode',Struct())
444 444 save_dstore = dstore.setdefault
445 445
446 446 # save a few values we'll need to recover later
447 447 mode = save_dstore('mode',False)
448 448 save_dstore('rc_pprint',ptformatter.pprint)
449 449 save_dstore('xmode',shell.InteractiveTB.mode)
450 450 save_dstore('rc_separate_out',shell.separate_out)
451 451 save_dstore('rc_separate_out2',shell.separate_out2)
452 452 save_dstore('rc_prompts_pad_left',pm.justify)
453 453 save_dstore('rc_separate_in',shell.separate_in)
454 454 save_dstore('rc_active_types',disp_formatter.active_types)
455 455 save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template))
456 456
457 457 if mode == False:
458 458 # turn on
459 459 pm.in_template = '>>> '
460 460 pm.in2_template = '... '
461 461 pm.out_template = ''
462 462
463 463 # Prompt separators like plain python
464 464 shell.separate_in = ''
465 465 shell.separate_out = ''
466 466 shell.separate_out2 = ''
467 467
468 468 pm.justify = False
469 469
470 470 ptformatter.pprint = False
471 471 disp_formatter.active_types = ['text/plain']
472 472
473 473 shell.magic('xmode Plain')
474 474 else:
475 475 # turn off
476 476 pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates
477 477
478 478 shell.separate_in = dstore.rc_separate_in
479 479
480 480 shell.separate_out = dstore.rc_separate_out
481 481 shell.separate_out2 = dstore.rc_separate_out2
482 482
483 483 pm.justify = dstore.rc_prompts_pad_left
484 484
485 485 ptformatter.pprint = dstore.rc_pprint
486 486 disp_formatter.active_types = dstore.rc_active_types
487 487
488 488 shell.magic('xmode ' + dstore.xmode)
489 489
490 490 # Store new mode and inform
491 491 dstore.mode = bool(1-int(mode))
492 492 mode_label = ['OFF','ON'][dstore.mode]
493 493 print('Doctest mode is:', mode_label)
494 494
495 495 @line_magic
496 496 def gui(self, parameter_s=''):
497 497 """Enable or disable IPython GUI event loop integration.
498 498
499 499 %gui [GUINAME]
500 500
501 501 This magic replaces IPython's threaded shells that were activated
502 502 using the (pylab/wthread/etc.) command line flags. GUI toolkits
503 503 can now be enabled at runtime and keyboard
504 504 interrupts should work without any problems. The following toolkits
505 505 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
506 506
507 507 %gui wx # enable wxPython event loop integration
508 508 %gui qt4|qt # enable PyQt4 event loop integration
509 509 %gui qt5 # enable PyQt5 event loop integration
510 510 %gui gtk # enable PyGTK event loop integration
511 511 %gui gtk3 # enable Gtk3 event loop integration
512 512 %gui tk # enable Tk event loop integration
513 513 %gui osx # enable Cocoa event loop integration
514 514 # (requires %matplotlib 1.1)
515 515 %gui # disable all event loop integration
516 516
517 517 WARNING: after any of these has been called you can simply create
518 518 an application object, but DO NOT start the event loop yourself, as
519 519 we have already handled that.
520 520 """
521 521 opts, arg = self.parse_options(parameter_s, '')
522 522 if arg=='': arg = None
523 523 try:
524 524 return self.shell.enable_gui(arg)
525 525 except Exception as e:
526 526 # print simple error message, rather than traceback if we can't
527 527 # hook up the GUI
528 528 error(str(e))
529 529
530 530 @skip_doctest
531 531 @line_magic
532 532 def precision(self, s=''):
533 533 """Set floating point precision for pretty printing.
534 534
535 535 Can set either integer precision or a format string.
536 536
537 537 If numpy has been imported and precision is an int,
538 538 numpy display precision will also be set, via ``numpy.set_printoptions``.
539 539
540 540 If no argument is given, defaults will be restored.
541 541
542 542 Examples
543 543 --------
544 544 ::
545 545
546 546 In [1]: from math import pi
547 547
548 548 In [2]: %precision 3
549 549 Out[2]: u'%.3f'
550 550
551 551 In [3]: pi
552 552 Out[3]: 3.142
553 553
554 554 In [4]: %precision %i
555 555 Out[4]: u'%i'
556 556
557 557 In [5]: pi
558 558 Out[5]: 3
559 559
560 560 In [6]: %precision %e
561 561 Out[6]: u'%e'
562 562
563 563 In [7]: pi**10
564 564 Out[7]: 9.364805e+04
565 565
566 566 In [8]: %precision
567 567 Out[8]: u'%r'
568 568
569 569 In [9]: pi**10
570 570 Out[9]: 93648.047476082982
571 571 """
572 572 ptformatter = self.shell.display_formatter.formatters['text/plain']
573 573 ptformatter.float_precision = s
574 574 return ptformatter.float_format
575 575
576 576 @magic_arguments.magic_arguments()
577 577 @magic_arguments.argument(
578 578 '-e', '--export', action='store_true', default=False,
579 579 help='Export IPython history as a notebook. The filename argument '
580 580 'is used to specify the notebook name and format. For example '
581 581 'a filename of notebook.ipynb will result in a notebook name '
582 582 'of "notebook" and a format of "json". Likewise using a ".py" '
583 583 'file extension will write the notebook as a Python script'
584 584 )
585 585 @magic_arguments.argument(
586 586 'filename', type=unicode_type,
587 587 help='Notebook name or filename'
588 588 )
589 589 @line_magic
590 590 def notebook(self, s):
591 591 """Export and convert IPython notebooks.
592 592
593 593 This function can export the current IPython history to a notebook file.
594 594 For example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb".
595 595 To export the history to "foo.py" do "%notebook -e foo.py".
596 596 """
597 597 args = magic_arguments.parse_argstring(self.notebook, s)
598 598
599 from IPython.nbformat import write, v4
599 from jupyter_nbformat import write, v4
600 600 args.filename = unquote_filename(args.filename)
601 601 if args.export:
602 602 cells = []
603 603 hist = list(self.shell.history_manager.get_range())
604 604 if(len(hist)<=1):
605 605 raise ValueError('History is empty, cannot export')
606 606 for session, execution_count, source in hist[:-1]:
607 607 cells.append(v4.new_code_cell(
608 608 execution_count=execution_count,
609 609 source=source
610 610 ))
611 611 nb = v4.new_notebook(cells=cells)
612 612 with io.open(args.filename, 'w', encoding='utf-8') as f:
613 613 write(nb, f, version=4)
@@ -1,159 +1,159 b''
1 1 """Implementation of configuration-related magic functions.
2 2 """
3 3 from __future__ import print_function
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (c) 2012 The IPython Development Team.
6 6 #
7 7 # Distributed under the terms of the Modified BSD License.
8 8 #
9 9 # The full license is in the file COPYING.txt, distributed with this software.
10 10 #-----------------------------------------------------------------------------
11 11
12 12 #-----------------------------------------------------------------------------
13 13 # Imports
14 14 #-----------------------------------------------------------------------------
15 15
16 16 # Stdlib
17 17 import re
18 18
19 19 # Our own packages
20 20 from IPython.core.error import UsageError
21 21 from IPython.core.magic import Magics, magics_class, line_magic
22 22 from IPython.utils.warn import error
23 23
24 24 #-----------------------------------------------------------------------------
25 25 # Magic implementation classes
26 26 #-----------------------------------------------------------------------------
27 27
28 28 reg = re.compile('^\w+\.\w+$')
29 29 @magics_class
30 30 class ConfigMagics(Magics):
31 31
32 32 def __init__(self, shell):
33 33 super(ConfigMagics, self).__init__(shell)
34 34 self.configurables = []
35 35
36 36 @line_magic
37 37 def config(self, s):
38 38 """configure IPython
39 39
40 40 %config Class[.trait=value]
41 41
42 42 This magic exposes most of the IPython config system. Any
43 43 Configurable class should be able to be configured with the simple
44 44 line::
45 45
46 46 %config Class.trait=value
47 47
48 48 Where `value` will be resolved in the user's namespace, if it is an
49 49 expression or variable name.
50 50
51 51 Examples
52 52 --------
53 53
54 54 To see what classes are available for config, pass no arguments::
55 55
56 56 In [1]: %config
57 57 Available objects for config:
58 58 TerminalInteractiveShell
59 59 HistoryManager
60 60 PrefilterManager
61 61 AliasManager
62 62 IPCompleter
63 63 PromptManager
64 64 DisplayFormatter
65 65
66 66 To view what is configurable on a given class, just pass the class
67 67 name::
68 68
69 69 In [2]: %config IPCompleter
70 70 IPCompleter options
71 71 -----------------
72 72 IPCompleter.omit__names=<Enum>
73 73 Current: 2
74 74 Choices: (0, 1, 2)
75 75 Instruct the completer to omit private method names
76 76 Specifically, when completing on ``object.<tab>``.
77 77 When 2 [default]: all names that start with '_' will be excluded.
78 78 When 1: all 'magic' names (``__foo__``) will be excluded.
79 79 When 0: nothing will be excluded.
80 80 IPCompleter.merge_completions=<CBool>
81 81 Current: True
82 82 Whether to merge completion results into a single list
83 83 If False, only the completion results from the first non-empty
84 84 completer will be returned.
85 85 IPCompleter.limit_to__all__=<CBool>
86 86 Current: False
87 87 Instruct the completer to use __all__ for the completion
88 88 Specifically, when completing on ``object.<tab>``.
89 89 When True: only those names in obj.__all__ will be included.
90 90 When False [default]: the __all__ attribute is ignored
91 91 IPCompleter.greedy=<CBool>
92 92 Current: False
93 93 Activate greedy completion
94 94 This will enable completion on elements of lists, results of
95 95 function calls, etc., but can be unsafe because the code is
96 96 actually evaluated on TAB.
97 97
98 98 but the real use is in setting values::
99 99
100 100 In [3]: %config IPCompleter.greedy = True
101 101
102 102 and these values are read from the user_ns if they are variables::
103 103
104 104 In [4]: feeling_greedy=False
105 105
106 106 In [5]: %config IPCompleter.greedy = feeling_greedy
107 107
108 108 """
109 from IPython.config.loader import Config
109 from traitlets.config.loader import Config
110 110 # some IPython objects are Configurable, but do not yet have
111 111 # any configurable traits. Exclude them from the effects of
112 112 # this magic, as their presence is just noise:
113 113 configurables = [ c for c in self.shell.configurables
114 114 if c.__class__.class_traits(config=True) ]
115 115 classnames = [ c.__class__.__name__ for c in configurables ]
116 116
117 117 line = s.strip()
118 118 if not line:
119 119 # print available configurable names
120 120 print("Available objects for config:")
121 121 for name in classnames:
122 122 print(" ", name)
123 123 return
124 124 elif line in classnames:
125 125 # `%config TerminalInteractiveShell` will print trait info for
126 126 # TerminalInteractiveShell
127 127 c = configurables[classnames.index(line)]
128 128 cls = c.__class__
129 129 help = cls.class_get_help(c)
130 130 # strip leading '--' from cl-args:
131 131 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
132 132 print(help)
133 133 return
134 134 elif reg.match(line):
135 135 cls, attr = line.split('.')
136 136 return getattr(configurables[classnames.index(cls)],attr)
137 137 elif '=' not in line:
138 138 msg = "Invalid config statement: %r, "\
139 139 "should be `Class.trait = value`."
140 140
141 141 ll = line.lower()
142 142 for classname in classnames:
143 143 if ll == classname.lower():
144 144 msg = msg + '\nDid you mean %s (note the case)?' % classname
145 145 break
146 146
147 147 raise UsageError( msg % line)
148 148
149 149 # otherwise, assume we are setting configurables.
150 150 # leave quotes on args when splitting, because we want
151 151 # unquoted args to eval in user_ns
152 152 cfg = Config()
153 153 exec("cfg."+line, locals(), self.shell.user_ns)
154 154
155 155 for configurable in configurables:
156 156 try:
157 157 configurable.update_config(cfg)
158 158 except Exception as e:
159 159 error(e)
@@ -1,155 +1,155 b''
1 1 """Implementation of magic functions for matplotlib/pylab support.
2 2 """
3 3 from __future__ import print_function
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (c) 2012 The IPython Development Team.
6 6 #
7 7 # Distributed under the terms of the Modified BSD License.
8 8 #
9 9 # The full license is in the file COPYING.txt, distributed with this software.
10 10 #-----------------------------------------------------------------------------
11 11
12 12 #-----------------------------------------------------------------------------
13 13 # Imports
14 14 #-----------------------------------------------------------------------------
15 15
16 16 # Our own packages
17 from IPython.config.application import Application
17 from traitlets.config.application import Application
18 18 from IPython.core import magic_arguments
19 19 from IPython.core.magic import Magics, magics_class, line_magic
20 20 from IPython.testing.skipdoctest import skip_doctest
21 21 from IPython.utils.warn import warn
22 22 from IPython.core.pylabtools import backends
23 23
24 24 #-----------------------------------------------------------------------------
25 25 # Magic implementation classes
26 26 #-----------------------------------------------------------------------------
27 27
28 28 magic_gui_arg = magic_arguments.argument(
29 29 'gui', nargs='?',
30 30 help="""Name of the matplotlib backend to use %s.
31 31 If given, the corresponding matplotlib backend is used,
32 32 otherwise it will be matplotlib's default
33 33 (which you can set in your matplotlib config file).
34 34 """ % str(tuple(sorted(backends.keys())))
35 35 )
36 36
37 37
38 38 @magics_class
39 39 class PylabMagics(Magics):
40 40 """Magics related to matplotlib's pylab support"""
41 41
42 42 @skip_doctest
43 43 @line_magic
44 44 @magic_arguments.magic_arguments()
45 45 @magic_gui_arg
46 46 def matplotlib(self, line=''):
47 47 """Set up matplotlib to work interactively.
48 48
49 49 This function lets you activate matplotlib interactive support
50 50 at any point during an IPython session. It does not import anything
51 51 into the interactive namespace.
52 52
53 53 If you are using the inline matplotlib backend in the IPython Notebook
54 54 you can set which figure formats are enabled using the following::
55 55
56 56 In [1]: from IPython.display import set_matplotlib_formats
57 57
58 58 In [2]: set_matplotlib_formats('pdf', 'svg')
59 59
60 60 The default for inline figures sets `bbox_inches` to 'tight'. This can
61 61 cause discrepancies between the displayed image and the identical
62 62 image created using `savefig`. This behavior can be disabled using the
63 63 `%config` magic::
64 64
65 65 In [3]: %config InlineBackend.print_figure_kwargs = {'bbox_inches':None}
66 66
67 67 In addition, see the docstring of
68 68 `IPython.display.set_matplotlib_formats` and
69 69 `IPython.display.set_matplotlib_close` for more information on
70 70 changing additional behaviors of the inline backend.
71 71
72 72 Examples
73 73 --------
74 74 To enable the inline backend for usage with the IPython Notebook::
75 75
76 76 In [1]: %matplotlib inline
77 77
78 78 In this case, where the matplotlib default is TkAgg::
79 79
80 80 In [2]: %matplotlib
81 81 Using matplotlib backend: TkAgg
82 82
83 83 But you can explicitly request a different GUI backend::
84 84
85 85 In [3]: %matplotlib qt
86 86 """
87 87 args = magic_arguments.parse_argstring(self.matplotlib, line)
88 88 gui, backend = self.shell.enable_matplotlib(args.gui)
89 89 self._show_matplotlib_backend(args.gui, backend)
90 90
91 91 @skip_doctest
92 92 @line_magic
93 93 @magic_arguments.magic_arguments()
94 94 @magic_arguments.argument(
95 95 '--no-import-all', action='store_true', default=None,
96 96 help="""Prevent IPython from performing ``import *`` into the interactive namespace.
97 97
98 98 You can govern the default behavior of this flag with the
99 99 InteractiveShellApp.pylab_import_all configurable.
100 100 """
101 101 )
102 102 @magic_gui_arg
103 103 def pylab(self, line=''):
104 104 """Load numpy and matplotlib to work interactively.
105 105
106 106 This function lets you activate pylab (matplotlib, numpy and
107 107 interactive support) at any point during an IPython session.
108 108
109 109 %pylab makes the following imports::
110 110
111 111 import numpy
112 112 import matplotlib
113 113 from matplotlib import pylab, mlab, pyplot
114 114 np = numpy
115 115 plt = pyplot
116 116
117 117 from IPython.display import display
118 118 from IPython.core.pylabtools import figsize, getfigs
119 119
120 120 from pylab import *
121 121 from numpy import *
122 122
123 123 If you pass `--no-import-all`, the last two `*` imports will be excluded.
124 124
125 125 See the %matplotlib magic for more details about activating matplotlib
126 126 without affecting the interactive namespace.
127 127 """
128 128 args = magic_arguments.parse_argstring(self.pylab, line)
129 129 if args.no_import_all is None:
130 130 # get default from Application
131 131 if Application.initialized():
132 132 app = Application.instance()
133 133 try:
134 134 import_all = app.pylab_import_all
135 135 except AttributeError:
136 136 import_all = True
137 137 else:
138 138 # nothing specified, no app - default True
139 139 import_all = True
140 140 else:
141 141 # invert no-import flag
142 142 import_all = not args.no_import_all
143 143
144 144 gui, backend, clobbered = self.shell.enable_pylab(args.gui, import_all=import_all)
145 145 self._show_matplotlib_backend(args.gui, backend)
146 146 print ("Populating the interactive namespace from numpy and matplotlib")
147 147 if clobbered:
148 148 warn("pylab import has clobbered these variables: %s" % clobbered +
149 149 "\n`%matplotlib` prevents importing * from pylab and numpy"
150 150 )
151 151
152 152 def _show_matplotlib_backend(self, gui, backend):
153 153 """show matplotlib message backend message"""
154 154 if not gui or gui == 'auto':
155 155 print("Using matplotlib backend: %s" % backend)
@@ -1,282 +1,282 b''
1 1 """Magic functions for running cells in various scripts."""
2 2 from __future__ import print_function
3 3 #-----------------------------------------------------------------------------
4 4 # Copyright (c) 2012 The IPython Development Team.
5 5 #
6 6 # Distributed under the terms of the Modified BSD License.
7 7 #
8 8 # The full license is in the file COPYING.txt, distributed with this software.
9 9 #-----------------------------------------------------------------------------
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Imports
13 13 #-----------------------------------------------------------------------------
14 14
15 15 # Stdlib
16 16 import errno
17 17 import os
18 18 import sys
19 19 import signal
20 20 import time
21 21 from subprocess import Popen, PIPE
22 22 import atexit
23 23
24 24 # Our own packages
25 from IPython.config.configurable import Configurable
25 from traitlets.config.configurable import Configurable
26 26 from IPython.core import magic_arguments
27 27 from IPython.core.magic import (
28 28 Magics, magics_class, line_magic, cell_magic
29 29 )
30 30 from IPython.lib.backgroundjobs import BackgroundJobManager
31 31 from IPython.utils import py3compat
32 32 from IPython.utils.process import arg_split
33 from IPython.utils.traitlets import List, Dict
33 from traitlets import List, Dict
34 34
35 35 #-----------------------------------------------------------------------------
36 36 # Magic implementation classes
37 37 #-----------------------------------------------------------------------------
38 38
39 39 def script_args(f):
40 40 """single decorator for adding script args"""
41 41 args = [
42 42 magic_arguments.argument(
43 43 '--out', type=str,
44 44 help="""The variable in which to store stdout from the script.
45 45 If the script is backgrounded, this will be the stdout *pipe*,
46 46 instead of the stderr text itself.
47 47 """
48 48 ),
49 49 magic_arguments.argument(
50 50 '--err', type=str,
51 51 help="""The variable in which to store stderr from the script.
52 52 If the script is backgrounded, this will be the stderr *pipe*,
53 53 instead of the stderr text itself.
54 54 """
55 55 ),
56 56 magic_arguments.argument(
57 57 '--bg', action="store_true",
58 58 help="""Whether to run the script in the background.
59 59 If given, the only way to see the output of the command is
60 60 with --out/err.
61 61 """
62 62 ),
63 63 magic_arguments.argument(
64 64 '--proc', type=str,
65 65 help="""The variable in which to store Popen instance.
66 66 This is used only when --bg option is given.
67 67 """
68 68 ),
69 69 ]
70 70 for arg in args:
71 71 f = arg(f)
72 72 return f
73 73
74 74 @magics_class
75 75 class ScriptMagics(Magics):
76 76 """Magics for talking to scripts
77 77
78 78 This defines a base `%%script` cell magic for running a cell
79 79 with a program in a subprocess, and registers a few top-level
80 80 magics that call %%script with common interpreters.
81 81 """
82 82 script_magics = List(config=True,
83 83 help="""Extra script cell magics to define
84 84
85 85 This generates simple wrappers of `%%script foo` as `%%foo`.
86 86
87 87 If you want to add script magics that aren't on your path,
88 88 specify them in script_paths
89 89 """,
90 90 )
91 91 def _script_magics_default(self):
92 92 """default to a common list of programs"""
93 93
94 94 defaults = [
95 95 'sh',
96 96 'bash',
97 97 'perl',
98 98 'ruby',
99 99 'python',
100 100 'python2',
101 101 'python3',
102 102 'pypy',
103 103 ]
104 104 if os.name == 'nt':
105 105 defaults.extend([
106 106 'cmd',
107 107 ])
108 108
109 109 return defaults
110 110
111 111 script_paths = Dict(config=True,
112 112 help="""Dict mapping short 'ruby' names to full paths, such as '/opt/secret/bin/ruby'
113 113
114 114 Only necessary for items in script_magics where the default path will not
115 115 find the right interpreter.
116 116 """
117 117 )
118 118
119 119 def __init__(self, shell=None):
120 120 super(ScriptMagics, self).__init__(shell=shell)
121 121 self._generate_script_magics()
122 122 self.job_manager = BackgroundJobManager()
123 123 self.bg_processes = []
124 124 atexit.register(self.kill_bg_processes)
125 125
126 126 def __del__(self):
127 127 self.kill_bg_processes()
128 128
129 129 def _generate_script_magics(self):
130 130 cell_magics = self.magics['cell']
131 131 for name in self.script_magics:
132 132 cell_magics[name] = self._make_script_magic(name)
133 133
134 134 def _make_script_magic(self, name):
135 135 """make a named magic, that calls %%script with a particular program"""
136 136 # expand to explicit path if necessary:
137 137 script = self.script_paths.get(name, name)
138 138
139 139 @magic_arguments.magic_arguments()
140 140 @script_args
141 141 def named_script_magic(line, cell):
142 142 # if line, add it as cl-flags
143 143 if line:
144 144 line = "%s %s" % (script, line)
145 145 else:
146 146 line = script
147 147 return self.shebang(line, cell)
148 148
149 149 # write a basic docstring:
150 150 named_script_magic.__doc__ = \
151 151 """%%{name} script magic
152 152
153 153 Run cells with {script} in a subprocess.
154 154
155 155 This is a shortcut for `%%script {script}`
156 156 """.format(**locals())
157 157
158 158 return named_script_magic
159 159
160 160 @magic_arguments.magic_arguments()
161 161 @script_args
162 162 @cell_magic("script")
163 163 def shebang(self, line, cell):
164 164 """Run a cell via a shell command
165 165
166 166 The `%%script` line is like the #! line of script,
167 167 specifying a program (bash, perl, ruby, etc.) with which to run.
168 168
169 169 The rest of the cell is run by that program.
170 170
171 171 Examples
172 172 --------
173 173 ::
174 174
175 175 In [1]: %%script bash
176 176 ...: for i in 1 2 3; do
177 177 ...: echo $i
178 178 ...: done
179 179 1
180 180 2
181 181 3
182 182 """
183 183 argv = arg_split(line, posix = not sys.platform.startswith('win'))
184 184 args, cmd = self.shebang.parser.parse_known_args(argv)
185 185
186 186 try:
187 187 p = Popen(cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE)
188 188 except OSError as e:
189 189 if e.errno == errno.ENOENT:
190 190 print("Couldn't find program: %r" % cmd[0])
191 191 return
192 192 else:
193 193 raise
194 194
195 195 if not cell.endswith('\n'):
196 196 cell += '\n'
197 197 cell = cell.encode('utf8', 'replace')
198 198 if args.bg:
199 199 self.bg_processes.append(p)
200 200 self._gc_bg_processes()
201 201 if args.out:
202 202 self.shell.user_ns[args.out] = p.stdout
203 203 if args.err:
204 204 self.shell.user_ns[args.err] = p.stderr
205 205 self.job_manager.new(self._run_script, p, cell, daemon=True)
206 206 if args.proc:
207 207 self.shell.user_ns[args.proc] = p
208 208 return
209 209
210 210 try:
211 211 out, err = p.communicate(cell)
212 212 except KeyboardInterrupt:
213 213 try:
214 214 p.send_signal(signal.SIGINT)
215 215 time.sleep(0.1)
216 216 if p.poll() is not None:
217 217 print("Process is interrupted.")
218 218 return
219 219 p.terminate()
220 220 time.sleep(0.1)
221 221 if p.poll() is not None:
222 222 print("Process is terminated.")
223 223 return
224 224 p.kill()
225 225 print("Process is killed.")
226 226 except OSError:
227 227 pass
228 228 except Exception as e:
229 229 print("Error while terminating subprocess (pid=%i): %s" \
230 230 % (p.pid, e))
231 231 return
232 232 out = py3compat.bytes_to_str(out)
233 233 err = py3compat.bytes_to_str(err)
234 234 if args.out:
235 235 self.shell.user_ns[args.out] = out
236 236 else:
237 237 sys.stdout.write(out)
238 238 sys.stdout.flush()
239 239 if args.err:
240 240 self.shell.user_ns[args.err] = err
241 241 else:
242 242 sys.stderr.write(err)
243 243 sys.stderr.flush()
244 244
245 245 def _run_script(self, p, cell):
246 246 """callback for running the script in the background"""
247 247 p.stdin.write(cell)
248 248 p.stdin.close()
249 249 p.wait()
250 250
251 251 @line_magic("killbgscripts")
252 252 def killbgscripts(self, _nouse_=''):
253 253 """Kill all BG processes started by %%script and its family."""
254 254 self.kill_bg_processes()
255 255 print("All background processes were killed.")
256 256
257 257 def kill_bg_processes(self):
258 258 """Kill all BG processes which are still running."""
259 259 for p in self.bg_processes:
260 260 if p.poll() is None:
261 261 try:
262 262 p.send_signal(signal.SIGINT)
263 263 except:
264 264 pass
265 265 time.sleep(0.1)
266 266 for p in self.bg_processes:
267 267 if p.poll() is None:
268 268 try:
269 269 p.terminate()
270 270 except:
271 271 pass
272 272 time.sleep(0.1)
273 273 for p in self.bg_processes:
274 274 if p.poll() is None:
275 275 try:
276 276 p.kill()
277 277 except:
278 278 pass
279 279 self._gc_bg_processes()
280 280
281 281 def _gc_bg_processes(self):
282 282 self.bg_processes = [p for p in self.bg_processes if p.poll() is None]
@@ -1,55 +1,55 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Payload system for IPython.
3 3
4 4 Authors:
5 5
6 6 * Fernando Perez
7 7 * Brian Granger
8 8 """
9 9
10 10 #-----------------------------------------------------------------------------
11 11 # Copyright (C) 2008-2011 The IPython Development Team
12 12 #
13 13 # Distributed under the terms of the BSD License. The full license is in
14 14 # the file COPYING, distributed as part of this software.
15 15 #-----------------------------------------------------------------------------
16 16
17 17 #-----------------------------------------------------------------------------
18 18 # Imports
19 19 #-----------------------------------------------------------------------------
20 20
21 from IPython.config.configurable import Configurable
22 from IPython.utils.traitlets import List
21 from traitlets.config.configurable import Configurable
22 from traitlets import List
23 23
24 24 #-----------------------------------------------------------------------------
25 25 # Main payload class
26 26 #-----------------------------------------------------------------------------
27 27
28 28 class PayloadManager(Configurable):
29 29
30 30 _payload = List([])
31 31
32 32 def write_payload(self, data, single=True):
33 33 """Include or update the specified `data` payload in the PayloadManager.
34 34
35 35 If a previous payload with the same source exists and `single` is True,
36 36 it will be overwritten with the new one.
37 37 """
38 38
39 39 if not isinstance(data, dict):
40 40 raise TypeError('Each payload write must be a dict, got: %r' % data)
41 41
42 42 if single and 'source' in data:
43 43 source = data['source']
44 44 for i, pl in enumerate(self._payload):
45 45 if 'source' in pl and pl['source'] == source:
46 46 self._payload[i] = data
47 47 return
48 48
49 49 self._payload.append(data)
50 50
51 51 def read_payload(self):
52 52 return self._payload
53 53
54 54 def clear_payload(self):
55 55 self._payload = []
@@ -1,715 +1,715 b''
1 1 # encoding: utf-8
2 2 """
3 3 Prefiltering components.
4 4
5 5 Prefilters transform user input before it is exec'd by Python. These
6 6 transforms are used to implement additional syntax such as !ls and %magic.
7 7
8 8 Authors:
9 9
10 10 * Brian Granger
11 11 * Fernando Perez
12 12 * Dan Milstein
13 13 * Ville Vainio
14 14 """
15 15
16 16 #-----------------------------------------------------------------------------
17 17 # Copyright (C) 2008-2011 The IPython Development Team
18 18 #
19 19 # Distributed under the terms of the BSD License. The full license is in
20 20 # the file COPYING, distributed as part of this software.
21 21 #-----------------------------------------------------------------------------
22 22
23 23 #-----------------------------------------------------------------------------
24 24 # Imports
25 25 #-----------------------------------------------------------------------------
26 26
27 27 from keyword import iskeyword
28 28 import re
29 29
30 30 from IPython.core.autocall import IPyAutocall
31 from IPython.config.configurable import Configurable
31 from traitlets.config.configurable import Configurable
32 32 from IPython.core.inputsplitter import (
33 33 ESC_MAGIC,
34 34 ESC_QUOTE,
35 35 ESC_QUOTE2,
36 36 ESC_PAREN,
37 37 )
38 38 from IPython.core.macro import Macro
39 39 from IPython.core.splitinput import LineInfo
40 40
41 from IPython.utils.traitlets import (
41 from traitlets import (
42 42 List, Integer, Unicode, CBool, Bool, Instance, CRegExp
43 43 )
44 44
45 45 #-----------------------------------------------------------------------------
46 46 # Global utilities, errors and constants
47 47 #-----------------------------------------------------------------------------
48 48
49 49
50 50 class PrefilterError(Exception):
51 51 pass
52 52
53 53
54 54 # RegExp to identify potential function names
55 55 re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
56 56
57 57 # RegExp to exclude strings with this start from autocalling. In
58 58 # particular, all binary operators should be excluded, so that if foo is
59 59 # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The
60 60 # characters '!=()' don't need to be checked for, as the checkPythonChars
61 61 # routine explicitely does so, to catch direct calls and rebindings of
62 62 # existing names.
63 63
64 64 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
65 65 # it affects the rest of the group in square brackets.
66 66 re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]'
67 67 r'|^is |^not |^in |^and |^or ')
68 68
69 69 # try to catch also methods for stuff in lists/tuples/dicts: off
70 70 # (experimental). For this to work, the line_split regexp would need
71 71 # to be modified so it wouldn't break things at '['. That line is
72 72 # nasty enough that I shouldn't change it until I can test it _well_.
73 73 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
74 74
75 75
76 76 # Handler Check Utilities
77 77 def is_shadowed(identifier, ip):
78 78 """Is the given identifier defined in one of the namespaces which shadow
79 79 the alias and magic namespaces? Note that an identifier is different
80 80 than ifun, because it can not contain a '.' character."""
81 81 # This is much safer than calling ofind, which can change state
82 82 return (identifier in ip.user_ns \
83 83 or identifier in ip.user_global_ns \
84 84 or identifier in ip.ns_table['builtin']\
85 85 or iskeyword(identifier))
86 86
87 87
88 88 #-----------------------------------------------------------------------------
89 89 # Main Prefilter manager
90 90 #-----------------------------------------------------------------------------
91 91
92 92
93 93 class PrefilterManager(Configurable):
94 94 """Main prefilter component.
95 95
96 96 The IPython prefilter is run on all user input before it is run. The
97 97 prefilter consumes lines of input and produces transformed lines of
98 98 input.
99 99
100 100 The iplementation consists of two phases:
101 101
102 102 1. Transformers
103 103 2. Checkers and handlers
104 104
105 105 Over time, we plan on deprecating the checkers and handlers and doing
106 106 everything in the transformers.
107 107
108 108 The transformers are instances of :class:`PrefilterTransformer` and have
109 109 a single method :meth:`transform` that takes a line and returns a
110 110 transformed line. The transformation can be accomplished using any
111 111 tool, but our current ones use regular expressions for speed.
112 112
113 113 After all the transformers have been run, the line is fed to the checkers,
114 114 which are instances of :class:`PrefilterChecker`. The line is passed to
115 115 the :meth:`check` method, which either returns `None` or a
116 116 :class:`PrefilterHandler` instance. If `None` is returned, the other
117 117 checkers are tried. If an :class:`PrefilterHandler` instance is returned,
118 118 the line is passed to the :meth:`handle` method of the returned
119 119 handler and no further checkers are tried.
120 120
121 121 Both transformers and checkers have a `priority` attribute, that determines
122 122 the order in which they are called. Smaller priorities are tried first.
123 123
124 124 Both transformers and checkers also have `enabled` attribute, which is
125 125 a boolean that determines if the instance is used.
126 126
127 127 Users or developers can change the priority or enabled attribute of
128 128 transformers or checkers, but they must call the :meth:`sort_checkers`
129 129 or :meth:`sort_transformers` method after changing the priority.
130 130 """
131 131
132 132 multi_line_specials = CBool(True, config=True)
133 133 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
134 134
135 135 def __init__(self, shell=None, **kwargs):
136 136 super(PrefilterManager, self).__init__(shell=shell, **kwargs)
137 137 self.shell = shell
138 138 self.init_transformers()
139 139 self.init_handlers()
140 140 self.init_checkers()
141 141
142 142 #-------------------------------------------------------------------------
143 143 # API for managing transformers
144 144 #-------------------------------------------------------------------------
145 145
146 146 def init_transformers(self):
147 147 """Create the default transformers."""
148 148 self._transformers = []
149 149 for transformer_cls in _default_transformers:
150 150 transformer_cls(
151 151 shell=self.shell, prefilter_manager=self, parent=self
152 152 )
153 153
154 154 def sort_transformers(self):
155 155 """Sort the transformers by priority.
156 156
157 157 This must be called after the priority of a transformer is changed.
158 158 The :meth:`register_transformer` method calls this automatically.
159 159 """
160 160 self._transformers.sort(key=lambda x: x.priority)
161 161
162 162 @property
163 163 def transformers(self):
164 164 """Return a list of checkers, sorted by priority."""
165 165 return self._transformers
166 166
167 167 def register_transformer(self, transformer):
168 168 """Register a transformer instance."""
169 169 if transformer not in self._transformers:
170 170 self._transformers.append(transformer)
171 171 self.sort_transformers()
172 172
173 173 def unregister_transformer(self, transformer):
174 174 """Unregister a transformer instance."""
175 175 if transformer in self._transformers:
176 176 self._transformers.remove(transformer)
177 177
178 178 #-------------------------------------------------------------------------
179 179 # API for managing checkers
180 180 #-------------------------------------------------------------------------
181 181
182 182 def init_checkers(self):
183 183 """Create the default checkers."""
184 184 self._checkers = []
185 185 for checker in _default_checkers:
186 186 checker(
187 187 shell=self.shell, prefilter_manager=self, parent=self
188 188 )
189 189
190 190 def sort_checkers(self):
191 191 """Sort the checkers by priority.
192 192
193 193 This must be called after the priority of a checker is changed.
194 194 The :meth:`register_checker` method calls this automatically.
195 195 """
196 196 self._checkers.sort(key=lambda x: x.priority)
197 197
198 198 @property
199 199 def checkers(self):
200 200 """Return a list of checkers, sorted by priority."""
201 201 return self._checkers
202 202
203 203 def register_checker(self, checker):
204 204 """Register a checker instance."""
205 205 if checker not in self._checkers:
206 206 self._checkers.append(checker)
207 207 self.sort_checkers()
208 208
209 209 def unregister_checker(self, checker):
210 210 """Unregister a checker instance."""
211 211 if checker in self._checkers:
212 212 self._checkers.remove(checker)
213 213
214 214 #-------------------------------------------------------------------------
215 215 # API for managing handlers
216 216 #-------------------------------------------------------------------------
217 217
218 218 def init_handlers(self):
219 219 """Create the default handlers."""
220 220 self._handlers = {}
221 221 self._esc_handlers = {}
222 222 for handler in _default_handlers:
223 223 handler(
224 224 shell=self.shell, prefilter_manager=self, parent=self
225 225 )
226 226
227 227 @property
228 228 def handlers(self):
229 229 """Return a dict of all the handlers."""
230 230 return self._handlers
231 231
232 232 def register_handler(self, name, handler, esc_strings):
233 233 """Register a handler instance by name with esc_strings."""
234 234 self._handlers[name] = handler
235 235 for esc_str in esc_strings:
236 236 self._esc_handlers[esc_str] = handler
237 237
238 238 def unregister_handler(self, name, handler, esc_strings):
239 239 """Unregister a handler instance by name with esc_strings."""
240 240 try:
241 241 del self._handlers[name]
242 242 except KeyError:
243 243 pass
244 244 for esc_str in esc_strings:
245 245 h = self._esc_handlers.get(esc_str)
246 246 if h is handler:
247 247 del self._esc_handlers[esc_str]
248 248
249 249 def get_handler_by_name(self, name):
250 250 """Get a handler by its name."""
251 251 return self._handlers.get(name)
252 252
253 253 def get_handler_by_esc(self, esc_str):
254 254 """Get a handler by its escape string."""
255 255 return self._esc_handlers.get(esc_str)
256 256
257 257 #-------------------------------------------------------------------------
258 258 # Main prefiltering API
259 259 #-------------------------------------------------------------------------
260 260
261 261 def prefilter_line_info(self, line_info):
262 262 """Prefilter a line that has been converted to a LineInfo object.
263 263
264 264 This implements the checker/handler part of the prefilter pipe.
265 265 """
266 266 # print "prefilter_line_info: ", line_info
267 267 handler = self.find_handler(line_info)
268 268 return handler.handle(line_info)
269 269
270 270 def find_handler(self, line_info):
271 271 """Find a handler for the line_info by trying checkers."""
272 272 for checker in self.checkers:
273 273 if checker.enabled:
274 274 handler = checker.check(line_info)
275 275 if handler:
276 276 return handler
277 277 return self.get_handler_by_name('normal')
278 278
279 279 def transform_line(self, line, continue_prompt):
280 280 """Calls the enabled transformers in order of increasing priority."""
281 281 for transformer in self.transformers:
282 282 if transformer.enabled:
283 283 line = transformer.transform(line, continue_prompt)
284 284 return line
285 285
286 286 def prefilter_line(self, line, continue_prompt=False):
287 287 """Prefilter a single input line as text.
288 288
289 289 This method prefilters a single line of text by calling the
290 290 transformers and then the checkers/handlers.
291 291 """
292 292
293 293 # print "prefilter_line: ", line, continue_prompt
294 294 # All handlers *must* return a value, even if it's blank ('').
295 295
296 296 # save the line away in case we crash, so the post-mortem handler can
297 297 # record it
298 298 self.shell._last_input_line = line
299 299
300 300 if not line:
301 301 # Return immediately on purely empty lines, so that if the user
302 302 # previously typed some whitespace that started a continuation
303 303 # prompt, he can break out of that loop with just an empty line.
304 304 # This is how the default python prompt works.
305 305 return ''
306 306
307 307 # At this point, we invoke our transformers.
308 308 if not continue_prompt or (continue_prompt and self.multi_line_specials):
309 309 line = self.transform_line(line, continue_prompt)
310 310
311 311 # Now we compute line_info for the checkers and handlers
312 312 line_info = LineInfo(line, continue_prompt)
313 313
314 314 # the input history needs to track even empty lines
315 315 stripped = line.strip()
316 316
317 317 normal_handler = self.get_handler_by_name('normal')
318 318 if not stripped:
319 319 return normal_handler.handle(line_info)
320 320
321 321 # special handlers are only allowed for single line statements
322 322 if continue_prompt and not self.multi_line_specials:
323 323 return normal_handler.handle(line_info)
324 324
325 325 prefiltered = self.prefilter_line_info(line_info)
326 326 # print "prefiltered line: %r" % prefiltered
327 327 return prefiltered
328 328
329 329 def prefilter_lines(self, lines, continue_prompt=False):
330 330 """Prefilter multiple input lines of text.
331 331
332 332 This is the main entry point for prefiltering multiple lines of
333 333 input. This simply calls :meth:`prefilter_line` for each line of
334 334 input.
335 335
336 336 This covers cases where there are multiple lines in the user entry,
337 337 which is the case when the user goes back to a multiline history
338 338 entry and presses enter.
339 339 """
340 340 llines = lines.rstrip('\n').split('\n')
341 341 # We can get multiple lines in one shot, where multiline input 'blends'
342 342 # into one line, in cases like recalling from the readline history
343 343 # buffer. We need to make sure that in such cases, we correctly
344 344 # communicate downstream which line is first and which are continuation
345 345 # ones.
346 346 if len(llines) > 1:
347 347 out = '\n'.join([self.prefilter_line(line, lnum>0)
348 348 for lnum, line in enumerate(llines) ])
349 349 else:
350 350 out = self.prefilter_line(llines[0], continue_prompt)
351 351
352 352 return out
353 353
354 354 #-----------------------------------------------------------------------------
355 355 # Prefilter transformers
356 356 #-----------------------------------------------------------------------------
357 357
358 358
359 359 class PrefilterTransformer(Configurable):
360 360 """Transform a line of user input."""
361 361
362 362 priority = Integer(100, config=True)
363 363 # Transformers don't currently use shell or prefilter_manager, but as we
364 364 # move away from checkers and handlers, they will need them.
365 365 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
366 366 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
367 367 enabled = Bool(True, config=True)
368 368
369 369 def __init__(self, shell=None, prefilter_manager=None, **kwargs):
370 370 super(PrefilterTransformer, self).__init__(
371 371 shell=shell, prefilter_manager=prefilter_manager, **kwargs
372 372 )
373 373 self.prefilter_manager.register_transformer(self)
374 374
375 375 def transform(self, line, continue_prompt):
376 376 """Transform a line, returning the new one."""
377 377 return None
378 378
379 379 def __repr__(self):
380 380 return "<%s(priority=%r, enabled=%r)>" % (
381 381 self.__class__.__name__, self.priority, self.enabled)
382 382
383 383
384 384 #-----------------------------------------------------------------------------
385 385 # Prefilter checkers
386 386 #-----------------------------------------------------------------------------
387 387
388 388
389 389 class PrefilterChecker(Configurable):
390 390 """Inspect an input line and return a handler for that line."""
391 391
392 392 priority = Integer(100, config=True)
393 393 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
394 394 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
395 395 enabled = Bool(True, config=True)
396 396
397 397 def __init__(self, shell=None, prefilter_manager=None, **kwargs):
398 398 super(PrefilterChecker, self).__init__(
399 399 shell=shell, prefilter_manager=prefilter_manager, **kwargs
400 400 )
401 401 self.prefilter_manager.register_checker(self)
402 402
403 403 def check(self, line_info):
404 404 """Inspect line_info and return a handler instance or None."""
405 405 return None
406 406
407 407 def __repr__(self):
408 408 return "<%s(priority=%r, enabled=%r)>" % (
409 409 self.__class__.__name__, self.priority, self.enabled)
410 410
411 411
412 412 class EmacsChecker(PrefilterChecker):
413 413
414 414 priority = Integer(100, config=True)
415 415 enabled = Bool(False, config=True)
416 416
417 417 def check(self, line_info):
418 418 "Emacs ipython-mode tags certain input lines."
419 419 if line_info.line.endswith('# PYTHON-MODE'):
420 420 return self.prefilter_manager.get_handler_by_name('emacs')
421 421 else:
422 422 return None
423 423
424 424
425 425 class MacroChecker(PrefilterChecker):
426 426
427 427 priority = Integer(250, config=True)
428 428
429 429 def check(self, line_info):
430 430 obj = self.shell.user_ns.get(line_info.ifun)
431 431 if isinstance(obj, Macro):
432 432 return self.prefilter_manager.get_handler_by_name('macro')
433 433 else:
434 434 return None
435 435
436 436
437 437 class IPyAutocallChecker(PrefilterChecker):
438 438
439 439 priority = Integer(300, config=True)
440 440
441 441 def check(self, line_info):
442 442 "Instances of IPyAutocall in user_ns get autocalled immediately"
443 443 obj = self.shell.user_ns.get(line_info.ifun, None)
444 444 if isinstance(obj, IPyAutocall):
445 445 obj.set_ip(self.shell)
446 446 return self.prefilter_manager.get_handler_by_name('auto')
447 447 else:
448 448 return None
449 449
450 450
451 451 class AssignmentChecker(PrefilterChecker):
452 452
453 453 priority = Integer(600, config=True)
454 454
455 455 def check(self, line_info):
456 456 """Check to see if user is assigning to a var for the first time, in
457 457 which case we want to avoid any sort of automagic / autocall games.
458 458
459 459 This allows users to assign to either alias or magic names true python
460 460 variables (the magic/alias systems always take second seat to true
461 461 python code). E.g. ls='hi', or ls,that=1,2"""
462 462 if line_info.the_rest:
463 463 if line_info.the_rest[0] in '=,':
464 464 return self.prefilter_manager.get_handler_by_name('normal')
465 465 else:
466 466 return None
467 467
468 468
469 469 class AutoMagicChecker(PrefilterChecker):
470 470
471 471 priority = Integer(700, config=True)
472 472
473 473 def check(self, line_info):
474 474 """If the ifun is magic, and automagic is on, run it. Note: normal,
475 475 non-auto magic would already have been triggered via '%' in
476 476 check_esc_chars. This just checks for automagic. Also, before
477 477 triggering the magic handler, make sure that there is nothing in the
478 478 user namespace which could shadow it."""
479 479 if not self.shell.automagic or not self.shell.find_magic(line_info.ifun):
480 480 return None
481 481
482 482 # We have a likely magic method. Make sure we should actually call it.
483 483 if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials:
484 484 return None
485 485
486 486 head = line_info.ifun.split('.',1)[0]
487 487 if is_shadowed(head, self.shell):
488 488 return None
489 489
490 490 return self.prefilter_manager.get_handler_by_name('magic')
491 491
492 492
493 493 class PythonOpsChecker(PrefilterChecker):
494 494
495 495 priority = Integer(900, config=True)
496 496
497 497 def check(self, line_info):
498 498 """If the 'rest' of the line begins with a function call or pretty much
499 499 any python operator, we should simply execute the line (regardless of
500 500 whether or not there's a possible autocall expansion). This avoids
501 501 spurious (and very confusing) geattr() accesses."""
502 502 if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|':
503 503 return self.prefilter_manager.get_handler_by_name('normal')
504 504 else:
505 505 return None
506 506
507 507
508 508 class AutocallChecker(PrefilterChecker):
509 509
510 510 priority = Integer(1000, config=True)
511 511
512 512 function_name_regexp = CRegExp(re_fun_name, config=True,
513 513 help="RegExp to identify potential function names.")
514 514 exclude_regexp = CRegExp(re_exclude_auto, config=True,
515 515 help="RegExp to exclude strings with this start from autocalling.")
516 516
517 517 def check(self, line_info):
518 518 "Check if the initial word/function is callable and autocall is on."
519 519 if not self.shell.autocall:
520 520 return None
521 521
522 522 oinfo = line_info.ofind(self.shell) # This can mutate state via getattr
523 523 if not oinfo['found']:
524 524 return None
525 525
526 526 if callable(oinfo['obj']) \
527 527 and (not self.exclude_regexp.match(line_info.the_rest)) \
528 528 and self.function_name_regexp.match(line_info.ifun):
529 529 return self.prefilter_manager.get_handler_by_name('auto')
530 530 else:
531 531 return None
532 532
533 533
534 534 #-----------------------------------------------------------------------------
535 535 # Prefilter handlers
536 536 #-----------------------------------------------------------------------------
537 537
538 538
539 539 class PrefilterHandler(Configurable):
540 540
541 541 handler_name = Unicode('normal')
542 542 esc_strings = List([])
543 543 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
544 544 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
545 545
546 546 def __init__(self, shell=None, prefilter_manager=None, **kwargs):
547 547 super(PrefilterHandler, self).__init__(
548 548 shell=shell, prefilter_manager=prefilter_manager, **kwargs
549 549 )
550 550 self.prefilter_manager.register_handler(
551 551 self.handler_name,
552 552 self,
553 553 self.esc_strings
554 554 )
555 555
556 556 def handle(self, line_info):
557 557 # print "normal: ", line_info
558 558 """Handle normal input lines. Use as a template for handlers."""
559 559
560 560 # With autoindent on, we need some way to exit the input loop, and I
561 561 # don't want to force the user to have to backspace all the way to
562 562 # clear the line. The rule will be in this case, that either two
563 563 # lines of pure whitespace in a row, or a line of pure whitespace but
564 564 # of a size different to the indent level, will exit the input loop.
565 565 line = line_info.line
566 566 continue_prompt = line_info.continue_prompt
567 567
568 568 if (continue_prompt and
569 569 self.shell.autoindent and
570 570 line.isspace() and
571 571 0 < abs(len(line) - self.shell.indent_current_nsp) <= 2):
572 572 line = ''
573 573
574 574 return line
575 575
576 576 def __str__(self):
577 577 return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name)
578 578
579 579
580 580 class MacroHandler(PrefilterHandler):
581 581 handler_name = Unicode("macro")
582 582
583 583 def handle(self, line_info):
584 584 obj = self.shell.user_ns.get(line_info.ifun)
585 585 pre_space = line_info.pre_whitespace
586 586 line_sep = "\n" + pre_space
587 587 return pre_space + line_sep.join(obj.value.splitlines())
588 588
589 589
590 590 class MagicHandler(PrefilterHandler):
591 591
592 592 handler_name = Unicode('magic')
593 593 esc_strings = List([ESC_MAGIC])
594 594
595 595 def handle(self, line_info):
596 596 """Execute magic functions."""
597 597 ifun = line_info.ifun
598 598 the_rest = line_info.the_rest
599 599 cmd = '%sget_ipython().magic(%r)' % (line_info.pre_whitespace,
600 600 (ifun + " " + the_rest))
601 601 return cmd
602 602
603 603
604 604 class AutoHandler(PrefilterHandler):
605 605
606 606 handler_name = Unicode('auto')
607 607 esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2])
608 608
609 609 def handle(self, line_info):
610 610 """Handle lines which can be auto-executed, quoting if requested."""
611 611 line = line_info.line
612 612 ifun = line_info.ifun
613 613 the_rest = line_info.the_rest
614 614 pre = line_info.pre
615 615 esc = line_info.esc
616 616 continue_prompt = line_info.continue_prompt
617 617 obj = line_info.ofind(self.shell)['obj']
618 618 #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg
619 619
620 620 # This should only be active for single-line input!
621 621 if continue_prompt:
622 622 return line
623 623
624 624 force_auto = isinstance(obj, IPyAutocall)
625 625
626 626 # User objects sometimes raise exceptions on attribute access other
627 627 # than AttributeError (we've seen it in the past), so it's safest to be
628 628 # ultra-conservative here and catch all.
629 629 try:
630 630 auto_rewrite = obj.rewrite
631 631 except Exception:
632 632 auto_rewrite = True
633 633
634 634 if esc == ESC_QUOTE:
635 635 # Auto-quote splitting on whitespace
636 636 newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
637 637 elif esc == ESC_QUOTE2:
638 638 # Auto-quote whole string
639 639 newcmd = '%s("%s")' % (ifun,the_rest)
640 640 elif esc == ESC_PAREN:
641 641 newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
642 642 else:
643 643 # Auto-paren.
644 644 if force_auto:
645 645 # Don't rewrite if it is already a call.
646 646 do_rewrite = not the_rest.startswith('(')
647 647 else:
648 648 if not the_rest:
649 649 # We only apply it to argument-less calls if the autocall
650 650 # parameter is set to 2.
651 651 do_rewrite = (self.shell.autocall >= 2)
652 652 elif the_rest.startswith('[') and hasattr(obj, '__getitem__'):
653 653 # Don't autocall in this case: item access for an object
654 654 # which is BOTH callable and implements __getitem__.
655 655 do_rewrite = False
656 656 else:
657 657 do_rewrite = True
658 658
659 659 # Figure out the rewritten command
660 660 if do_rewrite:
661 661 if the_rest.endswith(';'):
662 662 newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
663 663 else:
664 664 newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
665 665 else:
666 666 normal_handler = self.prefilter_manager.get_handler_by_name('normal')
667 667 return normal_handler.handle(line_info)
668 668
669 669 # Display the rewritten call
670 670 if auto_rewrite:
671 671 self.shell.auto_rewrite_input(newcmd)
672 672
673 673 return newcmd
674 674
675 675
676 676 class EmacsHandler(PrefilterHandler):
677 677
678 678 handler_name = Unicode('emacs')
679 679 esc_strings = List([])
680 680
681 681 def handle(self, line_info):
682 682 """Handle input lines marked by python-mode."""
683 683
684 684 # Currently, nothing is done. Later more functionality can be added
685 685 # here if needed.
686 686
687 687 # The input cache shouldn't be updated
688 688 return line_info.line
689 689
690 690
691 691 #-----------------------------------------------------------------------------
692 692 # Defaults
693 693 #-----------------------------------------------------------------------------
694 694
695 695
696 696 _default_transformers = [
697 697 ]
698 698
699 699 _default_checkers = [
700 700 EmacsChecker,
701 701 MacroChecker,
702 702 IPyAutocallChecker,
703 703 AssignmentChecker,
704 704 AutoMagicChecker,
705 705 PythonOpsChecker,
706 706 AutocallChecker
707 707 ]
708 708
709 709 _default_handlers = [
710 710 PrefilterHandler,
711 711 MacroHandler,
712 712 MagicHandler,
713 713 AutoHandler,
714 714 EmacsHandler
715 715 ]
@@ -1,317 +1,311 b''
1 1 # encoding: utf-8
2 2 """
3 3 An application for managing IPython profiles.
4 4
5 5 To be invoked as the `ipython profile` subcommand.
6 6
7 7 Authors:
8 8
9 9 * Min RK
10 10
11 11 """
12 12 from __future__ import print_function
13 13
14 14 #-----------------------------------------------------------------------------
15 15 # Copyright (C) 2008 The IPython Development Team
16 16 #
17 17 # Distributed under the terms of the BSD License. The full license is in
18 18 # the file COPYING, distributed as part of this software.
19 19 #-----------------------------------------------------------------------------
20 20
21 21 #-----------------------------------------------------------------------------
22 22 # Imports
23 23 #-----------------------------------------------------------------------------
24 24
25 25 import os
26 26
27 from IPython.config.application import Application
27 from traitlets.config.application import Application
28 28 from IPython.core.application import (
29 29 BaseIPythonApplication, base_flags
30 30 )
31 31 from IPython.core.profiledir import ProfileDir
32 32 from IPython.utils.importstring import import_item
33 from IPython.utils.path import get_ipython_dir, get_ipython_package_dir
33 from IPython.paths import get_ipython_dir, get_ipython_package_dir
34 34 from IPython.utils import py3compat
35 from IPython.utils.traitlets import Unicode, Bool, Dict
35 from traitlets import Unicode, Bool, Dict
36 36
37 37 #-----------------------------------------------------------------------------
38 38 # Constants
39 39 #-----------------------------------------------------------------------------
40 40
41 41 create_help = """Create an IPython profile by name
42 42
43 43 Create an ipython profile directory by its name or
44 44 profile directory path. Profile directories contain
45 45 configuration, log and security related files and are named
46 46 using the convention 'profile_<name>'. By default they are
47 47 located in your ipython directory. Once created, you will
48 48 can edit the configuration files in the profile
49 49 directory to configure IPython. Most users will create a
50 50 profile directory by name,
51 51 `ipython profile create myprofile`, which will put the directory
52 52 in `<ipython_dir>/profile_myprofile`.
53 53 """
54 54 list_help = """List available IPython profiles
55 55
56 56 List all available profiles, by profile location, that can
57 57 be found in the current working directly or in the ipython
58 58 directory. Profile directories are named using the convention
59 59 'profile_<profile>'.
60 60 """
61 61 profile_help = """Manage IPython profiles
62 62
63 63 Profile directories contain
64 64 configuration, log and security related files and are named
65 65 using the convention 'profile_<name>'. By default they are
66 66 located in your ipython directory. You can create profiles
67 67 with `ipython profile create <name>`, or see the profiles you
68 68 already have with `ipython profile list`
69 69
70 70 To get started configuring IPython, simply do:
71 71
72 72 $> ipython profile create
73 73
74 74 and IPython will create the default profile in <ipython_dir>/profile_default,
75 75 where you can edit ipython_config.py to start configuring IPython.
76 76
77 77 """
78 78
79 79 _list_examples = "ipython profile list # list all profiles"
80 80
81 81 _create_examples = """
82 82 ipython profile create foo # create profile foo w/ default config files
83 83 ipython profile create foo --reset # restage default config files over current
84 84 ipython profile create foo --parallel # also stage parallel config files
85 85 """
86 86
87 87 _main_examples = """
88 88 ipython profile create -h # show the help string for the create subcommand
89 89 ipython profile list -h # show the help string for the list subcommand
90 90
91 91 ipython locate profile foo # print the path to the directory for profile 'foo'
92 92 """
93 93
94 94 #-----------------------------------------------------------------------------
95 95 # Profile Application Class (for `ipython profile` subcommand)
96 96 #-----------------------------------------------------------------------------
97 97
98 98
99 99 def list_profiles_in(path):
100 100 """list profiles in a given root directory"""
101 101 files = os.listdir(path)
102 102 profiles = []
103 103 for f in files:
104 104 try:
105 105 full_path = os.path.join(path, f)
106 106 except UnicodeError:
107 107 continue
108 108 if os.path.isdir(full_path) and f.startswith('profile_'):
109 109 profiles.append(f.split('_',1)[-1])
110 110 return profiles
111 111
112 112
113 113 def list_bundled_profiles():
114 114 """list profiles that are bundled with IPython."""
115 115 path = os.path.join(get_ipython_package_dir(), u'core', u'profile')
116 116 files = os.listdir(path)
117 117 profiles = []
118 118 for profile in files:
119 119 full_path = os.path.join(path, profile)
120 120 if os.path.isdir(full_path) and profile != "__pycache__":
121 121 profiles.append(profile)
122 122 return profiles
123 123
124 124
125 125 class ProfileLocate(BaseIPythonApplication):
126 126 description = """print the path to an IPython profile dir"""
127 127
128 128 def parse_command_line(self, argv=None):
129 129 super(ProfileLocate, self).parse_command_line(argv)
130 130 if self.extra_args:
131 131 self.profile = self.extra_args[0]
132 132
133 133 def start(self):
134 134 print(self.profile_dir.location)
135 135
136 136
137 137 class ProfileList(Application):
138 138 name = u'ipython-profile'
139 139 description = list_help
140 140 examples = _list_examples
141 141
142 142 aliases = Dict({
143 143 'ipython-dir' : 'ProfileList.ipython_dir',
144 144 'log-level' : 'Application.log_level',
145 145 })
146 146 flags = Dict(dict(
147 147 debug = ({'Application' : {'log_level' : 0}},
148 148 "Set Application.log_level to 0, maximizing log output."
149 149 )
150 150 ))
151 151
152 152 ipython_dir = Unicode(get_ipython_dir(), config=True,
153 153 help="""
154 154 The name of the IPython directory. This directory is used for logging
155 155 configuration (through profiles), history storage, etc. The default
156 156 is usually $HOME/.ipython. This options can also be specified through
157 157 the environment variable IPYTHONDIR.
158 158 """
159 159 )
160 160
161 161
162 162 def _print_profiles(self, profiles):
163 163 """print list of profiles, indented."""
164 164 for profile in profiles:
165 165 print(' %s' % profile)
166 166
167 167 def list_profile_dirs(self):
168 168 profiles = list_bundled_profiles()
169 169 if profiles:
170 170 print()
171 171 print("Available profiles in IPython:")
172 172 self._print_profiles(profiles)
173 173 print()
174 174 print(" The first request for a bundled profile will copy it")
175 175 print(" into your IPython directory (%s)," % self.ipython_dir)
176 176 print(" where you can customize it.")
177 177
178 178 profiles = list_profiles_in(self.ipython_dir)
179 179 if profiles:
180 180 print()
181 181 print("Available profiles in %s:" % self.ipython_dir)
182 182 self._print_profiles(profiles)
183 183
184 184 profiles = list_profiles_in(py3compat.getcwd())
185 185 if profiles:
186 186 print()
187 187 print("Available profiles in current directory (%s):" % py3compat.getcwd())
188 188 self._print_profiles(profiles)
189 189
190 190 print()
191 191 print("To use any of the above profiles, start IPython with:")
192 192 print(" ipython --profile=<name>")
193 193 print()
194 194
195 195 def start(self):
196 196 self.list_profile_dirs()
197 197
198 198
199 199 create_flags = {}
200 200 create_flags.update(base_flags)
201 201 # don't include '--init' flag, which implies running profile create in other apps
202 202 create_flags.pop('init')
203 203 create_flags['reset'] = ({'ProfileCreate': {'overwrite' : True}},
204 204 "reset config files in this profile to the defaults.")
205 205 create_flags['parallel'] = ({'ProfileCreate': {'parallel' : True}},
206 206 "Include the config files for parallel "
207 207 "computing apps (ipengine, ipcontroller, etc.)")
208 208
209 209
210 210 class ProfileCreate(BaseIPythonApplication):
211 211 name = u'ipython-profile'
212 212 description = create_help
213 213 examples = _create_examples
214 214 auto_create = Bool(True, config=False)
215 215 def _log_format_default(self):
216 216 return "[%(name)s] %(message)s"
217 217
218 218 def _copy_config_files_default(self):
219 219 return True
220 220
221 221 parallel = Bool(False, config=True,
222 222 help="whether to include parallel computing config files")
223 223 def _parallel_changed(self, name, old, new):
224 224 parallel_files = [ 'ipcontroller_config.py',
225 225 'ipengine_config.py',
226 226 'ipcluster_config.py'
227 227 ]
228 228 if new:
229 229 for cf in parallel_files:
230 230 self.config_files.append(cf)
231 231 else:
232 232 for cf in parallel_files:
233 233 if cf in self.config_files:
234 234 self.config_files.remove(cf)
235 235
236 236 def parse_command_line(self, argv):
237 237 super(ProfileCreate, self).parse_command_line(argv)
238 238 # accept positional arg as profile name
239 239 if self.extra_args:
240 240 self.profile = self.extra_args[0]
241 241
242 242 flags = Dict(create_flags)
243 243
244 244 classes = [ProfileDir]
245 245
246 246 def _import_app(self, app_path):
247 247 """import an app class"""
248 248 app = None
249 249 name = app_path.rsplit('.', 1)[-1]
250 250 try:
251 251 app = import_item(app_path)
252 252 except ImportError:
253 253 self.log.info("Couldn't import %s, config file will be excluded", name)
254 254 except Exception:
255 255 self.log.warn('Unexpected error importing %s', name, exc_info=True)
256 256 return app
257 257
258 258 def init_config_files(self):
259 259 super(ProfileCreate, self).init_config_files()
260 260 # use local imports, since these classes may import from here
261 261 from IPython.terminal.ipapp import TerminalIPythonApp
262 262 apps = [TerminalIPythonApp]
263 263 for app_path in (
264 'IPython.kernel.zmq.kernelapp.IPKernelApp',
265 'IPython.terminal.console.app.ZMQTerminalIPythonApp',
266 'IPython.qt.console.qtconsoleapp.IPythonQtConsoleApp',
267 'IPython.html.notebookapp.NotebookApp',
268 'IPython.nbconvert.nbconvertapp.NbConvertApp',
264 'ipython_kernel.kernelapp.IPKernelApp',
269 265 ):
270 266 app = self._import_app(app_path)
271 267 if app is not None:
272 268 apps.append(app)
273 269 if self.parallel:
274 from IPython.parallel.apps.ipcontrollerapp import IPControllerApp
275 from IPython.parallel.apps.ipengineapp import IPEngineApp
276 from IPython.parallel.apps.ipclusterapp import IPClusterStart
277 from IPython.parallel.apps.iploggerapp import IPLoggerApp
270 from ipython_parallel.apps.ipcontrollerapp import IPControllerApp
271 from ipython_parallel.apps.ipengineapp import IPEngineApp
272 from ipython_parallel.apps.ipclusterapp import IPClusterStart
278 273 apps.extend([
279 274 IPControllerApp,
280 275 IPEngineApp,
281 276 IPClusterStart,
282 IPLoggerApp,
283 277 ])
284 278 for App in apps:
285 279 app = App()
286 280 app.config.update(self.config)
287 281 app.log = self.log
288 282 app.overwrite = self.overwrite
289 283 app.copy_config_files=True
290 284 app.ipython_dir=self.ipython_dir
291 285 app.profile_dir=self.profile_dir
292 286 app.init_config_files()
293 287
294 288 def stage_default_config_file(self):
295 289 pass
296 290
297 291
298 292 class ProfileApp(Application):
299 293 name = u'ipython profile'
300 294 description = profile_help
301 295 examples = _main_examples
302 296
303 297 subcommands = Dict(dict(
304 298 create = (ProfileCreate, ProfileCreate.description.splitlines()[0]),
305 299 list = (ProfileList, ProfileList.description.splitlines()[0]),
306 300 locate = (ProfileLocate, ProfileLocate.description.splitlines()[0]),
307 301 ))
308 302
309 303 def start(self):
310 304 if self.subapp is None:
311 305 print("No subcommand specified. Must specify one of: %s"%(self.subcommands.keys()))
312 306 print()
313 307 self.print_description()
314 308 self.print_subcommands()
315 309 self.exit(1)
316 310 else:
317 311 return self.subapp.start()
@@ -1,252 +1,235 b''
1 1 # encoding: utf-8
2 2 """An object for managing IPython profile directories."""
3 3
4 4 # Copyright (c) IPython Development Team.
5 5 # Distributed under the terms of the Modified BSD License.
6 6
7 7 import os
8 8 import shutil
9 9 import errno
10 10
11 from IPython.config.configurable import LoggingConfigurable
12 from IPython.utils.path import get_ipython_package_dir, expand_path, ensure_dir_exists
11 from traitlets.config.configurable import LoggingConfigurable
12 from IPython.paths import get_ipython_package_dir
13 from IPython.utils.path import expand_path, ensure_dir_exists
13 14 from IPython.utils import py3compat
14 from IPython.utils.traitlets import Unicode, Bool
15 from traitlets import Unicode, Bool
15 16
16 17 #-----------------------------------------------------------------------------
17 18 # Module errors
18 19 #-----------------------------------------------------------------------------
19 20
20 21 class ProfileDirError(Exception):
21 22 pass
22 23
23 24
24 25 #-----------------------------------------------------------------------------
25 26 # Class for managing profile directories
26 27 #-----------------------------------------------------------------------------
27 28
28 29 class ProfileDir(LoggingConfigurable):
29 30 """An object to manage the profile directory and its resources.
30 31
31 32 The profile directory is used by all IPython applications, to manage
32 33 configuration, logging and security.
33 34
34 35 This object knows how to find, create and manage these directories. This
35 36 should be used by any code that wants to handle profiles.
36 37 """
37 38
38 39 security_dir_name = Unicode('security')
39 40 log_dir_name = Unicode('log')
40 41 startup_dir_name = Unicode('startup')
41 42 pid_dir_name = Unicode('pid')
42 43 static_dir_name = Unicode('static')
43 44 security_dir = Unicode(u'')
44 45 log_dir = Unicode(u'')
45 46 startup_dir = Unicode(u'')
46 47 pid_dir = Unicode(u'')
47 48 static_dir = Unicode(u'')
48 49
49 50 location = Unicode(u'', config=True,
50 51 help="""Set the profile location directly. This overrides the logic used by the
51 52 `profile` option.""",
52 53 )
53 54
54 55 _location_isset = Bool(False) # flag for detecting multiply set location
55 56
56 57 def _location_changed(self, name, old, new):
57 58 if self._location_isset:
58 59 raise RuntimeError("Cannot set profile location more than once.")
59 60 self._location_isset = True
60 61 ensure_dir_exists(new)
61 62
62 63 # ensure config files exist:
63 64 self.security_dir = os.path.join(new, self.security_dir_name)
64 65 self.log_dir = os.path.join(new, self.log_dir_name)
65 66 self.startup_dir = os.path.join(new, self.startup_dir_name)
66 67 self.pid_dir = os.path.join(new, self.pid_dir_name)
67 68 self.static_dir = os.path.join(new, self.static_dir_name)
68 69 self.check_dirs()
69 70
70 71 def _log_dir_changed(self, name, old, new):
71 72 self.check_log_dir()
72 73
73 74 def _mkdir(self, path, mode=None):
74 75 """ensure a directory exists at a given path
75 76
76 77 This is a version of os.mkdir, with the following differences:
77 78
78 79 - returns True if it created the directory, False otherwise
79 80 - ignores EEXIST, protecting against race conditions where
80 81 the dir may have been created in between the check and
81 82 the creation
82 83 - sets permissions if requested and the dir already exists
83 84 """
84 85 if os.path.exists(path):
85 86 if mode and os.stat(path).st_mode != mode:
86 87 try:
87 88 os.chmod(path, mode)
88 89 except OSError:
89 90 self.log.warn(
90 91 "Could not set permissions on %s",
91 92 path
92 93 )
93 94 return False
94 95 try:
95 96 if mode:
96 97 os.mkdir(path, mode)
97 98 else:
98 99 os.mkdir(path)
99 100 except OSError as e:
100 101 if e.errno == errno.EEXIST:
101 102 return False
102 103 else:
103 104 raise
104 105
105 106 return True
106 107
107 108 def check_log_dir(self):
108 109 self._mkdir(self.log_dir)
109 110
110 111 def _startup_dir_changed(self, name, old, new):
111 112 self.check_startup_dir()
112 113
113 114 def check_startup_dir(self):
114 115 self._mkdir(self.startup_dir)
115 116
116 117 readme = os.path.join(self.startup_dir, 'README')
117 118 src = os.path.join(get_ipython_package_dir(), u'core', u'profile', u'README_STARTUP')
118 119
119 120 if not os.path.exists(src):
120 121 self.log.warn("Could not copy README_STARTUP to startup dir. Source file %s does not exist.", src)
121 122
122 123 if os.path.exists(src) and not os.path.exists(readme):
123 124 shutil.copy(src, readme)
124 125
125 126 def _security_dir_changed(self, name, old, new):
126 127 self.check_security_dir()
127 128
128 129 def check_security_dir(self):
129 130 self._mkdir(self.security_dir, 0o40700)
130 131
131 132 def _pid_dir_changed(self, name, old, new):
132 133 self.check_pid_dir()
133 134
134 135 def check_pid_dir(self):
135 136 self._mkdir(self.pid_dir, 0o40700)
136 137
137 138 def _static_dir_changed(self, name, old, new):
138 139 self.check_startup_dir()
139 140
140 def check_static_dir(self):
141 self._mkdir(self.static_dir)
142 custom = os.path.join(self.static_dir, 'custom')
143 self._mkdir(custom)
144 try:
145 from jupyter_notebook import DEFAULT_STATIC_FILES_PATH
146 except ImportError:
147 return
148 for fname in ('custom.js', 'custom.css'):
149 src = os.path.join(DEFAULT_STATIC_FILES_PATH, 'custom', fname)
150 dest = os.path.join(custom, fname)
151 if not os.path.exists(src):
152 self.log.warn("Could not copy default file to static dir. Source file %s does not exist.", src)
153 continue
154 if not os.path.exists(dest):
155 shutil.copy(src, dest)
156
157 141 def check_dirs(self):
158 142 self.check_security_dir()
159 143 self.check_log_dir()
160 144 self.check_pid_dir()
161 145 self.check_startup_dir()
162 self.check_static_dir()
163 146
164 147 def copy_config_file(self, config_file, path=None, overwrite=False):
165 148 """Copy a default config file into the active profile directory.
166 149
167 Default configuration files are kept in :mod:`IPython.config.default`.
150 Default configuration files are kept in :mod:`IPython.core.profile`.
168 151 This function moves these from that location to the working profile
169 152 directory.
170 153 """
171 154 dst = os.path.join(self.location, config_file)
172 155 if os.path.isfile(dst) and not overwrite:
173 156 return False
174 157 if path is None:
175 158 path = os.path.join(get_ipython_package_dir(), u'core', u'profile', u'default')
176 159 src = os.path.join(path, config_file)
177 160 shutil.copy(src, dst)
178 161 return True
179 162
180 163 @classmethod
181 164 def create_profile_dir(cls, profile_dir, config=None):
182 165 """Create a new profile directory given a full path.
183 166
184 167 Parameters
185 168 ----------
186 169 profile_dir : str
187 170 The full path to the profile directory. If it does exist, it will
188 171 be used. If not, it will be created.
189 172 """
190 173 return cls(location=profile_dir, config=config)
191 174
192 175 @classmethod
193 176 def create_profile_dir_by_name(cls, path, name=u'default', config=None):
194 177 """Create a profile dir by profile name and path.
195 178
196 179 Parameters
197 180 ----------
198 181 path : unicode
199 182 The path (directory) to put the profile directory in.
200 183 name : unicode
201 184 The name of the profile. The name of the profile directory will
202 185 be "profile_<profile>".
203 186 """
204 187 if not os.path.isdir(path):
205 188 raise ProfileDirError('Directory not found: %s' % path)
206 189 profile_dir = os.path.join(path, u'profile_' + name)
207 190 return cls(location=profile_dir, config=config)
208 191
209 192 @classmethod
210 193 def find_profile_dir_by_name(cls, ipython_dir, name=u'default', config=None):
211 194 """Find an existing profile dir by profile name, return its ProfileDir.
212 195
213 196 This searches through a sequence of paths for a profile dir. If it
214 197 is not found, a :class:`ProfileDirError` exception will be raised.
215 198
216 199 The search path algorithm is:
217 200 1. ``py3compat.getcwd()``
218 201 2. ``ipython_dir``
219 202
220 203 Parameters
221 204 ----------
222 205 ipython_dir : unicode or str
223 206 The IPython directory to use.
224 207 name : unicode or str
225 208 The name of the profile. The name of the profile directory
226 209 will be "profile_<profile>".
227 210 """
228 211 dirname = u'profile_' + name
229 212 paths = [py3compat.getcwd(), ipython_dir]
230 213 for p in paths:
231 214 profile_dir = os.path.join(p, dirname)
232 215 if os.path.isdir(profile_dir):
233 216 return cls(location=profile_dir, config=config)
234 217 else:
235 218 raise ProfileDirError('Profile directory not found in paths: %s' % dirname)
236 219
237 220 @classmethod
238 221 def find_profile_dir(cls, profile_dir, config=None):
239 222 """Find/create a profile dir and return its ProfileDir.
240 223
241 224 This will create the profile directory if it doesn't exist.
242 225
243 226 Parameters
244 227 ----------
245 228 profile_dir : unicode or str
246 229 The path of the profile directory. This is expanded using
247 230 :func:`IPython.utils.genutils.expand_path`.
248 231 """
249 232 profile_dir = expand_path(profile_dir)
250 233 if not os.path.isdir(profile_dir):
251 234 raise ProfileDirError('Profile directory not found: %s' % profile_dir)
252 235 return cls(location=profile_dir, config=config)
@@ -1,442 +1,442 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Classes for handling input/output prompts.
3 3
4 4 Authors:
5 5
6 6 * Fernando Perez
7 7 * Brian Granger
8 8 * Thomas Kluyver
9 9 """
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Copyright (C) 2008-2011 The IPython Development Team
13 13 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
14 14 #
15 15 # Distributed under the terms of the BSD License. The full license is in
16 16 # the file COPYING, distributed as part of this software.
17 17 #-----------------------------------------------------------------------------
18 18
19 19 #-----------------------------------------------------------------------------
20 20 # Imports
21 21 #-----------------------------------------------------------------------------
22 22
23 23 import os
24 24 import re
25 25 import socket
26 26 import sys
27 27 import time
28 28
29 29 from string import Formatter
30 30
31 from IPython.config.configurable import Configurable
31 from traitlets.config.configurable import Configurable
32 32 from IPython.core import release
33 33 from IPython.utils import coloransi, py3compat
34 from IPython.utils.traitlets import (Unicode, Instance, Dict, Bool, Int)
34 from traitlets import (Unicode, Instance, Dict, Bool, Int)
35 35
36 36 #-----------------------------------------------------------------------------
37 37 # Color schemes for prompts
38 38 #-----------------------------------------------------------------------------
39 39
40 40 InputColors = coloransi.InputTermColors # just a shorthand
41 41 Colors = coloransi.TermColors # just a shorthand
42 42
43 43 color_lists = dict(normal=Colors(), inp=InputColors(), nocolor=coloransi.NoColors())
44 44
45 45 PColNoColors = coloransi.ColorScheme(
46 46 'NoColor',
47 47 in_prompt = InputColors.NoColor, # Input prompt
48 48 in_number = InputColors.NoColor, # Input prompt number
49 49 in_prompt2 = InputColors.NoColor, # Continuation prompt
50 50 in_normal = InputColors.NoColor, # color off (usu. Colors.Normal)
51 51
52 52 out_prompt = Colors.NoColor, # Output prompt
53 53 out_number = Colors.NoColor, # Output prompt number
54 54
55 55 normal = Colors.NoColor # color off (usu. Colors.Normal)
56 56 )
57 57
58 58 # make some schemes as instances so we can copy them for modification easily:
59 59 PColLinux = coloransi.ColorScheme(
60 60 'Linux',
61 61 in_prompt = InputColors.Green,
62 62 in_number = InputColors.LightGreen,
63 63 in_prompt2 = InputColors.Green,
64 64 in_normal = InputColors.Normal, # color off (usu. Colors.Normal)
65 65
66 66 out_prompt = Colors.Red,
67 67 out_number = Colors.LightRed,
68 68
69 69 normal = Colors.Normal
70 70 )
71 71
72 72 # Slightly modified Linux for light backgrounds
73 73 PColLightBG = PColLinux.copy('LightBG')
74 74
75 75 PColLightBG.colors.update(
76 76 in_prompt = InputColors.Blue,
77 77 in_number = InputColors.LightBlue,
78 78 in_prompt2 = InputColors.Blue
79 79 )
80 80
81 81 #-----------------------------------------------------------------------------
82 82 # Utilities
83 83 #-----------------------------------------------------------------------------
84 84
85 85 class LazyEvaluate(object):
86 86 """This is used for formatting strings with values that need to be updated
87 87 at that time, such as the current time or working directory."""
88 88 def __init__(self, func, *args, **kwargs):
89 89 self.func = func
90 90 self.args = args
91 91 self.kwargs = kwargs
92 92
93 93 def __call__(self, **kwargs):
94 94 self.kwargs.update(kwargs)
95 95 return self.func(*self.args, **self.kwargs)
96 96
97 97 def __str__(self):
98 98 return str(self())
99 99
100 100 def __unicode__(self):
101 101 return py3compat.unicode_type(self())
102 102
103 103 def __format__(self, format_spec):
104 104 return format(self(), format_spec)
105 105
106 106 def multiple_replace(dict, text):
107 107 """ Replace in 'text' all occurences of any key in the given
108 108 dictionary by its corresponding value. Returns the new string."""
109 109
110 110 # Function by Xavier Defrang, originally found at:
111 111 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
112 112
113 113 # Create a regular expression from the dictionary keys
114 114 regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
115 115 # For each match, look-up corresponding value in dictionary
116 116 return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
117 117
118 118 #-----------------------------------------------------------------------------
119 119 # Special characters that can be used in prompt templates, mainly bash-like
120 120 #-----------------------------------------------------------------------------
121 121
122 122 # If $HOME isn't defined (Windows), make it an absurd string so that it can
123 123 # never be expanded out into '~'. Basically anything which can never be a
124 124 # reasonable directory name will do, we just want the $HOME -> '~' operation
125 125 # to become a no-op. We pre-compute $HOME here so it's not done on every
126 126 # prompt call.
127 127
128 128 # FIXME:
129 129
130 130 # - This should be turned into a class which does proper namespace management,
131 131 # since the prompt specials need to be evaluated in a certain namespace.
132 132 # Currently it's just globals, which need to be managed manually by code
133 133 # below.
134 134
135 135 # - I also need to split up the color schemes from the prompt specials
136 136 # somehow. I don't have a clean design for that quite yet.
137 137
138 138 HOME = py3compat.str_to_unicode(os.environ.get("HOME","//////:::::ZZZZZ,,,~~~"))
139 139
140 140 # This is needed on FreeBSD, and maybe other systems which symlink /home to
141 141 # /usr/home, but retain the $HOME variable as pointing to /home
142 142 HOME = os.path.realpath(HOME)
143 143
144 144 # We precompute a few more strings here for the prompt_specials, which are
145 145 # fixed once ipython starts. This reduces the runtime overhead of computing
146 146 # prompt strings.
147 147 USER = py3compat.str_to_unicode(os.environ.get("USER",''))
148 148 HOSTNAME = py3compat.str_to_unicode(socket.gethostname())
149 149 HOSTNAME_SHORT = HOSTNAME.split(".")[0]
150 150
151 151 # IronPython doesn't currently have os.getuid() even if
152 152 # os.name == 'posix'; 2/8/2014
153 153 ROOT_SYMBOL = "#" if (os.name=='nt' or sys.platform=='cli' or os.getuid()==0) else "$"
154 154
155 155 prompt_abbreviations = {
156 156 # Prompt/history count
157 157 '%n' : '{color.number}' '{count}' '{color.prompt}',
158 158 r'\#': '{color.number}' '{count}' '{color.prompt}',
159 159 # Just the prompt counter number, WITHOUT any coloring wrappers, so users
160 160 # can get numbers displayed in whatever color they want.
161 161 r'\N': '{count}',
162 162
163 163 # Prompt/history count, with the actual digits replaced by dots. Used
164 164 # mainly in continuation prompts (prompt_in2)
165 165 r'\D': '{dots}',
166 166
167 167 # Current time
168 168 r'\T' : '{time}',
169 169 # Current working directory
170 170 r'\w': '{cwd}',
171 171 # Basename of current working directory.
172 172 # (use os.sep to make this portable across OSes)
173 173 r'\W' : '{cwd_last}',
174 174 # These X<N> are an extension to the normal bash prompts. They return
175 175 # N terms of the path, after replacing $HOME with '~'
176 176 r'\X0': '{cwd_x[0]}',
177 177 r'\X1': '{cwd_x[1]}',
178 178 r'\X2': '{cwd_x[2]}',
179 179 r'\X3': '{cwd_x[3]}',
180 180 r'\X4': '{cwd_x[4]}',
181 181 r'\X5': '{cwd_x[5]}',
182 182 # Y<N> are similar to X<N>, but they show '~' if it's the directory
183 183 # N+1 in the list. Somewhat like %cN in tcsh.
184 184 r'\Y0': '{cwd_y[0]}',
185 185 r'\Y1': '{cwd_y[1]}',
186 186 r'\Y2': '{cwd_y[2]}',
187 187 r'\Y3': '{cwd_y[3]}',
188 188 r'\Y4': '{cwd_y[4]}',
189 189 r'\Y5': '{cwd_y[5]}',
190 190 # Hostname up to first .
191 191 r'\h': HOSTNAME_SHORT,
192 192 # Full hostname
193 193 r'\H': HOSTNAME,
194 194 # Username of current user
195 195 r'\u': USER,
196 196 # Escaped '\'
197 197 '\\\\': '\\',
198 198 # Newline
199 199 r'\n': '\n',
200 200 # Carriage return
201 201 r'\r': '\r',
202 202 # Release version
203 203 r'\v': release.version,
204 204 # Root symbol ($ or #)
205 205 r'\$': ROOT_SYMBOL,
206 206 }
207 207
208 208 #-----------------------------------------------------------------------------
209 209 # More utilities
210 210 #-----------------------------------------------------------------------------
211 211
212 212 def cwd_filt(depth):
213 213 """Return the last depth elements of the current working directory.
214 214
215 215 $HOME is always replaced with '~'.
216 216 If depth==0, the full path is returned."""
217 217
218 218 cwd = py3compat.getcwd().replace(HOME,"~")
219 219 out = os.sep.join(cwd.split(os.sep)[-depth:])
220 220 return out or os.sep
221 221
222 222 def cwd_filt2(depth):
223 223 """Return the last depth elements of the current working directory.
224 224
225 225 $HOME is always replaced with '~'.
226 226 If depth==0, the full path is returned."""
227 227
228 228 full_cwd = py3compat.getcwd()
229 229 cwd = full_cwd.replace(HOME,"~").split(os.sep)
230 230 if '~' in cwd and len(cwd) == depth+1:
231 231 depth += 1
232 232 drivepart = ''
233 233 if sys.platform == 'win32' and len(cwd) > depth:
234 234 drivepart = os.path.splitdrive(full_cwd)[0]
235 235 out = drivepart + '/'.join(cwd[-depth:])
236 236
237 237 return out or os.sep
238 238
239 239 #-----------------------------------------------------------------------------
240 240 # Prompt classes
241 241 #-----------------------------------------------------------------------------
242 242
243 243 lazily_evaluate = {'time': LazyEvaluate(time.strftime, "%H:%M:%S"),
244 244 'cwd': LazyEvaluate(py3compat.getcwd),
245 245 'cwd_last': LazyEvaluate(lambda: py3compat.getcwd().split(os.sep)[-1]),
246 246 'cwd_x': [LazyEvaluate(lambda: py3compat.getcwd().replace(HOME,"~"))] +\
247 247 [LazyEvaluate(cwd_filt, x) for x in range(1,6)],
248 248 'cwd_y': [LazyEvaluate(cwd_filt2, x) for x in range(6)]
249 249 }
250 250
251 251 def _lenlastline(s):
252 252 """Get the length of the last line. More intelligent than
253 253 len(s.splitlines()[-1]).
254 254 """
255 255 if not s or s.endswith(('\n', '\r')):
256 256 return 0
257 257 return len(s.splitlines()[-1])
258 258
259 259
260 260 class UserNSFormatter(Formatter):
261 261 """A Formatter that falls back on a shell's user_ns and __builtins__ for name resolution"""
262 262 def __init__(self, shell):
263 263 self.shell = shell
264 264
265 265 def get_value(self, key, args, kwargs):
266 266 # try regular formatting first:
267 267 try:
268 268 return Formatter.get_value(self, key, args, kwargs)
269 269 except Exception:
270 270 pass
271 271 # next, look in user_ns and builtins:
272 272 for container in (self.shell.user_ns, __builtins__):
273 273 if key in container:
274 274 return container[key]
275 275 # nothing found, put error message in its place
276 276 return "<ERROR: '%s' not found>" % key
277 277
278 278
279 279 class PromptManager(Configurable):
280 280 """This is the primary interface for producing IPython's prompts."""
281 281 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
282 282
283 283 color_scheme_table = Instance(coloransi.ColorSchemeTable, allow_none=True)
284 284 color_scheme = Unicode('Linux', config=True)
285 285 def _color_scheme_changed(self, name, new_value):
286 286 self.color_scheme_table.set_active_scheme(new_value)
287 287 for pname in ['in', 'in2', 'out', 'rewrite']:
288 288 # We need to recalculate the number of invisible characters
289 289 self.update_prompt(pname)
290 290
291 291 lazy_evaluate_fields = Dict(help="""
292 292 This maps field names used in the prompt templates to functions which
293 293 will be called when the prompt is rendered. This allows us to include
294 294 things like the current time in the prompts. Functions are only called
295 295 if they are used in the prompt.
296 296 """)
297 297 def _lazy_evaluate_fields_default(self): return lazily_evaluate.copy()
298 298
299 299 in_template = Unicode('In [\\#]: ', config=True,
300 300 help="Input prompt. '\\#' will be transformed to the prompt number")
301 301 in2_template = Unicode(' .\\D.: ', config=True,
302 302 help="Continuation prompt.")
303 303 out_template = Unicode('Out[\\#]: ', config=True,
304 304 help="Output prompt. '\\#' will be transformed to the prompt number")
305 305
306 306 justify = Bool(True, config=True, help="""
307 307 If True (default), each prompt will be right-aligned with the
308 308 preceding one.
309 309 """)
310 310
311 311 # We actually store the expanded templates here:
312 312 templates = Dict()
313 313
314 314 # The number of characters in the last prompt rendered, not including
315 315 # colour characters.
316 316 width = Int()
317 317 txtwidth = Int() # Not including right-justification
318 318
319 319 # The number of characters in each prompt which don't contribute to width
320 320 invisible_chars = Dict()
321 321 def _invisible_chars_default(self):
322 322 return {'in': 0, 'in2': 0, 'out': 0, 'rewrite':0}
323 323
324 324 def __init__(self, shell, **kwargs):
325 325 super(PromptManager, self).__init__(shell=shell, **kwargs)
326 326
327 327 # Prepare colour scheme table
328 328 self.color_scheme_table = coloransi.ColorSchemeTable([PColNoColors,
329 329 PColLinux, PColLightBG], self.color_scheme)
330 330
331 331 self._formatter = UserNSFormatter(shell)
332 332 # Prepare templates & numbers of invisible characters
333 333 self.update_prompt('in', self.in_template)
334 334 self.update_prompt('in2', self.in2_template)
335 335 self.update_prompt('out', self.out_template)
336 336 self.update_prompt('rewrite')
337 337 self.on_trait_change(self._update_prompt_trait, ['in_template',
338 338 'in2_template', 'out_template'])
339 339
340 340 def update_prompt(self, name, new_template=None):
341 341 """This is called when a prompt template is updated. It processes
342 342 abbreviations used in the prompt template (like \#) and calculates how
343 343 many invisible characters (ANSI colour escapes) the resulting prompt
344 344 contains.
345 345
346 346 It is also called for each prompt on changing the colour scheme. In both
347 347 cases, traitlets should take care of calling this automatically.
348 348 """
349 349 if new_template is not None:
350 350 self.templates[name] = multiple_replace(prompt_abbreviations, new_template)
351 351 # We count invisible characters (colour escapes) on the last line of the
352 352 # prompt, to calculate the width for lining up subsequent prompts.
353 353 invis_chars = _lenlastline(self._render(name, color=True)) - \
354 354 _lenlastline(self._render(name, color=False))
355 355 self.invisible_chars[name] = invis_chars
356 356
357 357 def _update_prompt_trait(self, traitname, new_template):
358 358 name = traitname[:-9] # Cut off '_template'
359 359 self.update_prompt(name, new_template)
360 360
361 361 def _render(self, name, color=True, **kwargs):
362 362 """Render but don't justify, or update the width or txtwidth attributes.
363 363 """
364 364 if name == 'rewrite':
365 365 return self._render_rewrite(color=color)
366 366
367 367 if color:
368 368 scheme = self.color_scheme_table.active_colors
369 369 if name=='out':
370 370 colors = color_lists['normal']
371 371 colors.number, colors.prompt, colors.normal = \
372 372 scheme.out_number, scheme.out_prompt, scheme.normal
373 373 else:
374 374 colors = color_lists['inp']
375 375 colors.number, colors.prompt, colors.normal = \
376 376 scheme.in_number, scheme.in_prompt, scheme.in_normal
377 377 if name=='in2':
378 378 colors.prompt = scheme.in_prompt2
379 379 else:
380 380 # No color
381 381 colors = color_lists['nocolor']
382 382 colors.number, colors.prompt, colors.normal = '', '', ''
383 383
384 384 count = self.shell.execution_count # Shorthand
385 385 # Build the dictionary to be passed to string formatting
386 386 fmtargs = dict(color=colors, count=count,
387 387 dots="."*len(str(count)),
388 388 width=self.width, txtwidth=self.txtwidth )
389 389 fmtargs.update(self.lazy_evaluate_fields)
390 390 fmtargs.update(kwargs)
391 391
392 392 # Prepare the prompt
393 393 prompt = colors.prompt + self.templates[name] + colors.normal
394 394
395 395 # Fill in required fields
396 396 return self._formatter.format(prompt, **fmtargs)
397 397
398 398 def _render_rewrite(self, color=True):
399 399 """Render the ---> rewrite prompt."""
400 400 if color:
401 401 scheme = self.color_scheme_table.active_colors
402 402 # We need a non-input version of these escapes
403 403 color_prompt = scheme.in_prompt.replace("\001","").replace("\002","")
404 404 color_normal = scheme.normal
405 405 else:
406 406 color_prompt, color_normal = '', ''
407 407
408 408 return color_prompt + "-> ".rjust(self.txtwidth, "-") + color_normal
409 409
410 410 def render(self, name, color=True, just=None, **kwargs):
411 411 """
412 412 Render the selected prompt.
413 413
414 414 Parameters
415 415 ----------
416 416 name : str
417 417 Which prompt to render. One of 'in', 'in2', 'out', 'rewrite'
418 418 color : bool
419 419 If True (default), include ANSI escape sequences for a coloured prompt.
420 420 just : bool
421 421 If True, justify the prompt to the width of the last prompt. The
422 422 default is stored in self.justify.
423 423 **kwargs :
424 424 Additional arguments will be passed to the string formatting operation,
425 425 so they can override the values that would otherwise fill in the
426 426 template.
427 427
428 428 Returns
429 429 -------
430 430 A string containing the rendered prompt.
431 431 """
432 432 res = self._render(name, color=color, **kwargs)
433 433
434 434 # Handle justification of prompt
435 435 invis_chars = self.invisible_chars[name] if color else 0
436 436 self.txtwidth = _lenlastline(res) - invis_chars
437 437 just = self.justify if (just is None) else just
438 438 # If the prompt spans more than one line, don't try to justify it:
439 439 if just and name != 'in' and ('\n' not in res) and ('\r' not in res):
440 440 res = res.rjust(self.width + invis_chars)
441 441 self.width = _lenlastline(res) - invis_chars
442 442 return res
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 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