Show More
The requested changes are too big and content was truncated. Show full diff
@@ -1,257 +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 | 27 | from traitlets.config.configurable import Configurable |
|
28 | 28 | from IPython.core.error import UsageError |
|
29 | 29 | |
|
30 | from IPython.utils.py3compat import string_types | |
|
31 | 30 | from traitlets import List, Instance |
|
32 | 31 | from logging import error |
|
33 | 32 | |
|
34 | 33 | #----------------------------------------------------------------------------- |
|
35 | 34 | # Utilities |
|
36 | 35 | #----------------------------------------------------------------------------- |
|
37 | 36 | |
|
38 | 37 | # This is used as the pattern for calls to split_user_input. |
|
39 | 38 | shell_line_split = re.compile(r'^(\s*)()(\S+)(.*$)') |
|
40 | 39 | |
|
41 | 40 | def default_aliases(): |
|
42 | 41 | """Return list of shell aliases to auto-define. |
|
43 | 42 | """ |
|
44 | 43 | # Note: the aliases defined here should be safe to use on a kernel |
|
45 | 44 | # regardless of what frontend it is attached to. Frontends that use a |
|
46 | 45 | # kernel in-process can define additional aliases that will only work in |
|
47 | 46 | # their case. For example, things like 'less' or 'clear' that manipulate |
|
48 | 47 | # the terminal should NOT be declared here, as they will only work if the |
|
49 | 48 | # kernel is running inside a true terminal, and not over the network. |
|
50 | 49 | |
|
51 | 50 | if os.name == 'posix': |
|
52 | 51 | default_aliases = [('mkdir', 'mkdir'), ('rmdir', 'rmdir'), |
|
53 | 52 | ('mv', 'mv'), ('rm', 'rm'), ('cp', 'cp'), |
|
54 | 53 | ('cat', 'cat'), |
|
55 | 54 | ] |
|
56 | 55 | # Useful set of ls aliases. The GNU and BSD options are a little |
|
57 | 56 | # different, so we make aliases that provide as similar as possible |
|
58 | 57 | # behavior in ipython, by passing the right flags for each platform |
|
59 | 58 | if sys.platform.startswith('linux'): |
|
60 | 59 | ls_aliases = [('ls', 'ls -F --color'), |
|
61 | 60 | # long ls |
|
62 | 61 | ('ll', 'ls -F -o --color'), |
|
63 | 62 | # ls normal files only |
|
64 | 63 | ('lf', 'ls -F -o --color %l | grep ^-'), |
|
65 | 64 | # ls symbolic links |
|
66 | 65 | ('lk', 'ls -F -o --color %l | grep ^l'), |
|
67 | 66 | # directories or links to directories, |
|
68 | 67 | ('ldir', 'ls -F -o --color %l | grep /$'), |
|
69 | 68 | # things which are executable |
|
70 | 69 | ('lx', 'ls -F -o --color %l | grep ^-..x'), |
|
71 | 70 | ] |
|
72 | 71 | elif sys.platform.startswith('openbsd') or sys.platform.startswith('netbsd'): |
|
73 | 72 | # OpenBSD, NetBSD. The ls implementation on these platforms do not support |
|
74 | 73 | # the -G switch and lack the ability to use colorized output. |
|
75 | 74 | ls_aliases = [('ls', 'ls -F'), |
|
76 | 75 | # long ls |
|
77 | 76 | ('ll', 'ls -F -l'), |
|
78 | 77 | # ls normal files only |
|
79 | 78 | ('lf', 'ls -F -l %l | grep ^-'), |
|
80 | 79 | # ls symbolic links |
|
81 | 80 | ('lk', 'ls -F -l %l | grep ^l'), |
|
82 | 81 | # directories or links to directories, |
|
83 | 82 | ('ldir', 'ls -F -l %l | grep /$'), |
|
84 | 83 | # things which are executable |
|
85 | 84 | ('lx', 'ls -F -l %l | grep ^-..x'), |
|
86 | 85 | ] |
|
87 | 86 | else: |
|
88 | 87 | # BSD, OSX, etc. |
|
89 | 88 | ls_aliases = [('ls', 'ls -F -G'), |
|
90 | 89 | # long ls |
|
91 | 90 | ('ll', 'ls -F -l -G'), |
|
92 | 91 | # ls normal files only |
|
93 | 92 | ('lf', 'ls -F -l -G %l | grep ^-'), |
|
94 | 93 | # ls symbolic links |
|
95 | 94 | ('lk', 'ls -F -l -G %l | grep ^l'), |
|
96 | 95 | # directories or links to directories, |
|
97 | 96 | ('ldir', 'ls -F -G -l %l | grep /$'), |
|
98 | 97 | # things which are executable |
|
99 | 98 | ('lx', 'ls -F -l -G %l | grep ^-..x'), |
|
100 | 99 | ] |
|
101 | 100 | default_aliases = default_aliases + ls_aliases |
|
102 | 101 | elif os.name in ['nt', 'dos']: |
|
103 | 102 | default_aliases = [('ls', 'dir /on'), |
|
104 | 103 | ('ddir', 'dir /ad /on'), ('ldir', 'dir /ad /on'), |
|
105 | 104 | ('mkdir', 'mkdir'), ('rmdir', 'rmdir'), |
|
106 | 105 | ('echo', 'echo'), ('ren', 'ren'), ('copy', 'copy'), |
|
107 | 106 | ] |
|
108 | 107 | else: |
|
109 | 108 | default_aliases = [] |
|
110 | 109 | |
|
111 | 110 | return default_aliases |
|
112 | 111 | |
|
113 | 112 | |
|
114 | 113 | class AliasError(Exception): |
|
115 | 114 | pass |
|
116 | 115 | |
|
117 | 116 | |
|
118 | 117 | class InvalidAliasError(AliasError): |
|
119 | 118 | pass |
|
120 | 119 | |
|
121 | 120 | class Alias(object): |
|
122 | 121 | """Callable object storing the details of one alias. |
|
123 | 122 | |
|
124 | 123 | Instances are registered as magic functions to allow use of aliases. |
|
125 | 124 | """ |
|
126 | 125 | |
|
127 | 126 | # Prepare blacklist |
|
128 | 127 | blacklist = {'cd','popd','pushd','dhist','alias','unalias'} |
|
129 | 128 | |
|
130 | 129 | def __init__(self, shell, name, cmd): |
|
131 | 130 | self.shell = shell |
|
132 | 131 | self.name = name |
|
133 | 132 | self.cmd = cmd |
|
134 | 133 | self.__doc__ = "Alias for `!{}`".format(cmd) |
|
135 | 134 | self.nargs = self.validate() |
|
136 | 135 | |
|
137 | 136 | def validate(self): |
|
138 | 137 | """Validate the alias, and return the number of arguments.""" |
|
139 | 138 | if self.name in self.blacklist: |
|
140 | 139 | raise InvalidAliasError("The name %s can't be aliased " |
|
141 | 140 | "because it is a keyword or builtin." % self.name) |
|
142 | 141 | try: |
|
143 | 142 | caller = self.shell.magics_manager.magics['line'][self.name] |
|
144 | 143 | except KeyError: |
|
145 | 144 | pass |
|
146 | 145 | else: |
|
147 | 146 | if not isinstance(caller, Alias): |
|
148 | 147 | raise InvalidAliasError("The name %s can't be aliased " |
|
149 | 148 | "because it is another magic command." % self.name) |
|
150 | 149 | |
|
151 |
if not (isinstance(self.cmd, str |
|
|
150 | if not (isinstance(self.cmd, str)): | |
|
152 | 151 | raise InvalidAliasError("An alias command must be a string, " |
|
153 | 152 | "got: %r" % self.cmd) |
|
154 | 153 | |
|
155 | 154 | nargs = self.cmd.count('%s') - self.cmd.count('%%s') |
|
156 | 155 | |
|
157 | 156 | if (nargs > 0) and (self.cmd.find('%l') >= 0): |
|
158 | 157 | raise InvalidAliasError('The %s and %l specifiers are mutually ' |
|
159 | 158 | 'exclusive in alias definitions.') |
|
160 | 159 | |
|
161 | 160 | return nargs |
|
162 | 161 | |
|
163 | 162 | def __repr__(self): |
|
164 | 163 | return "<alias {} for {!r}>".format(self.name, self.cmd) |
|
165 | 164 | |
|
166 | 165 | def __call__(self, rest=''): |
|
167 | 166 | cmd = self.cmd |
|
168 | 167 | nargs = self.nargs |
|
169 | 168 | # Expand the %l special to be the user's input line |
|
170 | 169 | if cmd.find('%l') >= 0: |
|
171 | 170 | cmd = cmd.replace('%l', rest) |
|
172 | 171 | rest = '' |
|
173 | 172 | |
|
174 | 173 | if nargs==0: |
|
175 | 174 | if cmd.find('%%s') >= 1: |
|
176 | 175 | cmd = cmd.replace('%%s', '%s') |
|
177 | 176 | # Simple, argument-less aliases |
|
178 | 177 | cmd = '%s %s' % (cmd, rest) |
|
179 | 178 | else: |
|
180 | 179 | # Handle aliases with positional arguments |
|
181 | 180 | args = rest.split(None, nargs) |
|
182 | 181 | if len(args) < nargs: |
|
183 | 182 | raise UsageError('Alias <%s> requires %s arguments, %s given.' % |
|
184 | 183 | (self.name, nargs, len(args))) |
|
185 | 184 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) |
|
186 | 185 | |
|
187 | 186 | self.shell.system(cmd) |
|
188 | 187 | |
|
189 | 188 | #----------------------------------------------------------------------------- |
|
190 | 189 | # Main AliasManager class |
|
191 | 190 | #----------------------------------------------------------------------------- |
|
192 | 191 | |
|
193 | 192 | class AliasManager(Configurable): |
|
194 | 193 | |
|
195 | 194 | default_aliases = List(default_aliases()).tag(config=True) |
|
196 | 195 | user_aliases = List(default_value=[]).tag(config=True) |
|
197 | 196 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True) |
|
198 | 197 | |
|
199 | 198 | def __init__(self, shell=None, **kwargs): |
|
200 | 199 | super(AliasManager, self).__init__(shell=shell, **kwargs) |
|
201 | 200 | # For convenient access |
|
202 | 201 | self.linemagics = self.shell.magics_manager.magics['line'] |
|
203 | 202 | self.init_aliases() |
|
204 | 203 | |
|
205 | 204 | def init_aliases(self): |
|
206 | 205 | # Load default & user aliases |
|
207 | 206 | for name, cmd in self.default_aliases + self.user_aliases: |
|
208 | 207 | self.soft_define_alias(name, cmd) |
|
209 | 208 | |
|
210 | 209 | @property |
|
211 | 210 | def aliases(self): |
|
212 | 211 | return [(n, func.cmd) for (n, func) in self.linemagics.items() |
|
213 | 212 | if isinstance(func, Alias)] |
|
214 | 213 | |
|
215 | 214 | def soft_define_alias(self, name, cmd): |
|
216 | 215 | """Define an alias, but don't raise on an AliasError.""" |
|
217 | 216 | try: |
|
218 | 217 | self.define_alias(name, cmd) |
|
219 | 218 | except AliasError as e: |
|
220 | 219 | error("Invalid alias: %s" % e) |
|
221 | 220 | |
|
222 | 221 | def define_alias(self, name, cmd): |
|
223 | 222 | """Define a new alias after validating it. |
|
224 | 223 | |
|
225 | 224 | This will raise an :exc:`AliasError` if there are validation |
|
226 | 225 | problems. |
|
227 | 226 | """ |
|
228 | 227 | caller = Alias(shell=self.shell, name=name, cmd=cmd) |
|
229 | 228 | self.shell.magics_manager.register_function(caller, magic_kind='line', |
|
230 | 229 | magic_name=name) |
|
231 | 230 | |
|
232 | 231 | def get_alias(self, name): |
|
233 | 232 | """Return an alias, or None if no alias by that name exists.""" |
|
234 | 233 | aname = self.linemagics.get(name, None) |
|
235 | 234 | return aname if isinstance(aname, Alias) else None |
|
236 | 235 | |
|
237 | 236 | def is_alias(self, name): |
|
238 | 237 | """Return whether or not a given name has been defined as an alias""" |
|
239 | 238 | return self.get_alias(name) is not None |
|
240 | 239 | |
|
241 | 240 | def undefine_alias(self, name): |
|
242 | 241 | if self.is_alias(name): |
|
243 | 242 | del self.linemagics[name] |
|
244 | 243 | else: |
|
245 | 244 | raise ValueError('%s is not an alias' % name) |
|
246 | 245 | |
|
247 | 246 | def clear_aliases(self): |
|
248 | 247 | for name, cmd in self.aliases: |
|
249 | 248 | self.undefine_alias(name) |
|
250 | 249 | |
|
251 | 250 | def retrieve_alias(self, name): |
|
252 | 251 | """Retrieve the command to which an alias expands.""" |
|
253 | 252 | caller = self.get_alias(name) |
|
254 | 253 | if caller: |
|
255 | 254 | return caller.cmd |
|
256 | 255 | else: |
|
257 | 256 | raise ValueError('%s is not an alias' % name) |
@@ -1,458 +1,458 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 | from copy import deepcopy |
|
17 | 17 | import glob |
|
18 | 18 | import logging |
|
19 | 19 | import os |
|
20 | 20 | import shutil |
|
21 | 21 | import sys |
|
22 | 22 | |
|
23 | 23 | from traitlets.config.application import Application, catch_config_error |
|
24 | 24 | from traitlets.config.loader import ConfigFileNotFound, PyFileConfigLoader |
|
25 | 25 | from IPython.core import release, crashhandler |
|
26 | 26 | from IPython.core.profiledir import ProfileDir, ProfileDirError |
|
27 | 27 | from IPython.paths import get_ipython_dir, get_ipython_package_dir |
|
28 | 28 | from IPython.utils.path import ensure_dir_exists |
|
29 | 29 | from IPython.utils import py3compat |
|
30 | 30 | from traitlets import ( |
|
31 | 31 | List, Unicode, Type, Bool, Dict, Set, Instance, Undefined, |
|
32 | 32 | default, observe, |
|
33 | 33 | ) |
|
34 | 34 | |
|
35 | 35 | if os.name == 'nt': |
|
36 | 36 | programdata = os.environ.get('PROGRAMDATA', None) |
|
37 | 37 | if programdata: |
|
38 | 38 | SYSTEM_CONFIG_DIRS = [os.path.join(programdata, 'ipython')] |
|
39 | 39 | else: # PROGRAMDATA is not defined by default on XP. |
|
40 | 40 | SYSTEM_CONFIG_DIRS = [] |
|
41 | 41 | else: |
|
42 | 42 | SYSTEM_CONFIG_DIRS = [ |
|
43 | 43 | "/usr/local/etc/ipython", |
|
44 | 44 | "/etc/ipython", |
|
45 | 45 | ] |
|
46 | 46 | |
|
47 | 47 | _envvar = os.environ.get('IPYTHON_SUPPRESS_CONFIG_ERRORS') |
|
48 | 48 | if _envvar in {None, ''}: |
|
49 | 49 | IPYTHON_SUPPRESS_CONFIG_ERRORS = None |
|
50 | 50 | else: |
|
51 | 51 | if _envvar.lower() in {'1','true'}: |
|
52 | 52 | IPYTHON_SUPPRESS_CONFIG_ERRORS = True |
|
53 | 53 | elif _envvar.lower() in {'0','false'} : |
|
54 | 54 | IPYTHON_SUPPRESS_CONFIG_ERRORS = False |
|
55 | 55 | else: |
|
56 | 56 | sys.exit("Unsupported value for environment variable: 'IPYTHON_SUPPRESS_CONFIG_ERRORS' is set to '%s' which is none of {'0', '1', 'false', 'true', ''}."% _envvar ) |
|
57 | 57 | |
|
58 | 58 | # aliases and flags |
|
59 | 59 | |
|
60 | 60 | base_aliases = { |
|
61 | 61 | 'profile-dir' : 'ProfileDir.location', |
|
62 | 62 | 'profile' : 'BaseIPythonApplication.profile', |
|
63 | 63 | 'ipython-dir' : 'BaseIPythonApplication.ipython_dir', |
|
64 | 64 | 'log-level' : 'Application.log_level', |
|
65 | 65 | 'config' : 'BaseIPythonApplication.extra_config_file', |
|
66 | 66 | } |
|
67 | 67 | |
|
68 | 68 | base_flags = dict( |
|
69 | 69 | debug = ({'Application' : {'log_level' : logging.DEBUG}}, |
|
70 | 70 | "set log level to logging.DEBUG (maximize logging output)"), |
|
71 | 71 | quiet = ({'Application' : {'log_level' : logging.CRITICAL}}, |
|
72 | 72 | "set log level to logging.CRITICAL (minimize logging output)"), |
|
73 | 73 | init = ({'BaseIPythonApplication' : { |
|
74 | 74 | 'copy_config_files' : True, |
|
75 | 75 | 'auto_create' : True} |
|
76 | 76 | }, """Initialize profile with default config files. This is equivalent |
|
77 | 77 | to running `ipython profile create <profile>` prior to startup. |
|
78 | 78 | """) |
|
79 | 79 | ) |
|
80 | 80 | |
|
81 | 81 | class ProfileAwareConfigLoader(PyFileConfigLoader): |
|
82 | 82 | """A Python file config loader that is aware of IPython profiles.""" |
|
83 | 83 | def load_subconfig(self, fname, path=None, profile=None): |
|
84 | 84 | if profile is not None: |
|
85 | 85 | try: |
|
86 | 86 | profile_dir = ProfileDir.find_profile_dir_by_name( |
|
87 | 87 | get_ipython_dir(), |
|
88 | 88 | profile, |
|
89 | 89 | ) |
|
90 | 90 | except ProfileDirError: |
|
91 | 91 | return |
|
92 | 92 | path = profile_dir.location |
|
93 | 93 | return super(ProfileAwareConfigLoader, self).load_subconfig(fname, path=path) |
|
94 | 94 | |
|
95 | 95 | class BaseIPythonApplication(Application): |
|
96 | 96 | |
|
97 | 97 | name = Unicode(u'ipython') |
|
98 | 98 | description = Unicode(u'IPython: an enhanced interactive Python shell.') |
|
99 | 99 | version = Unicode(release.version) |
|
100 | 100 | |
|
101 | 101 | aliases = Dict(base_aliases) |
|
102 | 102 | flags = Dict(base_flags) |
|
103 | 103 | classes = List([ProfileDir]) |
|
104 | 104 | |
|
105 | 105 | # enable `load_subconfig('cfg.py', profile='name')` |
|
106 | 106 | python_config_loader_class = ProfileAwareConfigLoader |
|
107 | 107 | |
|
108 | 108 | # Track whether the config_file has changed, |
|
109 | 109 | # because some logic happens only if we aren't using the default. |
|
110 | 110 | config_file_specified = Set() |
|
111 | 111 | |
|
112 | 112 | config_file_name = Unicode() |
|
113 | 113 | @default('config_file_name') |
|
114 | 114 | def _config_file_name_default(self): |
|
115 | 115 | return self.name.replace('-','_') + u'_config.py' |
|
116 | 116 | @observe('config_file_name') |
|
117 | 117 | def _config_file_name_changed(self, change): |
|
118 | 118 | if change['new'] != change['old']: |
|
119 | 119 | self.config_file_specified.add(change['new']) |
|
120 | 120 | |
|
121 | 121 | # The directory that contains IPython's builtin profiles. |
|
122 | 122 | builtin_profile_dir = Unicode( |
|
123 | 123 | os.path.join(get_ipython_package_dir(), u'config', u'profile', u'default') |
|
124 | 124 | ) |
|
125 | 125 | |
|
126 | 126 | config_file_paths = List(Unicode()) |
|
127 | 127 | @default('config_file_paths') |
|
128 | 128 | def _config_file_paths_default(self): |
|
129 |
return [ |
|
|
129 | return [os.getcwd()] | |
|
130 | 130 | |
|
131 | 131 | extra_config_file = Unicode( |
|
132 | 132 | help="""Path to an extra config file to load. |
|
133 | 133 | |
|
134 | 134 | If specified, load this config file in addition to any other IPython config. |
|
135 | 135 | """).tag(config=True) |
|
136 | 136 | @observe('extra_config_file') |
|
137 | 137 | def _extra_config_file_changed(self, change): |
|
138 | 138 | old = change['old'] |
|
139 | 139 | new = change['new'] |
|
140 | 140 | try: |
|
141 | 141 | self.config_files.remove(old) |
|
142 | 142 | except ValueError: |
|
143 | 143 | pass |
|
144 | 144 | self.config_file_specified.add(new) |
|
145 | 145 | self.config_files.append(new) |
|
146 | 146 | |
|
147 | 147 | profile = Unicode(u'default', |
|
148 | 148 | help="""The IPython profile to use.""" |
|
149 | 149 | ).tag(config=True) |
|
150 | 150 | |
|
151 | 151 | @observe('profile') |
|
152 | 152 | def _profile_changed(self, change): |
|
153 | 153 | self.builtin_profile_dir = os.path.join( |
|
154 | 154 | get_ipython_package_dir(), u'config', u'profile', change['new'] |
|
155 | 155 | ) |
|
156 | 156 | |
|
157 | 157 | ipython_dir = Unicode( |
|
158 | 158 | help=""" |
|
159 | 159 | The name of the IPython directory. This directory is used for logging |
|
160 | 160 | configuration (through profiles), history storage, etc. The default |
|
161 | 161 | is usually $HOME/.ipython. This option can also be specified through |
|
162 | 162 | the environment variable IPYTHONDIR. |
|
163 | 163 | """ |
|
164 | 164 | ).tag(config=True) |
|
165 | 165 | @default('ipython_dir') |
|
166 | 166 | def _ipython_dir_default(self): |
|
167 | 167 | d = get_ipython_dir() |
|
168 | 168 | self._ipython_dir_changed({ |
|
169 | 169 | 'name': 'ipython_dir', |
|
170 | 170 | 'old': d, |
|
171 | 171 | 'new': d, |
|
172 | 172 | }) |
|
173 | 173 | return d |
|
174 | 174 | |
|
175 | 175 | _in_init_profile_dir = False |
|
176 | 176 | profile_dir = Instance(ProfileDir, allow_none=True) |
|
177 | 177 | @default('profile_dir') |
|
178 | 178 | def _profile_dir_default(self): |
|
179 | 179 | # avoid recursion |
|
180 | 180 | if self._in_init_profile_dir: |
|
181 | 181 | return |
|
182 | 182 | # profile_dir requested early, force initialization |
|
183 | 183 | self.init_profile_dir() |
|
184 | 184 | return self.profile_dir |
|
185 | 185 | |
|
186 | 186 | overwrite = Bool(False, |
|
187 | 187 | help="""Whether to overwrite existing config files when copying""" |
|
188 | 188 | ).tag(config=True) |
|
189 | 189 | auto_create = Bool(False, |
|
190 | 190 | help="""Whether to create profile dir if it doesn't exist""" |
|
191 | 191 | ).tag(config=True) |
|
192 | 192 | |
|
193 | 193 | config_files = List(Unicode()) |
|
194 | 194 | @default('config_files') |
|
195 | 195 | def _config_files_default(self): |
|
196 | 196 | return [self.config_file_name] |
|
197 | 197 | |
|
198 | 198 | copy_config_files = Bool(False, |
|
199 | 199 | help="""Whether to install the default config files into the profile dir. |
|
200 | 200 | If a new profile is being created, and IPython contains config files for that |
|
201 | 201 | profile, then they will be staged into the new directory. Otherwise, |
|
202 | 202 | default config files will be automatically generated. |
|
203 | 203 | """).tag(config=True) |
|
204 | 204 | |
|
205 | 205 | verbose_crash = Bool(False, |
|
206 | 206 | help="""Create a massive crash report when IPython encounters what may be an |
|
207 | 207 | internal error. The default is to append a short message to the |
|
208 | 208 | usual traceback""").tag(config=True) |
|
209 | 209 | |
|
210 | 210 | # The class to use as the crash handler. |
|
211 | 211 | crash_handler_class = Type(crashhandler.CrashHandler) |
|
212 | 212 | |
|
213 | 213 | @catch_config_error |
|
214 | 214 | def __init__(self, **kwargs): |
|
215 | 215 | super(BaseIPythonApplication, self).__init__(**kwargs) |
|
216 | 216 | # ensure current working directory exists |
|
217 | 217 | try: |
|
218 |
|
|
|
218 | os.getcwd() | |
|
219 | 219 | except: |
|
220 | 220 | # exit if cwd doesn't exist |
|
221 | 221 | self.log.error("Current working directory doesn't exist.") |
|
222 | 222 | self.exit(1) |
|
223 | 223 | |
|
224 | 224 | #------------------------------------------------------------------------- |
|
225 | 225 | # Various stages of Application creation |
|
226 | 226 | #------------------------------------------------------------------------- |
|
227 | 227 | |
|
228 | 228 | deprecated_subcommands = {} |
|
229 | 229 | |
|
230 | 230 | def initialize_subcommand(self, subc, argv=None): |
|
231 | 231 | if subc in self.deprecated_subcommands: |
|
232 | 232 | self.log.warning("Subcommand `ipython {sub}` is deprecated and will be removed " |
|
233 | 233 | "in future versions.".format(sub=subc)) |
|
234 | 234 | self.log.warning("You likely want to use `jupyter {sub}` in the " |
|
235 | 235 | "future".format(sub=subc)) |
|
236 | 236 | return super(BaseIPythonApplication, self).initialize_subcommand(subc, argv) |
|
237 | 237 | |
|
238 | 238 | def init_crash_handler(self): |
|
239 | 239 | """Create a crash handler, typically setting sys.excepthook to it.""" |
|
240 | 240 | self.crash_handler = self.crash_handler_class(self) |
|
241 | 241 | sys.excepthook = self.excepthook |
|
242 | 242 | def unset_crashhandler(): |
|
243 | 243 | sys.excepthook = sys.__excepthook__ |
|
244 | 244 | atexit.register(unset_crashhandler) |
|
245 | 245 | |
|
246 | 246 | def excepthook(self, etype, evalue, tb): |
|
247 | 247 | """this is sys.excepthook after init_crashhandler |
|
248 | 248 | |
|
249 | 249 | set self.verbose_crash=True to use our full crashhandler, instead of |
|
250 | 250 | a regular traceback with a short message (crash_handler_lite) |
|
251 | 251 | """ |
|
252 | 252 | |
|
253 | 253 | if self.verbose_crash: |
|
254 | 254 | return self.crash_handler(etype, evalue, tb) |
|
255 | 255 | else: |
|
256 | 256 | return crashhandler.crash_handler_lite(etype, evalue, tb) |
|
257 | 257 | |
|
258 | 258 | @observe('ipython_dir') |
|
259 | 259 | def _ipython_dir_changed(self, change): |
|
260 | 260 | old = change['old'] |
|
261 | 261 | new = change['new'] |
|
262 | 262 | if old is not Undefined: |
|
263 | 263 | str_old = py3compat.cast_bytes_py2(os.path.abspath(old), |
|
264 | 264 | sys.getfilesystemencoding() |
|
265 | 265 | ) |
|
266 | 266 | if str_old in sys.path: |
|
267 | 267 | sys.path.remove(str_old) |
|
268 | 268 | str_path = py3compat.cast_bytes_py2(os.path.abspath(new), |
|
269 | 269 | sys.getfilesystemencoding() |
|
270 | 270 | ) |
|
271 | 271 | sys.path.append(str_path) |
|
272 | 272 | ensure_dir_exists(new) |
|
273 | 273 | readme = os.path.join(new, 'README') |
|
274 | 274 | readme_src = os.path.join(get_ipython_package_dir(), u'config', u'profile', 'README') |
|
275 | 275 | if not os.path.exists(readme) and os.path.exists(readme_src): |
|
276 | 276 | shutil.copy(readme_src, readme) |
|
277 | 277 | for d in ('extensions', 'nbextensions'): |
|
278 | 278 | path = os.path.join(new, d) |
|
279 | 279 | try: |
|
280 | 280 | ensure_dir_exists(path) |
|
281 | 281 | except OSError as e: |
|
282 | 282 | # this will not be EEXIST |
|
283 | 283 | self.log.error("couldn't create path %s: %s", path, e) |
|
284 | 284 | self.log.debug("IPYTHONDIR set to: %s" % new) |
|
285 | 285 | |
|
286 | 286 | def load_config_file(self, suppress_errors=IPYTHON_SUPPRESS_CONFIG_ERRORS): |
|
287 | 287 | """Load the config file. |
|
288 | 288 | |
|
289 | 289 | By default, errors in loading config are handled, and a warning |
|
290 | 290 | printed on screen. For testing, the suppress_errors option is set |
|
291 | 291 | to False, so errors will make tests fail. |
|
292 | 292 | |
|
293 | 293 | `supress_errors` default value is to be `None` in which case the |
|
294 | 294 | behavior default to the one of `traitlets.Application`. |
|
295 | 295 | |
|
296 | 296 | The default value can be set : |
|
297 | 297 | - to `False` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '0', or 'false' (case insensitive). |
|
298 | 298 | - to `True` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '1' or 'true' (case insensitive). |
|
299 | 299 | - to `None` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '' (empty string) or leaving it unset. |
|
300 | 300 | |
|
301 | 301 | Any other value are invalid, and will make IPython exit with a non-zero return code. |
|
302 | 302 | """ |
|
303 | 303 | |
|
304 | 304 | |
|
305 | 305 | self.log.debug("Searching path %s for config files", self.config_file_paths) |
|
306 | 306 | base_config = 'ipython_config.py' |
|
307 | 307 | self.log.debug("Attempting to load config file: %s" % |
|
308 | 308 | base_config) |
|
309 | 309 | try: |
|
310 | 310 | if suppress_errors is not None: |
|
311 | 311 | old_value = Application.raise_config_file_errors |
|
312 | 312 | Application.raise_config_file_errors = not suppress_errors; |
|
313 | 313 | Application.load_config_file( |
|
314 | 314 | self, |
|
315 | 315 | base_config, |
|
316 | 316 | path=self.config_file_paths |
|
317 | 317 | ) |
|
318 | 318 | except ConfigFileNotFound: |
|
319 | 319 | # ignore errors loading parent |
|
320 | 320 | self.log.debug("Config file %s not found", base_config) |
|
321 | 321 | pass |
|
322 | 322 | if suppress_errors is not None: |
|
323 | 323 | Application.raise_config_file_errors = old_value |
|
324 | 324 | |
|
325 | 325 | for config_file_name in self.config_files: |
|
326 | 326 | if not config_file_name or config_file_name == base_config: |
|
327 | 327 | continue |
|
328 | 328 | self.log.debug("Attempting to load config file: %s" % |
|
329 | 329 | self.config_file_name) |
|
330 | 330 | try: |
|
331 | 331 | Application.load_config_file( |
|
332 | 332 | self, |
|
333 | 333 | config_file_name, |
|
334 | 334 | path=self.config_file_paths |
|
335 | 335 | ) |
|
336 | 336 | except ConfigFileNotFound: |
|
337 | 337 | # Only warn if the default config file was NOT being used. |
|
338 | 338 | if config_file_name in self.config_file_specified: |
|
339 | 339 | msg = self.log.warning |
|
340 | 340 | else: |
|
341 | 341 | msg = self.log.debug |
|
342 | 342 | msg("Config file not found, skipping: %s", config_file_name) |
|
343 | 343 | except Exception: |
|
344 | 344 | # For testing purposes. |
|
345 | 345 | if not suppress_errors: |
|
346 | 346 | raise |
|
347 | 347 | self.log.warning("Error loading config file: %s" % |
|
348 | 348 | self.config_file_name, exc_info=True) |
|
349 | 349 | |
|
350 | 350 | def init_profile_dir(self): |
|
351 | 351 | """initialize the profile dir""" |
|
352 | 352 | self._in_init_profile_dir = True |
|
353 | 353 | if self.profile_dir is not None: |
|
354 | 354 | # already ran |
|
355 | 355 | return |
|
356 | 356 | if 'ProfileDir.location' not in self.config: |
|
357 | 357 | # location not specified, find by profile name |
|
358 | 358 | try: |
|
359 | 359 | p = ProfileDir.find_profile_dir_by_name(self.ipython_dir, self.profile, self.config) |
|
360 | 360 | except ProfileDirError: |
|
361 | 361 | # not found, maybe create it (always create default profile) |
|
362 | 362 | if self.auto_create or self.profile == 'default': |
|
363 | 363 | try: |
|
364 | 364 | p = ProfileDir.create_profile_dir_by_name(self.ipython_dir, self.profile, self.config) |
|
365 | 365 | except ProfileDirError: |
|
366 | 366 | self.log.fatal("Could not create profile: %r"%self.profile) |
|
367 | 367 | self.exit(1) |
|
368 | 368 | else: |
|
369 | 369 | self.log.info("Created profile dir: %r"%p.location) |
|
370 | 370 | else: |
|
371 | 371 | self.log.fatal("Profile %r not found."%self.profile) |
|
372 | 372 | self.exit(1) |
|
373 | 373 | else: |
|
374 | 374 | self.log.debug("Using existing profile dir: %r"%p.location) |
|
375 | 375 | else: |
|
376 | 376 | location = self.config.ProfileDir.location |
|
377 | 377 | # location is fully specified |
|
378 | 378 | try: |
|
379 | 379 | p = ProfileDir.find_profile_dir(location, self.config) |
|
380 | 380 | except ProfileDirError: |
|
381 | 381 | # not found, maybe create it |
|
382 | 382 | if self.auto_create: |
|
383 | 383 | try: |
|
384 | 384 | p = ProfileDir.create_profile_dir(location, self.config) |
|
385 | 385 | except ProfileDirError: |
|
386 | 386 | self.log.fatal("Could not create profile directory: %r"%location) |
|
387 | 387 | self.exit(1) |
|
388 | 388 | else: |
|
389 | 389 | self.log.debug("Creating new profile dir: %r"%location) |
|
390 | 390 | else: |
|
391 | 391 | self.log.fatal("Profile directory %r not found."%location) |
|
392 | 392 | self.exit(1) |
|
393 | 393 | else: |
|
394 | 394 | self.log.info("Using existing profile dir: %r"%location) |
|
395 | 395 | # if profile_dir is specified explicitly, set profile name |
|
396 | 396 | dir_name = os.path.basename(p.location) |
|
397 | 397 | if dir_name.startswith('profile_'): |
|
398 | 398 | self.profile = dir_name[8:] |
|
399 | 399 | |
|
400 | 400 | self.profile_dir = p |
|
401 | 401 | self.config_file_paths.append(p.location) |
|
402 | 402 | self._in_init_profile_dir = False |
|
403 | 403 | |
|
404 | 404 | def init_config_files(self): |
|
405 | 405 | """[optionally] copy default config files into profile dir.""" |
|
406 | 406 | self.config_file_paths.extend(SYSTEM_CONFIG_DIRS) |
|
407 | 407 | # copy config files |
|
408 | 408 | path = self.builtin_profile_dir |
|
409 | 409 | if self.copy_config_files: |
|
410 | 410 | src = self.profile |
|
411 | 411 | |
|
412 | 412 | cfg = self.config_file_name |
|
413 | 413 | if path and os.path.exists(os.path.join(path, cfg)): |
|
414 | 414 | self.log.warning("Staging %r from %s into %r [overwrite=%s]"%( |
|
415 | 415 | cfg, src, self.profile_dir.location, self.overwrite) |
|
416 | 416 | ) |
|
417 | 417 | self.profile_dir.copy_config_file(cfg, path=path, overwrite=self.overwrite) |
|
418 | 418 | else: |
|
419 | 419 | self.stage_default_config_file() |
|
420 | 420 | else: |
|
421 | 421 | # Still stage *bundled* config files, but not generated ones |
|
422 | 422 | # This is necessary for `ipython profile=sympy` to load the profile |
|
423 | 423 | # on the first go |
|
424 | 424 | files = glob.glob(os.path.join(path, '*.py')) |
|
425 | 425 | for fullpath in files: |
|
426 | 426 | cfg = os.path.basename(fullpath) |
|
427 | 427 | if self.profile_dir.copy_config_file(cfg, path=path, overwrite=False): |
|
428 | 428 | # file was copied |
|
429 | 429 | self.log.warning("Staging bundled %s from %s into %r"%( |
|
430 | 430 | cfg, self.profile, self.profile_dir.location) |
|
431 | 431 | ) |
|
432 | 432 | |
|
433 | 433 | |
|
434 | 434 | def stage_default_config_file(self): |
|
435 | 435 | """auto generate default config file, and stage it into the profile.""" |
|
436 | 436 | s = self.generate_config_file() |
|
437 | 437 | fname = os.path.join(self.profile_dir.location, self.config_file_name) |
|
438 | 438 | if self.overwrite or not os.path.exists(fname): |
|
439 | 439 | self.log.warning("Generating default config file: %r"%(fname)) |
|
440 | 440 | with open(fname, 'w') as f: |
|
441 | 441 | f.write(s) |
|
442 | 442 | |
|
443 | 443 | @catch_config_error |
|
444 | 444 | def initialize(self, argv=None): |
|
445 | 445 | # don't hook up crash handler before parsing command-line |
|
446 | 446 | self.parse_command_line(argv) |
|
447 | 447 | self.init_crash_handler() |
|
448 | 448 | if self.subapp is not None: |
|
449 | 449 | # stop here if subapp is taking over |
|
450 | 450 | return |
|
451 | 451 | # save a copy of CLI config to re-load after config files |
|
452 | 452 | # so that it has highest priority |
|
453 | 453 | cl_config = deepcopy(self.config) |
|
454 | 454 | self.init_profile_dir() |
|
455 | 455 | self.init_config_files() |
|
456 | 456 | self.load_config_file() |
|
457 | 457 | # enforce cl-opts override configfile opts: |
|
458 | 458 | self.update_config(cl_config) |
@@ -1,103 +1,103 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 | 21 | from traitlets.config.configurable import Configurable |
|
22 | 22 | |
|
23 |
from IPython.utils.py3compat import builtin_mod |
|
|
23 | from IPython.utils.py3compat import builtin_mod | |
|
24 | 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 | |
|
56 | 56 | def __enter__(self): |
|
57 | 57 | if self._nested_level == 0: |
|
58 | 58 | self.activate() |
|
59 | 59 | self._nested_level += 1 |
|
60 | 60 | # I return self, so callers can use add_builtin in a with clause. |
|
61 | 61 | return self |
|
62 | 62 | |
|
63 | 63 | def __exit__(self, type, value, traceback): |
|
64 | 64 | if self._nested_level == 1: |
|
65 | 65 | self.deactivate() |
|
66 | 66 | self._nested_level -= 1 |
|
67 | 67 | # Returning False will cause exceptions to propagate |
|
68 | 68 | return False |
|
69 | 69 | |
|
70 | 70 | def add_builtin(self, key, value): |
|
71 | 71 | """Add a builtin and save the original.""" |
|
72 | 72 | bdict = builtin_mod.__dict__ |
|
73 | 73 | orig = bdict.get(key, BuiltinUndefined) |
|
74 | 74 | if value is HideBuiltin: |
|
75 | 75 | if orig is not BuiltinUndefined: #same as 'key in bdict' |
|
76 | 76 | self._orig_builtins[key] = orig |
|
77 | 77 | del bdict[key] |
|
78 | 78 | else: |
|
79 | 79 | self._orig_builtins[key] = orig |
|
80 | 80 | bdict[key] = value |
|
81 | 81 | |
|
82 | 82 | def remove_builtin(self, key, orig): |
|
83 | 83 | """Remove an added builtin and re-set the original.""" |
|
84 | 84 | if orig is BuiltinUndefined: |
|
85 | 85 | del builtin_mod.__dict__[key] |
|
86 | 86 | else: |
|
87 | 87 | builtin_mod.__dict__[key] = orig |
|
88 | 88 | |
|
89 | 89 | def activate(self): |
|
90 | 90 | """Store ipython references in the __builtin__ namespace.""" |
|
91 | 91 | |
|
92 | 92 | add_builtin = self.add_builtin |
|
93 |
for name, func in |
|
|
93 | for name, func in self.auto_builtins.items(): | |
|
94 | 94 | add_builtin(name, func) |
|
95 | 95 | |
|
96 | 96 | def deactivate(self): |
|
97 | 97 | """Remove any builtins which might have been added by add_builtins, or |
|
98 | 98 | restore overwritten ones to their previous values.""" |
|
99 | 99 | remove_builtin = self.remove_builtin |
|
100 |
for key, val in |
|
|
100 | for key, val in self._orig_builtins.items(): | |
|
101 | 101 | remove_builtin(key, val) |
|
102 | 102 | self._orig_builtins.clear() |
|
103 | 103 | self._builtins_added = False |
@@ -1,1229 +1,1229 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """Word completion for IPython. |
|
3 | 3 | |
|
4 | 4 | This module started as 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, |
|
7 | 7 | |
|
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 | # Some of this code originated from rlcompleter in the Python standard library |
|
14 | 14 | # Copyright (C) 2001 Python Software Foundation, www.python.org |
|
15 | 15 | |
|
16 | 16 | |
|
17 | 17 | import __main__ |
|
18 | 18 | import glob |
|
19 | 19 | import inspect |
|
20 | 20 | import itertools |
|
21 | 21 | import keyword |
|
22 | 22 | import os |
|
23 | 23 | import re |
|
24 | 24 | import sys |
|
25 | 25 | import unicodedata |
|
26 | 26 | import string |
|
27 | 27 | import warnings |
|
28 | 28 | from importlib import import_module |
|
29 | 29 | |
|
30 | 30 | from traitlets.config.configurable import Configurable |
|
31 | 31 | from IPython.core.error import TryNext |
|
32 | 32 | from IPython.core.inputsplitter import ESC_MAGIC |
|
33 | 33 | from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol |
|
34 | 34 | from IPython.utils import generics |
|
35 | 35 | from IPython.utils.decorators import undoc |
|
36 | 36 | from IPython.utils.dir2 import dir2, get_real_method |
|
37 | 37 | from IPython.utils.process import arg_split |
|
38 |
from IPython.utils.py3compat import builtin_mod, |
|
|
38 | from IPython.utils.py3compat import builtin_mod, PY3, cast_unicode_py2 | |
|
39 | 39 | from traitlets import Bool, Enum, observe |
|
40 | 40 | |
|
41 | 41 | from functools import wraps |
|
42 | 42 | |
|
43 | 43 | #----------------------------------------------------------------------------- |
|
44 | 44 | # Globals |
|
45 | 45 | #----------------------------------------------------------------------------- |
|
46 | 46 | |
|
47 | 47 | # Public API |
|
48 | 48 | __all__ = ['Completer','IPCompleter'] |
|
49 | 49 | |
|
50 | 50 | if sys.platform == 'win32': |
|
51 | 51 | PROTECTABLES = ' ' |
|
52 | 52 | else: |
|
53 | 53 | PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&' |
|
54 | 54 | |
|
55 | 55 | |
|
56 | 56 | #----------------------------------------------------------------------------- |
|
57 | 57 | # Work around BUG decorators. |
|
58 | 58 | #----------------------------------------------------------------------------- |
|
59 | 59 | |
|
60 | 60 | def _strip_single_trailing_space(complete): |
|
61 | 61 | """ |
|
62 | 62 | This is a workaround for a weird IPython/Prompt_toolkit behavior, |
|
63 | 63 | that can be removed once we rely on a slightly more recent prompt_toolkit |
|
64 | 64 | version (likely > 1.0.3). So this can likely be removed in IPython 6.0 |
|
65 | 65 | |
|
66 | 66 | cf https://github.com/ipython/ipython/issues/9658 |
|
67 | 67 | and https://github.com/jonathanslenders/python-prompt-toolkit/pull/328 |
|
68 | 68 | |
|
69 | 69 | The bug is due to the fact that in PTK the completer will reinvoke itself |
|
70 | 70 | after trying to completer to the longuest common prefix of all the |
|
71 | 71 | completions, unless only one completion is available. |
|
72 | 72 | |
|
73 | 73 | This logic is faulty if the completion ends with space, which can happen in |
|
74 | 74 | case like:: |
|
75 | 75 | |
|
76 | 76 | from foo import im<ta> |
|
77 | 77 | |
|
78 | 78 | which only matching completion is `import `. Note the leading space at the |
|
79 | 79 | end. So leaving a space at the end is a reasonable request, but for now |
|
80 | 80 | we'll strip it. |
|
81 | 81 | """ |
|
82 | 82 | |
|
83 | 83 | @wraps(complete) |
|
84 | 84 | def comp(*args, **kwargs): |
|
85 | 85 | text, matches = complete(*args, **kwargs) |
|
86 | 86 | if len(matches) == 1: |
|
87 | 87 | return text, [matches[0].rstrip()] |
|
88 | 88 | return text, matches |
|
89 | 89 | |
|
90 | 90 | return comp |
|
91 | 91 | |
|
92 | 92 | |
|
93 | 93 | |
|
94 | 94 | #----------------------------------------------------------------------------- |
|
95 | 95 | # Main functions and classes |
|
96 | 96 | #----------------------------------------------------------------------------- |
|
97 | 97 | |
|
98 | 98 | def has_open_quotes(s): |
|
99 | 99 | """Return whether a string has open quotes. |
|
100 | 100 | |
|
101 | 101 | This simply counts whether the number of quote characters of either type in |
|
102 | 102 | the string is odd. |
|
103 | 103 | |
|
104 | 104 | Returns |
|
105 | 105 | ------- |
|
106 | 106 | If there is an open quote, the quote character is returned. Else, return |
|
107 | 107 | False. |
|
108 | 108 | """ |
|
109 | 109 | # We check " first, then ', so complex cases with nested quotes will get |
|
110 | 110 | # the " to take precedence. |
|
111 | 111 | if s.count('"') % 2: |
|
112 | 112 | return '"' |
|
113 | 113 | elif s.count("'") % 2: |
|
114 | 114 | return "'" |
|
115 | 115 | else: |
|
116 | 116 | return False |
|
117 | 117 | |
|
118 | 118 | |
|
119 | 119 | def protect_filename(s): |
|
120 | 120 | """Escape a string to protect certain characters.""" |
|
121 | 121 | if set(s) & set(PROTECTABLES): |
|
122 | 122 | if sys.platform == "win32": |
|
123 | 123 | return '"' + s + '"' |
|
124 | 124 | else: |
|
125 | 125 | return "".join(("\\" + c if c in PROTECTABLES else c) for c in s) |
|
126 | 126 | else: |
|
127 | 127 | return s |
|
128 | 128 | |
|
129 | 129 | |
|
130 | 130 | def expand_user(path): |
|
131 | 131 | """Expand '~'-style usernames in strings. |
|
132 | 132 | |
|
133 | 133 | This is similar to :func:`os.path.expanduser`, but it computes and returns |
|
134 | 134 | extra information that will be useful if the input was being used in |
|
135 | 135 | computing completions, and you wish to return the completions with the |
|
136 | 136 | original '~' instead of its expanded value. |
|
137 | 137 | |
|
138 | 138 | Parameters |
|
139 | 139 | ---------- |
|
140 | 140 | path : str |
|
141 | 141 | String to be expanded. If no ~ is present, the output is the same as the |
|
142 | 142 | input. |
|
143 | 143 | |
|
144 | 144 | Returns |
|
145 | 145 | ------- |
|
146 | 146 | newpath : str |
|
147 | 147 | Result of ~ expansion in the input path. |
|
148 | 148 | tilde_expand : bool |
|
149 | 149 | Whether any expansion was performed or not. |
|
150 | 150 | tilde_val : str |
|
151 | 151 | The value that ~ was replaced with. |
|
152 | 152 | """ |
|
153 | 153 | # Default values |
|
154 | 154 | tilde_expand = False |
|
155 | 155 | tilde_val = '' |
|
156 | 156 | newpath = path |
|
157 | 157 | |
|
158 | 158 | if path.startswith('~'): |
|
159 | 159 | tilde_expand = True |
|
160 | 160 | rest = len(path)-1 |
|
161 | 161 | newpath = os.path.expanduser(path) |
|
162 | 162 | if rest: |
|
163 | 163 | tilde_val = newpath[:-rest] |
|
164 | 164 | else: |
|
165 | 165 | tilde_val = newpath |
|
166 | 166 | |
|
167 | 167 | return newpath, tilde_expand, tilde_val |
|
168 | 168 | |
|
169 | 169 | |
|
170 | 170 | def compress_user(path, tilde_expand, tilde_val): |
|
171 | 171 | """Does the opposite of expand_user, with its outputs. |
|
172 | 172 | """ |
|
173 | 173 | if tilde_expand: |
|
174 | 174 | return path.replace(tilde_val, '~') |
|
175 | 175 | else: |
|
176 | 176 | return path |
|
177 | 177 | |
|
178 | 178 | |
|
179 | 179 | def completions_sorting_key(word): |
|
180 | 180 | """key for sorting completions |
|
181 | 181 | |
|
182 | 182 | This does several things: |
|
183 | 183 | |
|
184 | 184 | - Lowercase all completions, so they are sorted alphabetically with |
|
185 | 185 | upper and lower case words mingled |
|
186 | 186 | - Demote any completions starting with underscores to the end |
|
187 | 187 | - Insert any %magic and %%cellmagic completions in the alphabetical order |
|
188 | 188 | by their name |
|
189 | 189 | """ |
|
190 | 190 | # Case insensitive sort |
|
191 | 191 | word = word.lower() |
|
192 | 192 | |
|
193 | 193 | prio1, prio2 = 0, 0 |
|
194 | 194 | |
|
195 | 195 | if word.startswith('__'): |
|
196 | 196 | prio1 = 2 |
|
197 | 197 | elif word.startswith('_'): |
|
198 | 198 | prio1 = 1 |
|
199 | 199 | |
|
200 | 200 | if word.endswith('='): |
|
201 | 201 | prio1 = -1 |
|
202 | 202 | |
|
203 | 203 | if word.startswith('%%'): |
|
204 | 204 | # If there's another % in there, this is something else, so leave it alone |
|
205 | 205 | if not "%" in word[2:]: |
|
206 | 206 | word = word[2:] |
|
207 | 207 | prio2 = 2 |
|
208 | 208 | elif word.startswith('%'): |
|
209 | 209 | if not "%" in word[1:]: |
|
210 | 210 | word = word[1:] |
|
211 | 211 | prio2 = 1 |
|
212 | 212 | |
|
213 | 213 | return prio1, word, prio2 |
|
214 | 214 | |
|
215 | 215 | |
|
216 | 216 | @undoc |
|
217 | 217 | class Bunch(object): pass |
|
218 | 218 | |
|
219 | 219 | |
|
220 | 220 | if sys.platform == 'win32': |
|
221 | 221 | DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?' |
|
222 | 222 | else: |
|
223 | 223 | DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?' |
|
224 | 224 | |
|
225 | 225 | GREEDY_DELIMS = ' =\r\n' |
|
226 | 226 | |
|
227 | 227 | |
|
228 | 228 | class CompletionSplitter(object): |
|
229 | 229 | """An object to split an input line in a manner similar to readline. |
|
230 | 230 | |
|
231 | 231 | By having our own implementation, we can expose readline-like completion in |
|
232 | 232 | a uniform manner to all frontends. This object only needs to be given the |
|
233 | 233 | line of text to be split and the cursor position on said line, and it |
|
234 | 234 | returns the 'word' to be completed on at the cursor after splitting the |
|
235 | 235 | entire line. |
|
236 | 236 | |
|
237 | 237 | What characters are used as splitting delimiters can be controlled by |
|
238 | 238 | setting the `delims` attribute (this is a property that internally |
|
239 | 239 | automatically builds the necessary regular expression)""" |
|
240 | 240 | |
|
241 | 241 | # Private interface |
|
242 | 242 | |
|
243 | 243 | # A string of delimiter characters. The default value makes sense for |
|
244 | 244 | # IPython's most typical usage patterns. |
|
245 | 245 | _delims = DELIMS |
|
246 | 246 | |
|
247 | 247 | # The expression (a normal string) to be compiled into a regular expression |
|
248 | 248 | # for actual splitting. We store it as an attribute mostly for ease of |
|
249 | 249 | # debugging, since this type of code can be so tricky to debug. |
|
250 | 250 | _delim_expr = None |
|
251 | 251 | |
|
252 | 252 | # The regular expression that does the actual splitting |
|
253 | 253 | _delim_re = None |
|
254 | 254 | |
|
255 | 255 | def __init__(self, delims=None): |
|
256 | 256 | delims = CompletionSplitter._delims if delims is None else delims |
|
257 | 257 | self.delims = delims |
|
258 | 258 | |
|
259 | 259 | @property |
|
260 | 260 | def delims(self): |
|
261 | 261 | """Return the string of delimiter characters.""" |
|
262 | 262 | return self._delims |
|
263 | 263 | |
|
264 | 264 | @delims.setter |
|
265 | 265 | def delims(self, delims): |
|
266 | 266 | """Set the delimiters for line splitting.""" |
|
267 | 267 | expr = '[' + ''.join('\\'+ c for c in delims) + ']' |
|
268 | 268 | self._delim_re = re.compile(expr) |
|
269 | 269 | self._delims = delims |
|
270 | 270 | self._delim_expr = expr |
|
271 | 271 | |
|
272 | 272 | def split_line(self, line, cursor_pos=None): |
|
273 | 273 | """Split a line of text with a cursor at the given position. |
|
274 | 274 | """ |
|
275 | 275 | l = line if cursor_pos is None else line[:cursor_pos] |
|
276 | 276 | return self._delim_re.split(l)[-1] |
|
277 | 277 | |
|
278 | 278 | |
|
279 | 279 | class Completer(Configurable): |
|
280 | 280 | |
|
281 | 281 | greedy = Bool(False, |
|
282 | 282 | help="""Activate greedy completion |
|
283 | 283 | PENDING DEPRECTION. this is now mostly taken care of with Jedi. |
|
284 | 284 | |
|
285 | 285 | This will enable completion on elements of lists, results of function calls, etc., |
|
286 | 286 | but can be unsafe because the code is actually evaluated on TAB. |
|
287 | 287 | """ |
|
288 | 288 | ).tag(config=True) |
|
289 | 289 | |
|
290 | 290 | |
|
291 | 291 | def __init__(self, namespace=None, global_namespace=None, **kwargs): |
|
292 | 292 | """Create a new completer for the command line. |
|
293 | 293 | |
|
294 | 294 | Completer(namespace=ns, global_namespace=ns2) -> completer instance. |
|
295 | 295 | |
|
296 | 296 | If unspecified, the default namespace where completions are performed |
|
297 | 297 | is __main__ (technically, __main__.__dict__). Namespaces should be |
|
298 | 298 | given as dictionaries. |
|
299 | 299 | |
|
300 | 300 | An optional second namespace can be given. This allows the completer |
|
301 | 301 | to handle cases where both the local and global scopes need to be |
|
302 | 302 | distinguished. |
|
303 | 303 | |
|
304 | 304 | Completer instances should be used as the completion mechanism of |
|
305 | 305 | readline via the set_completer() call: |
|
306 | 306 | |
|
307 | 307 | readline.set_completer(Completer(my_namespace).complete) |
|
308 | 308 | """ |
|
309 | 309 | |
|
310 | 310 | # Don't bind to namespace quite yet, but flag whether the user wants a |
|
311 | 311 | # specific namespace or to use __main__.__dict__. This will allow us |
|
312 | 312 | # to bind to __main__.__dict__ at completion time, not now. |
|
313 | 313 | if namespace is None: |
|
314 | 314 | self.use_main_ns = 1 |
|
315 | 315 | else: |
|
316 | 316 | self.use_main_ns = 0 |
|
317 | 317 | self.namespace = namespace |
|
318 | 318 | |
|
319 | 319 | # The global namespace, if given, can be bound directly |
|
320 | 320 | if global_namespace is None: |
|
321 | 321 | self.global_namespace = {} |
|
322 | 322 | else: |
|
323 | 323 | self.global_namespace = global_namespace |
|
324 | 324 | |
|
325 | 325 | super(Completer, self).__init__(**kwargs) |
|
326 | 326 | |
|
327 | 327 | def complete(self, text, state): |
|
328 | 328 | """Return the next possible completion for 'text'. |
|
329 | 329 | |
|
330 | 330 | This is called successively with state == 0, 1, 2, ... until it |
|
331 | 331 | returns None. The completion should begin with 'text'. |
|
332 | 332 | |
|
333 | 333 | """ |
|
334 | 334 | if self.use_main_ns: |
|
335 | 335 | self.namespace = __main__.__dict__ |
|
336 | 336 | |
|
337 | 337 | if state == 0: |
|
338 | 338 | if "." in text: |
|
339 | 339 | self.matches = self.attr_matches(text) |
|
340 | 340 | else: |
|
341 | 341 | self.matches = self.global_matches(text) |
|
342 | 342 | try: |
|
343 | 343 | return self.matches[state] |
|
344 | 344 | except IndexError: |
|
345 | 345 | return None |
|
346 | 346 | |
|
347 | 347 | def global_matches(self, text): |
|
348 | 348 | """Compute matches when text is a simple name. |
|
349 | 349 | |
|
350 | 350 | Return a list of all keywords, built-in functions and names currently |
|
351 | 351 | defined in self.namespace or self.global_namespace that match. |
|
352 | 352 | |
|
353 | 353 | """ |
|
354 | 354 | matches = [] |
|
355 | 355 | match_append = matches.append |
|
356 | 356 | n = len(text) |
|
357 | 357 | for lst in [keyword.kwlist, |
|
358 | 358 | builtin_mod.__dict__.keys(), |
|
359 | 359 | self.namespace.keys(), |
|
360 | 360 | self.global_namespace.keys()]: |
|
361 | 361 | for word in lst: |
|
362 | 362 | if word[:n] == text and word != "__builtins__": |
|
363 | 363 | match_append(word) |
|
364 | 364 | return [cast_unicode_py2(m) for m in matches] |
|
365 | 365 | |
|
366 | 366 | def attr_matches(self, text): |
|
367 | 367 | """Compute matches when text contains a dot. |
|
368 | 368 | |
|
369 | 369 | Assuming the text is of the form NAME.NAME....[NAME], and is |
|
370 | 370 | evaluatable in self.namespace or self.global_namespace, it will be |
|
371 | 371 | evaluated and its attributes (as revealed by dir()) are used as |
|
372 | 372 | possible completions. (For class instances, class members are are |
|
373 | 373 | also considered.) |
|
374 | 374 | |
|
375 | 375 | WARNING: this can still invoke arbitrary C code, if an object |
|
376 | 376 | with a __getattr__ hook is evaluated. |
|
377 | 377 | |
|
378 | 378 | """ |
|
379 | 379 | |
|
380 | 380 | # Another option, seems to work great. Catches things like ''.<tab> |
|
381 | 381 | m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) |
|
382 | 382 | |
|
383 | 383 | if m: |
|
384 | 384 | expr, attr = m.group(1, 3) |
|
385 | 385 | elif self.greedy: |
|
386 | 386 | m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer) |
|
387 | 387 | if not m2: |
|
388 | 388 | return [] |
|
389 | 389 | expr, attr = m2.group(1,2) |
|
390 | 390 | else: |
|
391 | 391 | return [] |
|
392 | 392 | |
|
393 | 393 | try: |
|
394 | 394 | obj = eval(expr, self.namespace) |
|
395 | 395 | except: |
|
396 | 396 | try: |
|
397 | 397 | obj = eval(expr, self.global_namespace) |
|
398 | 398 | except: |
|
399 | 399 | return [] |
|
400 | 400 | |
|
401 | 401 | if self.limit_to__all__ and hasattr(obj, '__all__'): |
|
402 | 402 | words = get__all__entries(obj) |
|
403 | 403 | else: |
|
404 | 404 | words = dir2(obj) |
|
405 | 405 | |
|
406 | 406 | try: |
|
407 | 407 | words = generics.complete_object(obj, words) |
|
408 | 408 | except TryNext: |
|
409 | 409 | pass |
|
410 | 410 | except Exception: |
|
411 | 411 | # Silence errors from completion function |
|
412 | 412 | #raise # dbg |
|
413 | 413 | pass |
|
414 | 414 | # Build match list to return |
|
415 | 415 | n = len(attr) |
|
416 | 416 | return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ] |
|
417 | 417 | |
|
418 | 418 | |
|
419 | 419 | def get__all__entries(obj): |
|
420 | 420 | """returns the strings in the __all__ attribute""" |
|
421 | 421 | try: |
|
422 | 422 | words = getattr(obj, '__all__') |
|
423 | 423 | except: |
|
424 | 424 | return [] |
|
425 | 425 | |
|
426 |
return [cast_unicode_py2(w) for w in words if isinstance(w, str |
|
|
426 | return [cast_unicode_py2(w) for w in words if isinstance(w, str)] | |
|
427 | 427 | |
|
428 | 428 | |
|
429 | 429 | def match_dict_keys(keys, prefix, delims): |
|
430 | 430 | """Used by dict_key_matches, matching the prefix to a list of keys""" |
|
431 | 431 | if not prefix: |
|
432 | 432 | return None, 0, [repr(k) for k in keys |
|
433 |
if isinstance(k, (str |
|
|
433 | if isinstance(k, (str, bytes))] | |
|
434 | 434 | quote_match = re.search('["\']', prefix) |
|
435 | 435 | quote = quote_match.group() |
|
436 | 436 | try: |
|
437 | 437 | prefix_str = eval(prefix + quote, {}) |
|
438 | 438 | except Exception: |
|
439 | 439 | return None, 0, [] |
|
440 | 440 | |
|
441 | 441 | pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$' |
|
442 | 442 | token_match = re.search(pattern, prefix, re.UNICODE) |
|
443 | 443 | token_start = token_match.start() |
|
444 | 444 | token_prefix = token_match.group() |
|
445 | 445 | |
|
446 | 446 | # TODO: support bytes in Py3k |
|
447 | 447 | matched = [] |
|
448 | 448 | for key in keys: |
|
449 | 449 | try: |
|
450 | 450 | if not key.startswith(prefix_str): |
|
451 | 451 | continue |
|
452 | 452 | except (AttributeError, TypeError, UnicodeError): |
|
453 | 453 | # Python 3+ TypeError on b'a'.startswith('a') or vice-versa |
|
454 | 454 | continue |
|
455 | 455 | |
|
456 | 456 | # reformat remainder of key to begin with prefix |
|
457 | 457 | rem = key[len(prefix_str):] |
|
458 | 458 | # force repr wrapped in ' |
|
459 | 459 | rem_repr = repr(rem + '"') |
|
460 | 460 | if rem_repr.startswith('u') and prefix[0] not in 'uU': |
|
461 | 461 | # Found key is unicode, but prefix is Py2 string. |
|
462 | 462 | # Therefore attempt to interpret key as string. |
|
463 | 463 | try: |
|
464 | 464 | rem_repr = repr(rem.encode('ascii') + '"') |
|
465 | 465 | except UnicodeEncodeError: |
|
466 | 466 | continue |
|
467 | 467 | |
|
468 | 468 | rem_repr = rem_repr[1 + rem_repr.index("'"):-2] |
|
469 | 469 | if quote == '"': |
|
470 | 470 | # The entered prefix is quoted with ", |
|
471 | 471 | # but the match is quoted with '. |
|
472 | 472 | # A contained " hence needs escaping for comparison: |
|
473 | 473 | rem_repr = rem_repr.replace('"', '\\"') |
|
474 | 474 | |
|
475 | 475 | # then reinsert prefix from start of token |
|
476 | 476 | matched.append('%s%s' % (token_prefix, rem_repr)) |
|
477 | 477 | return quote, token_start, matched |
|
478 | 478 | |
|
479 | 479 | |
|
480 | 480 | def _safe_isinstance(obj, module, class_name): |
|
481 | 481 | """Checks if obj is an instance of module.class_name if loaded |
|
482 | 482 | """ |
|
483 | 483 | return (module in sys.modules and |
|
484 | 484 | isinstance(obj, getattr(import_module(module), class_name))) |
|
485 | 485 | |
|
486 | 486 | |
|
487 | 487 | def back_unicode_name_matches(text): |
|
488 | 488 | u"""Match unicode characters back to unicode name |
|
489 | 489 | |
|
490 | 490 | This does ☃ -> \\snowman |
|
491 | 491 | |
|
492 | 492 | Note that snowman is not a valid python3 combining character but will be expanded. |
|
493 | 493 | Though it will not recombine back to the snowman character by the completion machinery. |
|
494 | 494 | |
|
495 | 495 | This will not either back-complete standard sequences like \\n, \\b ... |
|
496 | 496 | |
|
497 | 497 | Used on Python 3 only. |
|
498 | 498 | """ |
|
499 | 499 | if len(text)<2: |
|
500 | 500 | return u'', () |
|
501 | 501 | maybe_slash = text[-2] |
|
502 | 502 | if maybe_slash != '\\': |
|
503 | 503 | return u'', () |
|
504 | 504 | |
|
505 | 505 | char = text[-1] |
|
506 | 506 | # no expand on quote for completion in strings. |
|
507 | 507 | # nor backcomplete standard ascii keys |
|
508 | 508 | if char in string.ascii_letters or char in ['"',"'"]: |
|
509 | 509 | return u'', () |
|
510 | 510 | try : |
|
511 | 511 | unic = unicodedata.name(char) |
|
512 | 512 | return '\\'+char,['\\'+unic] |
|
513 | 513 | except KeyError: |
|
514 | 514 | pass |
|
515 | 515 | return u'', () |
|
516 | 516 | |
|
517 | 517 | def back_latex_name_matches(text): |
|
518 | 518 | u"""Match latex characters back to unicode name |
|
519 | 519 | |
|
520 | 520 | This does ->\\sqrt |
|
521 | 521 | |
|
522 | 522 | Used on Python 3 only. |
|
523 | 523 | """ |
|
524 | 524 | if len(text)<2: |
|
525 | 525 | return u'', () |
|
526 | 526 | maybe_slash = text[-2] |
|
527 | 527 | if maybe_slash != '\\': |
|
528 | 528 | return u'', () |
|
529 | 529 | |
|
530 | 530 | |
|
531 | 531 | char = text[-1] |
|
532 | 532 | # no expand on quote for completion in strings. |
|
533 | 533 | # nor backcomplete standard ascii keys |
|
534 | 534 | if char in string.ascii_letters or char in ['"',"'"]: |
|
535 | 535 | return u'', () |
|
536 | 536 | try : |
|
537 | 537 | latex = reverse_latex_symbol[char] |
|
538 | 538 | # '\\' replace the \ as well |
|
539 | 539 | return '\\'+char,[latex] |
|
540 | 540 | except KeyError: |
|
541 | 541 | pass |
|
542 | 542 | return u'', () |
|
543 | 543 | |
|
544 | 544 | |
|
545 | 545 | class IPCompleter(Completer): |
|
546 | 546 | """Extension of the completer class with IPython-specific features""" |
|
547 | 547 | |
|
548 | 548 | @observe('greedy') |
|
549 | 549 | def _greedy_changed(self, change): |
|
550 | 550 | """update the splitter and readline delims when greedy is changed""" |
|
551 | 551 | if change['new']: |
|
552 | 552 | self.splitter.delims = GREEDY_DELIMS |
|
553 | 553 | else: |
|
554 | 554 | self.splitter.delims = DELIMS |
|
555 | 555 | |
|
556 | 556 | merge_completions = Bool(True, |
|
557 | 557 | help="""Whether to merge completion results into a single list |
|
558 | 558 | |
|
559 | 559 | If False, only the completion results from the first non-empty |
|
560 | 560 | completer will be returned. |
|
561 | 561 | """ |
|
562 | 562 | ).tag(config=True) |
|
563 | 563 | omit__names = Enum((0,1,2), default_value=2, |
|
564 | 564 | help="""Instruct the completer to omit private method names |
|
565 | 565 | |
|
566 | 566 | Specifically, when completing on ``object.<tab>``. |
|
567 | 567 | |
|
568 | 568 | When 2 [default]: all names that start with '_' will be excluded. |
|
569 | 569 | |
|
570 | 570 | When 1: all 'magic' names (``__foo__``) will be excluded. |
|
571 | 571 | |
|
572 | 572 | When 0: nothing will be excluded. |
|
573 | 573 | """ |
|
574 | 574 | ).tag(config=True) |
|
575 | 575 | limit_to__all__ = Bool(False, |
|
576 | 576 | help=""" |
|
577 | 577 | DEPRECATED as of version 5.0. |
|
578 | 578 | |
|
579 | 579 | Instruct the completer to use __all__ for the completion |
|
580 | 580 | |
|
581 | 581 | Specifically, when completing on ``object.<tab>``. |
|
582 | 582 | |
|
583 | 583 | When True: only those names in obj.__all__ will be included. |
|
584 | 584 | |
|
585 | 585 | When False [default]: the __all__ attribute is ignored |
|
586 | 586 | """, |
|
587 | 587 | ).tag(config=True) |
|
588 | 588 | |
|
589 | 589 | def __init__(self, shell=None, namespace=None, global_namespace=None, |
|
590 | 590 | use_readline=False, config=None, **kwargs): |
|
591 | 591 | """IPCompleter() -> completer |
|
592 | 592 | |
|
593 | 593 | Return a completer object suitable for use by the readline library |
|
594 | 594 | via readline.set_completer(). |
|
595 | 595 | |
|
596 | 596 | Inputs: |
|
597 | 597 | |
|
598 | 598 | - shell: a pointer to the ipython shell itself. This is needed |
|
599 | 599 | because this completer knows about magic functions, and those can |
|
600 | 600 | only be accessed via the ipython instance. |
|
601 | 601 | |
|
602 | 602 | - namespace: an optional dict where completions are performed. |
|
603 | 603 | |
|
604 | 604 | - global_namespace: secondary optional dict for completions, to |
|
605 | 605 | handle cases (such as IPython embedded inside functions) where |
|
606 | 606 | both Python scopes are visible. |
|
607 | 607 | |
|
608 | 608 | use_readline : bool, optional |
|
609 | 609 | DEPRECATED, ignored. |
|
610 | 610 | """ |
|
611 | 611 | |
|
612 | 612 | self.magic_escape = ESC_MAGIC |
|
613 | 613 | self.splitter = CompletionSplitter() |
|
614 | 614 | |
|
615 | 615 | if use_readline: |
|
616 | 616 | warnings.warn('The use_readline parameter is deprecated and ignored since IPython 6.0.', |
|
617 | 617 | DeprecationWarning, stacklevel=2) |
|
618 | 618 | |
|
619 | 619 | # _greedy_changed() depends on splitter and readline being defined: |
|
620 | 620 | Completer.__init__(self, namespace=namespace, global_namespace=global_namespace, |
|
621 | 621 | config=config, **kwargs) |
|
622 | 622 | |
|
623 | 623 | # List where completion matches will be stored |
|
624 | 624 | self.matches = [] |
|
625 | 625 | self.shell = shell |
|
626 | 626 | # Regexp to split filenames with spaces in them |
|
627 | 627 | self.space_name_re = re.compile(r'([^\\] )') |
|
628 | 628 | # Hold a local ref. to glob.glob for speed |
|
629 | 629 | self.glob = glob.glob |
|
630 | 630 | |
|
631 | 631 | # Determine if we are running on 'dumb' terminals, like (X)Emacs |
|
632 | 632 | # buffers, to avoid completion problems. |
|
633 | 633 | term = os.environ.get('TERM','xterm') |
|
634 | 634 | self.dumb_terminal = term in ['dumb','emacs'] |
|
635 | 635 | |
|
636 | 636 | # Special handling of backslashes needed in win32 platforms |
|
637 | 637 | if sys.platform == "win32": |
|
638 | 638 | self.clean_glob = self._clean_glob_win32 |
|
639 | 639 | else: |
|
640 | 640 | self.clean_glob = self._clean_glob |
|
641 | 641 | |
|
642 | 642 | #regexp to parse docstring for function signature |
|
643 | 643 | self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*') |
|
644 | 644 | self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)') |
|
645 | 645 | #use this if positional argument name is also needed |
|
646 | 646 | #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)') |
|
647 | 647 | |
|
648 | 648 | # All active matcher routines for completion |
|
649 | 649 | self.matchers = [ |
|
650 | 650 | self.python_matches, |
|
651 | 651 | self.file_matches, |
|
652 | 652 | self.magic_matches, |
|
653 | 653 | self.python_func_kw_matches, |
|
654 | 654 | self.dict_key_matches, |
|
655 | 655 | ] |
|
656 | 656 | |
|
657 | 657 | # This is set externally by InteractiveShell |
|
658 | 658 | self.custom_completers = None |
|
659 | 659 | |
|
660 | 660 | def all_completions(self, text): |
|
661 | 661 | """ |
|
662 | 662 | Wrapper around the complete method for the benefit of emacs. |
|
663 | 663 | """ |
|
664 | 664 | return self.complete(text)[1] |
|
665 | 665 | |
|
666 | 666 | def _clean_glob(self, text): |
|
667 | 667 | return self.glob("%s*" % text) |
|
668 | 668 | |
|
669 | 669 | def _clean_glob_win32(self,text): |
|
670 | 670 | return [f.replace("\\","/") |
|
671 | 671 | for f in self.glob("%s*" % text)] |
|
672 | 672 | |
|
673 | 673 | def file_matches(self, text): |
|
674 | 674 | """Match filenames, expanding ~USER type strings. |
|
675 | 675 | |
|
676 | 676 | Most of the seemingly convoluted logic in this completer is an |
|
677 | 677 | attempt to handle filenames with spaces in them. And yet it's not |
|
678 | 678 | quite perfect, because Python's readline doesn't expose all of the |
|
679 | 679 | GNU readline details needed for this to be done correctly. |
|
680 | 680 | |
|
681 | 681 | For a filename with a space in it, the printed completions will be |
|
682 | 682 | only the parts after what's already been typed (instead of the |
|
683 | 683 | full completions, as is normally done). I don't think with the |
|
684 | 684 | current (as of Python 2.3) Python readline it's possible to do |
|
685 | 685 | better.""" |
|
686 | 686 | |
|
687 | 687 | # chars that require escaping with backslash - i.e. chars |
|
688 | 688 | # that readline treats incorrectly as delimiters, but we |
|
689 | 689 | # don't want to treat as delimiters in filename matching |
|
690 | 690 | # when escaped with backslash |
|
691 | 691 | if text.startswith('!'): |
|
692 | 692 | text = text[1:] |
|
693 | 693 | text_prefix = u'!' |
|
694 | 694 | else: |
|
695 | 695 | text_prefix = u'' |
|
696 | 696 | |
|
697 | 697 | text_until_cursor = self.text_until_cursor |
|
698 | 698 | # track strings with open quotes |
|
699 | 699 | open_quotes = has_open_quotes(text_until_cursor) |
|
700 | 700 | |
|
701 | 701 | if '(' in text_until_cursor or '[' in text_until_cursor: |
|
702 | 702 | lsplit = text |
|
703 | 703 | else: |
|
704 | 704 | try: |
|
705 | 705 | # arg_split ~ shlex.split, but with unicode bugs fixed by us |
|
706 | 706 | lsplit = arg_split(text_until_cursor)[-1] |
|
707 | 707 | except ValueError: |
|
708 | 708 | # typically an unmatched ", or backslash without escaped char. |
|
709 | 709 | if open_quotes: |
|
710 | 710 | lsplit = text_until_cursor.split(open_quotes)[-1] |
|
711 | 711 | else: |
|
712 | 712 | return [] |
|
713 | 713 | except IndexError: |
|
714 | 714 | # tab pressed on empty line |
|
715 | 715 | lsplit = "" |
|
716 | 716 | |
|
717 | 717 | if not open_quotes and lsplit != protect_filename(lsplit): |
|
718 | 718 | # if protectables are found, do matching on the whole escaped name |
|
719 | 719 | has_protectables = True |
|
720 | 720 | text0,text = text,lsplit |
|
721 | 721 | else: |
|
722 | 722 | has_protectables = False |
|
723 | 723 | text = os.path.expanduser(text) |
|
724 | 724 | |
|
725 | 725 | if text == "": |
|
726 | 726 | return [text_prefix + cast_unicode_py2(protect_filename(f)) for f in self.glob("*")] |
|
727 | 727 | |
|
728 | 728 | # Compute the matches from the filesystem |
|
729 | 729 | if sys.platform == 'win32': |
|
730 | 730 | m0 = self.clean_glob(text) |
|
731 | 731 | else: |
|
732 | 732 | m0 = self.clean_glob(text.replace('\\', '')) |
|
733 | 733 | |
|
734 | 734 | if has_protectables: |
|
735 | 735 | # If we had protectables, we need to revert our changes to the |
|
736 | 736 | # beginning of filename so that we don't double-write the part |
|
737 | 737 | # of the filename we have so far |
|
738 | 738 | len_lsplit = len(lsplit) |
|
739 | 739 | matches = [text_prefix + text0 + |
|
740 | 740 | protect_filename(f[len_lsplit:]) for f in m0] |
|
741 | 741 | else: |
|
742 | 742 | if open_quotes: |
|
743 | 743 | # if we have a string with an open quote, we don't need to |
|
744 | 744 | # protect the names at all (and we _shouldn't_, as it |
|
745 | 745 | # would cause bugs when the filesystem call is made). |
|
746 | 746 | matches = m0 |
|
747 | 747 | else: |
|
748 | 748 | matches = [text_prefix + |
|
749 | 749 | protect_filename(f) for f in m0] |
|
750 | 750 | |
|
751 | 751 | # Mark directories in input list by appending '/' to their names. |
|
752 | 752 | return [cast_unicode_py2(x+'/') if os.path.isdir(x) else x for x in matches] |
|
753 | 753 | |
|
754 | 754 | def magic_matches(self, text): |
|
755 | 755 | """Match magics""" |
|
756 | 756 | # Get all shell magics now rather than statically, so magics loaded at |
|
757 | 757 | # runtime show up too. |
|
758 | 758 | lsm = self.shell.magics_manager.lsmagic() |
|
759 | 759 | line_magics = lsm['line'] |
|
760 | 760 | cell_magics = lsm['cell'] |
|
761 | 761 | pre = self.magic_escape |
|
762 | 762 | pre2 = pre+pre |
|
763 | 763 | |
|
764 | 764 | # Completion logic: |
|
765 | 765 | # - user gives %%: only do cell magics |
|
766 | 766 | # - user gives %: do both line and cell magics |
|
767 | 767 | # - no prefix: do both |
|
768 | 768 | # In other words, line magics are skipped if the user gives %% explicitly |
|
769 | 769 | bare_text = text.lstrip(pre) |
|
770 | 770 | comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)] |
|
771 | 771 | if not text.startswith(pre2): |
|
772 | 772 | comp += [ pre+m for m in line_magics if m.startswith(bare_text)] |
|
773 | 773 | return [cast_unicode_py2(c) for c in comp] |
|
774 | 774 | |
|
775 | 775 | |
|
776 | 776 | def python_matches(self, text): |
|
777 | 777 | """Match attributes or global python names""" |
|
778 | 778 | if "." in text: |
|
779 | 779 | try: |
|
780 | 780 | matches = self.attr_matches(text) |
|
781 | 781 | if text.endswith('.') and self.omit__names: |
|
782 | 782 | if self.omit__names == 1: |
|
783 | 783 | # true if txt is _not_ a __ name, false otherwise: |
|
784 | 784 | no__name = (lambda txt: |
|
785 | 785 | re.match(r'.*\.__.*?__',txt) is None) |
|
786 | 786 | else: |
|
787 | 787 | # true if txt is _not_ a _ name, false otherwise: |
|
788 | 788 | no__name = (lambda txt: |
|
789 | 789 | re.match(r'\._.*?',txt[txt.rindex('.'):]) is None) |
|
790 | 790 | matches = filter(no__name, matches) |
|
791 | 791 | except NameError: |
|
792 | 792 | # catches <undefined attributes>.<tab> |
|
793 | 793 | matches = [] |
|
794 | 794 | else: |
|
795 | 795 | matches = self.global_matches(text) |
|
796 | 796 | return matches |
|
797 | 797 | |
|
798 | 798 | def _default_arguments_from_docstring(self, doc): |
|
799 | 799 | """Parse the first line of docstring for call signature. |
|
800 | 800 | |
|
801 | 801 | Docstring should be of the form 'min(iterable[, key=func])\n'. |
|
802 | 802 | It can also parse cython docstring of the form |
|
803 | 803 | 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'. |
|
804 | 804 | """ |
|
805 | 805 | if doc is None: |
|
806 | 806 | return [] |
|
807 | 807 | |
|
808 | 808 | #care only the firstline |
|
809 | 809 | line = doc.lstrip().splitlines()[0] |
|
810 | 810 | |
|
811 | 811 | #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*') |
|
812 | 812 | #'min(iterable[, key=func])\n' -> 'iterable[, key=func]' |
|
813 | 813 | sig = self.docstring_sig_re.search(line) |
|
814 | 814 | if sig is None: |
|
815 | 815 | return [] |
|
816 | 816 | # iterable[, key=func]' -> ['iterable[' ,' key=func]'] |
|
817 | 817 | sig = sig.groups()[0].split(',') |
|
818 | 818 | ret = [] |
|
819 | 819 | for s in sig: |
|
820 | 820 | #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)') |
|
821 | 821 | ret += self.docstring_kwd_re.findall(s) |
|
822 | 822 | return ret |
|
823 | 823 | |
|
824 | 824 | def _default_arguments(self, obj): |
|
825 | 825 | """Return the list of default arguments of obj if it is callable, |
|
826 | 826 | or empty list otherwise.""" |
|
827 | 827 | call_obj = obj |
|
828 | 828 | ret = [] |
|
829 | 829 | if inspect.isbuiltin(obj): |
|
830 | 830 | pass |
|
831 | 831 | elif not (inspect.isfunction(obj) or inspect.ismethod(obj)): |
|
832 | 832 | if inspect.isclass(obj): |
|
833 | 833 | #for cython embededsignature=True the constructor docstring |
|
834 | 834 | #belongs to the object itself not __init__ |
|
835 | 835 | ret += self._default_arguments_from_docstring( |
|
836 | 836 | getattr(obj, '__doc__', '')) |
|
837 | 837 | # for classes, check for __init__,__new__ |
|
838 | 838 | call_obj = (getattr(obj, '__init__', None) or |
|
839 | 839 | getattr(obj, '__new__', None)) |
|
840 | 840 | # for all others, check if they are __call__able |
|
841 | 841 | elif hasattr(obj, '__call__'): |
|
842 | 842 | call_obj = obj.__call__ |
|
843 | 843 | ret += self._default_arguments_from_docstring( |
|
844 | 844 | getattr(call_obj, '__doc__', '')) |
|
845 | 845 | |
|
846 | 846 | _keeps = (inspect.Parameter.KEYWORD_ONLY, |
|
847 | 847 | inspect.Parameter.POSITIONAL_OR_KEYWORD) |
|
848 | 848 | |
|
849 | 849 | try: |
|
850 | 850 | sig = inspect.signature(call_obj) |
|
851 | 851 | ret.extend(k for k, v in sig.parameters.items() if |
|
852 | 852 | v.kind in _keeps) |
|
853 | 853 | except ValueError: |
|
854 | 854 | pass |
|
855 | 855 | |
|
856 | 856 | return list(set(ret)) |
|
857 | 857 | |
|
858 | 858 | def python_func_kw_matches(self,text): |
|
859 | 859 | """Match named parameters (kwargs) of the last open function""" |
|
860 | 860 | |
|
861 | 861 | if "." in text: # a parameter cannot be dotted |
|
862 | 862 | return [] |
|
863 | 863 | try: regexp = self.__funcParamsRegex |
|
864 | 864 | except AttributeError: |
|
865 | 865 | regexp = self.__funcParamsRegex = re.compile(r''' |
|
866 | 866 | '.*?(?<!\\)' | # single quoted strings or |
|
867 | 867 | ".*?(?<!\\)" | # double quoted strings or |
|
868 | 868 | \w+ | # identifier |
|
869 | 869 | \S # other characters |
|
870 | 870 | ''', re.VERBOSE | re.DOTALL) |
|
871 | 871 | # 1. find the nearest identifier that comes before an unclosed |
|
872 | 872 | # parenthesis before the cursor |
|
873 | 873 | # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo" |
|
874 | 874 | tokens = regexp.findall(self.text_until_cursor) |
|
875 | 875 | iterTokens = reversed(tokens); openPar = 0 |
|
876 | 876 | |
|
877 | 877 | for token in iterTokens: |
|
878 | 878 | if token == ')': |
|
879 | 879 | openPar -= 1 |
|
880 | 880 | elif token == '(': |
|
881 | 881 | openPar += 1 |
|
882 | 882 | if openPar > 0: |
|
883 | 883 | # found the last unclosed parenthesis |
|
884 | 884 | break |
|
885 | 885 | else: |
|
886 | 886 | return [] |
|
887 | 887 | # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) |
|
888 | 888 | ids = [] |
|
889 | 889 | isId = re.compile(r'\w+$').match |
|
890 | 890 | |
|
891 | 891 | while True: |
|
892 | 892 | try: |
|
893 | 893 | ids.append(next(iterTokens)) |
|
894 | 894 | if not isId(ids[-1]): |
|
895 | 895 | ids.pop(); break |
|
896 | 896 | if not next(iterTokens) == '.': |
|
897 | 897 | break |
|
898 | 898 | except StopIteration: |
|
899 | 899 | break |
|
900 | 900 | |
|
901 | 901 | # Find all named arguments already assigned to, as to avoid suggesting |
|
902 | 902 | # them again |
|
903 | 903 | usedNamedArgs = set() |
|
904 | 904 | par_level = -1 |
|
905 | 905 | for token, next_token in zip(tokens, tokens[1:]): |
|
906 | 906 | if token == '(': |
|
907 | 907 | par_level += 1 |
|
908 | 908 | elif token == ')': |
|
909 | 909 | par_level -= 1 |
|
910 | 910 | |
|
911 | 911 | if par_level != 0: |
|
912 | 912 | continue |
|
913 | 913 | |
|
914 | 914 | if next_token != '=': |
|
915 | 915 | continue |
|
916 | 916 | |
|
917 | 917 | usedNamedArgs.add(token) |
|
918 | 918 | |
|
919 | 919 | # lookup the candidate callable matches either using global_matches |
|
920 | 920 | # or attr_matches for dotted names |
|
921 | 921 | if len(ids) == 1: |
|
922 | 922 | callableMatches = self.global_matches(ids[0]) |
|
923 | 923 | else: |
|
924 | 924 | callableMatches = self.attr_matches('.'.join(ids[::-1])) |
|
925 | 925 | argMatches = [] |
|
926 | 926 | for callableMatch in callableMatches: |
|
927 | 927 | try: |
|
928 | 928 | namedArgs = self._default_arguments(eval(callableMatch, |
|
929 | 929 | self.namespace)) |
|
930 | 930 | except: |
|
931 | 931 | continue |
|
932 | 932 | |
|
933 | 933 | # Remove used named arguments from the list, no need to show twice |
|
934 | 934 | for namedArg in set(namedArgs) - usedNamedArgs: |
|
935 | 935 | if namedArg.startswith(text): |
|
936 | 936 | argMatches.append(u"%s=" %namedArg) |
|
937 | 937 | return argMatches |
|
938 | 938 | |
|
939 | 939 | def dict_key_matches(self, text): |
|
940 | 940 | "Match string keys in a dictionary, after e.g. 'foo[' " |
|
941 | 941 | def get_keys(obj): |
|
942 | 942 | # Objects can define their own completions by defining an |
|
943 | 943 | # _ipy_key_completions_() method. |
|
944 | 944 | method = get_real_method(obj, '_ipython_key_completions_') |
|
945 | 945 | if method is not None: |
|
946 | 946 | return method() |
|
947 | 947 | |
|
948 | 948 | # Special case some common in-memory dict-like types |
|
949 | 949 | if isinstance(obj, dict) or\ |
|
950 | 950 | _safe_isinstance(obj, 'pandas', 'DataFrame'): |
|
951 | 951 | try: |
|
952 | 952 | return list(obj.keys()) |
|
953 | 953 | except Exception: |
|
954 | 954 | return [] |
|
955 | 955 | elif _safe_isinstance(obj, 'numpy', 'ndarray') or\ |
|
956 | 956 | _safe_isinstance(obj, 'numpy', 'void'): |
|
957 | 957 | return obj.dtype.names or [] |
|
958 | 958 | return [] |
|
959 | 959 | |
|
960 | 960 | try: |
|
961 | 961 | regexps = self.__dict_key_regexps |
|
962 | 962 | except AttributeError: |
|
963 | 963 | dict_key_re_fmt = r'''(?x) |
|
964 | 964 | ( # match dict-referring expression wrt greedy setting |
|
965 | 965 | %s |
|
966 | 966 | ) |
|
967 | 967 | \[ # open bracket |
|
968 | 968 | \s* # and optional whitespace |
|
969 | 969 | ([uUbB]? # string prefix (r not handled) |
|
970 | 970 | (?: # unclosed string |
|
971 | 971 | '(?:[^']|(?<!\\)\\')* |
|
972 | 972 | | |
|
973 | 973 | "(?:[^"]|(?<!\\)\\")* |
|
974 | 974 | ) |
|
975 | 975 | )? |
|
976 | 976 | $ |
|
977 | 977 | ''' |
|
978 | 978 | regexps = self.__dict_key_regexps = { |
|
979 | 979 | False: re.compile(dict_key_re_fmt % ''' |
|
980 | 980 | # identifiers separated by . |
|
981 | 981 | (?!\d)\w+ |
|
982 | 982 | (?:\.(?!\d)\w+)* |
|
983 | 983 | '''), |
|
984 | 984 | True: re.compile(dict_key_re_fmt % ''' |
|
985 | 985 | .+ |
|
986 | 986 | ''') |
|
987 | 987 | } |
|
988 | 988 | |
|
989 | 989 | match = regexps[self.greedy].search(self.text_until_cursor) |
|
990 | 990 | if match is None: |
|
991 | 991 | return [] |
|
992 | 992 | |
|
993 | 993 | expr, prefix = match.groups() |
|
994 | 994 | try: |
|
995 | 995 | obj = eval(expr, self.namespace) |
|
996 | 996 | except Exception: |
|
997 | 997 | try: |
|
998 | 998 | obj = eval(expr, self.global_namespace) |
|
999 | 999 | except Exception: |
|
1000 | 1000 | return [] |
|
1001 | 1001 | |
|
1002 | 1002 | keys = get_keys(obj) |
|
1003 | 1003 | if not keys: |
|
1004 | 1004 | return keys |
|
1005 | 1005 | closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims) |
|
1006 | 1006 | if not matches: |
|
1007 | 1007 | return matches |
|
1008 | 1008 | |
|
1009 | 1009 | # get the cursor position of |
|
1010 | 1010 | # - the text being completed |
|
1011 | 1011 | # - the start of the key text |
|
1012 | 1012 | # - the start of the completion |
|
1013 | 1013 | text_start = len(self.text_until_cursor) - len(text) |
|
1014 | 1014 | if prefix: |
|
1015 | 1015 | key_start = match.start(2) |
|
1016 | 1016 | completion_start = key_start + token_offset |
|
1017 | 1017 | else: |
|
1018 | 1018 | key_start = completion_start = match.end() |
|
1019 | 1019 | |
|
1020 | 1020 | # grab the leading prefix, to make sure all completions start with `text` |
|
1021 | 1021 | if text_start > key_start: |
|
1022 | 1022 | leading = '' |
|
1023 | 1023 | else: |
|
1024 | 1024 | leading = text[text_start:completion_start] |
|
1025 | 1025 | |
|
1026 | 1026 | # the index of the `[` character |
|
1027 | 1027 | bracket_idx = match.end(1) |
|
1028 | 1028 | |
|
1029 | 1029 | # append closing quote and bracket as appropriate |
|
1030 | 1030 | # this is *not* appropriate if the opening quote or bracket is outside |
|
1031 | 1031 | # the text given to this method |
|
1032 | 1032 | suf = '' |
|
1033 | 1033 | continuation = self.line_buffer[len(self.text_until_cursor):] |
|
1034 | 1034 | if key_start > text_start and closing_quote: |
|
1035 | 1035 | # quotes were opened inside text, maybe close them |
|
1036 | 1036 | if continuation.startswith(closing_quote): |
|
1037 | 1037 | continuation = continuation[len(closing_quote):] |
|
1038 | 1038 | else: |
|
1039 | 1039 | suf += closing_quote |
|
1040 | 1040 | if bracket_idx > text_start: |
|
1041 | 1041 | # brackets were opened inside text, maybe close them |
|
1042 | 1042 | if not continuation.startswith(']'): |
|
1043 | 1043 | suf += ']' |
|
1044 | 1044 | |
|
1045 | 1045 | return [leading + k + suf for k in matches] |
|
1046 | 1046 | |
|
1047 | 1047 | def unicode_name_matches(self, text): |
|
1048 | 1048 | u"""Match Latex-like syntax for unicode characters base |
|
1049 | 1049 | on the name of the character. |
|
1050 | 1050 | |
|
1051 | 1051 | This does \\GREEK SMALL LETTER ETA -> η |
|
1052 | 1052 | |
|
1053 | 1053 | Works only on valid python 3 identifier, or on combining characters that |
|
1054 | 1054 | will combine to form a valid identifier. |
|
1055 | 1055 | |
|
1056 | 1056 | Used on Python 3 only. |
|
1057 | 1057 | """ |
|
1058 | 1058 | slashpos = text.rfind('\\') |
|
1059 | 1059 | if slashpos > -1: |
|
1060 | 1060 | s = text[slashpos+1:] |
|
1061 | 1061 | try : |
|
1062 | 1062 | unic = unicodedata.lookup(s) |
|
1063 | 1063 | # allow combining chars |
|
1064 | 1064 | if ('a'+unic).isidentifier(): |
|
1065 | 1065 | return '\\'+s,[unic] |
|
1066 | 1066 | except KeyError: |
|
1067 | 1067 | pass |
|
1068 | 1068 | return u'', [] |
|
1069 | 1069 | |
|
1070 | 1070 | |
|
1071 | 1071 | |
|
1072 | 1072 | |
|
1073 | 1073 | def latex_matches(self, text): |
|
1074 | 1074 | u"""Match Latex syntax for unicode characters. |
|
1075 | 1075 | |
|
1076 | 1076 | This does both \\alp -> \\alpha and \\alpha -> α |
|
1077 | 1077 | |
|
1078 | 1078 | Used on Python 3 only. |
|
1079 | 1079 | """ |
|
1080 | 1080 | slashpos = text.rfind('\\') |
|
1081 | 1081 | if slashpos > -1: |
|
1082 | 1082 | s = text[slashpos:] |
|
1083 | 1083 | if s in latex_symbols: |
|
1084 | 1084 | # Try to complete a full latex symbol to unicode |
|
1085 | 1085 | # \\alpha -> α |
|
1086 | 1086 | return s, [latex_symbols[s]] |
|
1087 | 1087 | else: |
|
1088 | 1088 | # If a user has partially typed a latex symbol, give them |
|
1089 | 1089 | # a full list of options \al -> [\aleph, \alpha] |
|
1090 | 1090 | matches = [k for k in latex_symbols if k.startswith(s)] |
|
1091 | 1091 | return s, matches |
|
1092 | 1092 | return u'', [] |
|
1093 | 1093 | |
|
1094 | 1094 | def dispatch_custom_completer(self, text): |
|
1095 | 1095 | if not self.custom_completers: |
|
1096 | 1096 | return |
|
1097 | 1097 | |
|
1098 | 1098 | line = self.line_buffer |
|
1099 | 1099 | if not line.strip(): |
|
1100 | 1100 | return None |
|
1101 | 1101 | |
|
1102 | 1102 | # Create a little structure to pass all the relevant information about |
|
1103 | 1103 | # the current completion to any custom completer. |
|
1104 | 1104 | event = Bunch() |
|
1105 | 1105 | event.line = line |
|
1106 | 1106 | event.symbol = text |
|
1107 | 1107 | cmd = line.split(None,1)[0] |
|
1108 | 1108 | event.command = cmd |
|
1109 | 1109 | event.text_until_cursor = self.text_until_cursor |
|
1110 | 1110 | |
|
1111 | 1111 | # for foo etc, try also to find completer for %foo |
|
1112 | 1112 | if not cmd.startswith(self.magic_escape): |
|
1113 | 1113 | try_magic = self.custom_completers.s_matches( |
|
1114 | 1114 | self.magic_escape + cmd) |
|
1115 | 1115 | else: |
|
1116 | 1116 | try_magic = [] |
|
1117 | 1117 | |
|
1118 | 1118 | for c in itertools.chain(self.custom_completers.s_matches(cmd), |
|
1119 | 1119 | try_magic, |
|
1120 | 1120 | self.custom_completers.flat_matches(self.text_until_cursor)): |
|
1121 | 1121 | try: |
|
1122 | 1122 | res = c(event) |
|
1123 | 1123 | if res: |
|
1124 | 1124 | # first, try case sensitive match |
|
1125 | 1125 | withcase = [cast_unicode_py2(r) for r in res if r.startswith(text)] |
|
1126 | 1126 | if withcase: |
|
1127 | 1127 | return withcase |
|
1128 | 1128 | # if none, then case insensitive ones are ok too |
|
1129 | 1129 | text_low = text.lower() |
|
1130 | 1130 | return [cast_unicode_py2(r) for r in res if r.lower().startswith(text_low)] |
|
1131 | 1131 | except TryNext: |
|
1132 | 1132 | pass |
|
1133 | 1133 | |
|
1134 | 1134 | return None |
|
1135 | 1135 | |
|
1136 | 1136 | @_strip_single_trailing_space |
|
1137 | 1137 | def complete(self, text=None, line_buffer=None, cursor_pos=None): |
|
1138 | 1138 | """Find completions for the given text and line context. |
|
1139 | 1139 | |
|
1140 | 1140 | Note that both the text and the line_buffer are optional, but at least |
|
1141 | 1141 | one of them must be given. |
|
1142 | 1142 | |
|
1143 | 1143 | Parameters |
|
1144 | 1144 | ---------- |
|
1145 | 1145 | text : string, optional |
|
1146 | 1146 | Text to perform the completion on. If not given, the line buffer |
|
1147 | 1147 | is split using the instance's CompletionSplitter object. |
|
1148 | 1148 | |
|
1149 | 1149 | line_buffer : string, optional |
|
1150 | 1150 | If not given, the completer attempts to obtain the current line |
|
1151 | 1151 | buffer via readline. This keyword allows clients which are |
|
1152 | 1152 | requesting for text completions in non-readline contexts to inform |
|
1153 | 1153 | the completer of the entire text. |
|
1154 | 1154 | |
|
1155 | 1155 | cursor_pos : int, optional |
|
1156 | 1156 | Index of the cursor in the full line buffer. Should be provided by |
|
1157 | 1157 | remote frontends where kernel has no access to frontend state. |
|
1158 | 1158 | |
|
1159 | 1159 | Returns |
|
1160 | 1160 | ------- |
|
1161 | 1161 | text : str |
|
1162 | 1162 | Text that was actually used in the completion. |
|
1163 | 1163 | |
|
1164 | 1164 | matches : list |
|
1165 | 1165 | A list of completion matches. |
|
1166 | 1166 | """ |
|
1167 | 1167 | # if the cursor position isn't given, the only sane assumption we can |
|
1168 | 1168 | # make is that it's at the end of the line (the common case) |
|
1169 | 1169 | if cursor_pos is None: |
|
1170 | 1170 | cursor_pos = len(line_buffer) if text is None else len(text) |
|
1171 | 1171 | |
|
1172 | 1172 | if self.use_main_ns: |
|
1173 | 1173 | self.namespace = __main__.__dict__ |
|
1174 | 1174 | |
|
1175 | 1175 | if PY3: |
|
1176 | 1176 | |
|
1177 | 1177 | base_text = text if not line_buffer else line_buffer[:cursor_pos] |
|
1178 | 1178 | latex_text, latex_matches = self.latex_matches(base_text) |
|
1179 | 1179 | if latex_matches: |
|
1180 | 1180 | return latex_text, latex_matches |
|
1181 | 1181 | name_text = '' |
|
1182 | 1182 | name_matches = [] |
|
1183 | 1183 | for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches): |
|
1184 | 1184 | name_text, name_matches = meth(base_text) |
|
1185 | 1185 | if name_text: |
|
1186 | 1186 | return name_text, name_matches |
|
1187 | 1187 | |
|
1188 | 1188 | # if text is either None or an empty string, rely on the line buffer |
|
1189 | 1189 | if not text: |
|
1190 | 1190 | text = self.splitter.split_line(line_buffer, cursor_pos) |
|
1191 | 1191 | |
|
1192 | 1192 | # If no line buffer is given, assume the input text is all there was |
|
1193 | 1193 | if line_buffer is None: |
|
1194 | 1194 | line_buffer = text |
|
1195 | 1195 | |
|
1196 | 1196 | self.line_buffer = line_buffer |
|
1197 | 1197 | self.text_until_cursor = self.line_buffer[:cursor_pos] |
|
1198 | 1198 | |
|
1199 | 1199 | # Start with a clean slate of completions |
|
1200 | 1200 | self.matches[:] = [] |
|
1201 | 1201 | custom_res = self.dispatch_custom_completer(text) |
|
1202 | 1202 | if custom_res is not None: |
|
1203 | 1203 | # did custom completers produce something? |
|
1204 | 1204 | self.matches = custom_res |
|
1205 | 1205 | else: |
|
1206 | 1206 | # Extend the list of completions with the results of each |
|
1207 | 1207 | # matcher, so we return results to the user from all |
|
1208 | 1208 | # namespaces. |
|
1209 | 1209 | if self.merge_completions: |
|
1210 | 1210 | self.matches = [] |
|
1211 | 1211 | for matcher in self.matchers: |
|
1212 | 1212 | try: |
|
1213 | 1213 | self.matches.extend(matcher(text)) |
|
1214 | 1214 | except: |
|
1215 | 1215 | # Show the ugly traceback if the matcher causes an |
|
1216 | 1216 | # exception, but do NOT crash the kernel! |
|
1217 | 1217 | sys.excepthook(*sys.exc_info()) |
|
1218 | 1218 | else: |
|
1219 | 1219 | for matcher in self.matchers: |
|
1220 | 1220 | self.matches = matcher(text) |
|
1221 | 1221 | if self.matches: |
|
1222 | 1222 | break |
|
1223 | 1223 | # FIXME: we should extend our api to return a dict with completions for |
|
1224 | 1224 | # different types of objects. The rlcomplete() method could then |
|
1225 | 1225 | # simply collapse the dict into a list for readline, but we'd have |
|
1226 | 1226 | # richer completion semantics in other evironments. |
|
1227 | 1227 | self.matches = sorted(set(self.matches), key=completions_sorting_key) |
|
1228 | 1228 | |
|
1229 | 1229 | return text, self.matches |
@@ -1,343 +1,342 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """Implementations for various useful completers. |
|
3 | 3 | |
|
4 | 4 | These are all loaded by default by IPython. |
|
5 | 5 | """ |
|
6 | 6 | #----------------------------------------------------------------------------- |
|
7 | 7 | # Copyright (C) 2010-2011 The IPython Development Team. |
|
8 | 8 | # |
|
9 | 9 | # Distributed under the terms of the BSD License. |
|
10 | 10 | # |
|
11 | 11 | # The full license is in the file COPYING.txt, distributed with this software. |
|
12 | 12 | #----------------------------------------------------------------------------- |
|
13 | 13 | |
|
14 | 14 | #----------------------------------------------------------------------------- |
|
15 | 15 | # Imports |
|
16 | 16 | #----------------------------------------------------------------------------- |
|
17 | 17 | |
|
18 | 18 | # Stdlib imports |
|
19 | 19 | import glob |
|
20 | 20 | import inspect |
|
21 | 21 | import os |
|
22 | 22 | import re |
|
23 | 23 | import sys |
|
24 | 24 | from importlib import import_module |
|
25 | 25 | from importlib.machinery import all_suffixes |
|
26 | 26 | |
|
27 | 27 | |
|
28 | 28 | # Third-party imports |
|
29 | 29 | from time import time |
|
30 | 30 | from zipimport import zipimporter |
|
31 | 31 | |
|
32 | 32 | # Our own imports |
|
33 | 33 | from IPython.core.completer import expand_user, compress_user |
|
34 | 34 | from IPython.core.error import TryNext |
|
35 | 35 | from IPython.utils._process_common import arg_split |
|
36 | from IPython.utils.py3compat import string_types | |
|
37 | 36 | |
|
38 | 37 | # FIXME: this should be pulled in with the right call via the component system |
|
39 | 38 | from IPython import get_ipython |
|
40 | 39 | |
|
41 | 40 | #----------------------------------------------------------------------------- |
|
42 | 41 | # Globals and constants |
|
43 | 42 | #----------------------------------------------------------------------------- |
|
44 | 43 | _suffixes = all_suffixes() |
|
45 | 44 | |
|
46 | 45 | # Time in seconds after which the rootmodules will be stored permanently in the |
|
47 | 46 | # ipython ip.db database (kept in the user's .ipython dir). |
|
48 | 47 | TIMEOUT_STORAGE = 2 |
|
49 | 48 | |
|
50 | 49 | # Time in seconds after which we give up |
|
51 | 50 | TIMEOUT_GIVEUP = 20 |
|
52 | 51 | |
|
53 | 52 | # Regular expression for the python import statement |
|
54 | 53 | import_re = re.compile(r'(?P<name>[a-zA-Z_][a-zA-Z0-9_]*?)' |
|
55 | 54 | r'(?P<package>[/\\]__init__)?' |
|
56 | 55 | r'(?P<suffix>%s)$' % |
|
57 | 56 | r'|'.join(re.escape(s) for s in _suffixes)) |
|
58 | 57 | |
|
59 | 58 | # RE for the ipython %run command (python + ipython scripts) |
|
60 | 59 | magic_run_re = re.compile(r'.*(\.ipy|\.ipynb|\.py[w]?)$') |
|
61 | 60 | |
|
62 | 61 | #----------------------------------------------------------------------------- |
|
63 | 62 | # Local utilities |
|
64 | 63 | #----------------------------------------------------------------------------- |
|
65 | 64 | |
|
66 | 65 | def module_list(path): |
|
67 | 66 | """ |
|
68 | 67 | Return the list containing the names of the modules available in the given |
|
69 | 68 | folder. |
|
70 | 69 | """ |
|
71 | 70 | # sys.path has the cwd as an empty string, but isdir/listdir need it as '.' |
|
72 | 71 | if path == '': |
|
73 | 72 | path = '.' |
|
74 | 73 | |
|
75 | 74 | # A few local constants to be used in loops below |
|
76 | 75 | pjoin = os.path.join |
|
77 | 76 | |
|
78 | 77 | if os.path.isdir(path): |
|
79 | 78 | # Build a list of all files in the directory and all files |
|
80 | 79 | # in its subdirectories. For performance reasons, do not |
|
81 | 80 | # recurse more than one level into subdirectories. |
|
82 | 81 | files = [] |
|
83 | 82 | for root, dirs, nondirs in os.walk(path, followlinks=True): |
|
84 | 83 | subdir = root[len(path)+1:] |
|
85 | 84 | if subdir: |
|
86 | 85 | files.extend(pjoin(subdir, f) for f in nondirs) |
|
87 | 86 | dirs[:] = [] # Do not recurse into additional subdirectories. |
|
88 | 87 | else: |
|
89 | 88 | files.extend(nondirs) |
|
90 | 89 | |
|
91 | 90 | else: |
|
92 | 91 | try: |
|
93 | 92 | files = list(zipimporter(path)._files.keys()) |
|
94 | 93 | except: |
|
95 | 94 | files = [] |
|
96 | 95 | |
|
97 | 96 | # Build a list of modules which match the import_re regex. |
|
98 | 97 | modules = [] |
|
99 | 98 | for f in files: |
|
100 | 99 | m = import_re.match(f) |
|
101 | 100 | if m: |
|
102 | 101 | modules.append(m.group('name')) |
|
103 | 102 | return list(set(modules)) |
|
104 | 103 | |
|
105 | 104 | |
|
106 | 105 | def get_root_modules(): |
|
107 | 106 | """ |
|
108 | 107 | Returns a list containing the names of all the modules available in the |
|
109 | 108 | folders of the pythonpath. |
|
110 | 109 | |
|
111 | 110 | ip.db['rootmodules_cache'] maps sys.path entries to list of modules. |
|
112 | 111 | """ |
|
113 | 112 | ip = get_ipython() |
|
114 | 113 | rootmodules_cache = ip.db.get('rootmodules_cache', {}) |
|
115 | 114 | rootmodules = list(sys.builtin_module_names) |
|
116 | 115 | start_time = time() |
|
117 | 116 | store = False |
|
118 | 117 | for path in sys.path: |
|
119 | 118 | try: |
|
120 | 119 | modules = rootmodules_cache[path] |
|
121 | 120 | except KeyError: |
|
122 | 121 | modules = module_list(path) |
|
123 | 122 | try: |
|
124 | 123 | modules.remove('__init__') |
|
125 | 124 | except ValueError: |
|
126 | 125 | pass |
|
127 | 126 | if path not in ('', '.'): # cwd modules should not be cached |
|
128 | 127 | rootmodules_cache[path] = modules |
|
129 | 128 | if time() - start_time > TIMEOUT_STORAGE and not store: |
|
130 | 129 | store = True |
|
131 | 130 | print("\nCaching the list of root modules, please wait!") |
|
132 | 131 | print("(This will only be done once - type '%rehashx' to " |
|
133 | 132 | "reset cache!)\n") |
|
134 | 133 | sys.stdout.flush() |
|
135 | 134 | if time() - start_time > TIMEOUT_GIVEUP: |
|
136 | 135 | print("This is taking too long, we give up.\n") |
|
137 | 136 | return [] |
|
138 | 137 | rootmodules.extend(modules) |
|
139 | 138 | if store: |
|
140 | 139 | ip.db['rootmodules_cache'] = rootmodules_cache |
|
141 | 140 | rootmodules = list(set(rootmodules)) |
|
142 | 141 | return rootmodules |
|
143 | 142 | |
|
144 | 143 | |
|
145 | 144 | def is_importable(module, attr, only_modules): |
|
146 | 145 | if only_modules: |
|
147 | 146 | return inspect.ismodule(getattr(module, attr)) |
|
148 | 147 | else: |
|
149 | 148 | return not(attr[:2] == '__' and attr[-2:] == '__') |
|
150 | 149 | |
|
151 | 150 | def try_import(mod, only_modules=False): |
|
152 | 151 | try: |
|
153 | 152 | m = import_module(mod) |
|
154 | 153 | except: |
|
155 | 154 | return [] |
|
156 | 155 | |
|
157 | 156 | m_is_init = hasattr(m, '__file__') and '__init__' in m.__file__ |
|
158 | 157 | |
|
159 | 158 | completions = [] |
|
160 | 159 | if (not hasattr(m, '__file__')) or (not only_modules) or m_is_init: |
|
161 | 160 | completions.extend( [attr for attr in dir(m) if |
|
162 | 161 | is_importable(m, attr, only_modules)]) |
|
163 | 162 | |
|
164 | 163 | completions.extend(getattr(m, '__all__', [])) |
|
165 | 164 | if m_is_init: |
|
166 | 165 | completions.extend(module_list(os.path.dirname(m.__file__))) |
|
167 |
completions = {c for c in completions if isinstance(c, str |
|
|
166 | completions = {c for c in completions if isinstance(c, str)} | |
|
168 | 167 | completions.discard('__init__') |
|
169 | 168 | return list(completions) |
|
170 | 169 | |
|
171 | 170 | |
|
172 | 171 | #----------------------------------------------------------------------------- |
|
173 | 172 | # Completion-related functions. |
|
174 | 173 | #----------------------------------------------------------------------------- |
|
175 | 174 | |
|
176 | 175 | def quick_completer(cmd, completions): |
|
177 | 176 | """ Easily create a trivial completer for a command. |
|
178 | 177 | |
|
179 | 178 | Takes either a list of completions, or all completions in string (that will |
|
180 | 179 | be split on whitespace). |
|
181 | 180 | |
|
182 | 181 | Example:: |
|
183 | 182 | |
|
184 | 183 | [d:\ipython]|1> import ipy_completers |
|
185 | 184 | [d:\ipython]|2> ipy_completers.quick_completer('foo', ['bar','baz']) |
|
186 | 185 | [d:\ipython]|3> foo b<TAB> |
|
187 | 186 | bar baz |
|
188 | 187 | [d:\ipython]|3> foo ba |
|
189 | 188 | """ |
|
190 | 189 | |
|
191 |
if isinstance(completions, str |
|
|
190 | if isinstance(completions, str): | |
|
192 | 191 | completions = completions.split() |
|
193 | 192 | |
|
194 | 193 | def do_complete(self, event): |
|
195 | 194 | return completions |
|
196 | 195 | |
|
197 | 196 | get_ipython().set_hook('complete_command',do_complete, str_key = cmd) |
|
198 | 197 | |
|
199 | 198 | def module_completion(line): |
|
200 | 199 | """ |
|
201 | 200 | Returns a list containing the completion possibilities for an import line. |
|
202 | 201 | |
|
203 | 202 | The line looks like this : |
|
204 | 203 | 'import xml.d' |
|
205 | 204 | 'from xml.dom import' |
|
206 | 205 | """ |
|
207 | 206 | |
|
208 | 207 | words = line.split(' ') |
|
209 | 208 | nwords = len(words) |
|
210 | 209 | |
|
211 | 210 | # from whatever <tab> -> 'import ' |
|
212 | 211 | if nwords == 3 and words[0] == 'from': |
|
213 | 212 | return ['import '] |
|
214 | 213 | |
|
215 | 214 | # 'from xy<tab>' or 'import xy<tab>' |
|
216 | 215 | if nwords < 3 and (words[0] in {'%aimport', 'import', 'from'}) : |
|
217 | 216 | if nwords == 1: |
|
218 | 217 | return get_root_modules() |
|
219 | 218 | mod = words[1].split('.') |
|
220 | 219 | if len(mod) < 2: |
|
221 | 220 | return get_root_modules() |
|
222 | 221 | completion_list = try_import('.'.join(mod[:-1]), True) |
|
223 | 222 | return ['.'.join(mod[:-1] + [el]) for el in completion_list] |
|
224 | 223 | |
|
225 | 224 | # 'from xyz import abc<tab>' |
|
226 | 225 | if nwords >= 3 and words[0] == 'from': |
|
227 | 226 | mod = words[1] |
|
228 | 227 | return try_import(mod) |
|
229 | 228 | |
|
230 | 229 | #----------------------------------------------------------------------------- |
|
231 | 230 | # Completers |
|
232 | 231 | #----------------------------------------------------------------------------- |
|
233 | 232 | # These all have the func(self, event) signature to be used as custom |
|
234 | 233 | # completers |
|
235 | 234 | |
|
236 | 235 | def module_completer(self,event): |
|
237 | 236 | """Give completions after user has typed 'import ...' or 'from ...'""" |
|
238 | 237 | |
|
239 | 238 | # This works in all versions of python. While 2.5 has |
|
240 | 239 | # pkgutil.walk_packages(), that particular routine is fairly dangerous, |
|
241 | 240 | # since it imports *EVERYTHING* on sys.path. That is: a) very slow b) full |
|
242 | 241 | # of possibly problematic side effects. |
|
243 | 242 | # This search the folders in the sys.path for available modules. |
|
244 | 243 | |
|
245 | 244 | return module_completion(event.line) |
|
246 | 245 | |
|
247 | 246 | # FIXME: there's a lot of logic common to the run, cd and builtin file |
|
248 | 247 | # completers, that is currently reimplemented in each. |
|
249 | 248 | |
|
250 | 249 | def magic_run_completer(self, event): |
|
251 | 250 | """Complete files that end in .py or .ipy or .ipynb for the %run command. |
|
252 | 251 | """ |
|
253 | 252 | comps = arg_split(event.line, strict=False) |
|
254 | 253 | # relpath should be the current token that we need to complete. |
|
255 | 254 | if (len(comps) > 1) and (not event.line.endswith(' ')): |
|
256 | 255 | relpath = comps[-1].strip("'\"") |
|
257 | 256 | else: |
|
258 | 257 | relpath = '' |
|
259 | 258 | |
|
260 | 259 | #print("\nev=", event) # dbg |
|
261 | 260 | #print("rp=", relpath) # dbg |
|
262 | 261 | #print('comps=', comps) # dbg |
|
263 | 262 | |
|
264 | 263 | lglob = glob.glob |
|
265 | 264 | isdir = os.path.isdir |
|
266 | 265 | relpath, tilde_expand, tilde_val = expand_user(relpath) |
|
267 | 266 | |
|
268 | 267 | # Find if the user has already typed the first filename, after which we |
|
269 | 268 | # should complete on all files, since after the first one other files may |
|
270 | 269 | # be arguments to the input script. |
|
271 | 270 | |
|
272 | 271 | if any(magic_run_re.match(c) for c in comps): |
|
273 | 272 | matches = [f.replace('\\','/') + ('/' if isdir(f) else '') |
|
274 | 273 | for f in lglob(relpath+'*')] |
|
275 | 274 | else: |
|
276 | 275 | dirs = [f.replace('\\','/') + "/" for f in lglob(relpath+'*') if isdir(f)] |
|
277 | 276 | pys = [f.replace('\\','/') |
|
278 | 277 | for f in lglob(relpath+'*.py') + lglob(relpath+'*.ipy') + |
|
279 | 278 | lglob(relpath+'*.ipynb') + lglob(relpath + '*.pyw')] |
|
280 | 279 | |
|
281 | 280 | matches = dirs + pys |
|
282 | 281 | |
|
283 | 282 | #print('run comp:', dirs+pys) # dbg |
|
284 | 283 | return [compress_user(p, tilde_expand, tilde_val) for p in matches] |
|
285 | 284 | |
|
286 | 285 | |
|
287 | 286 | def cd_completer(self, event): |
|
288 | 287 | """Completer function for cd, which only returns directories.""" |
|
289 | 288 | ip = get_ipython() |
|
290 | 289 | relpath = event.symbol |
|
291 | 290 | |
|
292 | 291 | #print(event) # dbg |
|
293 | 292 | if event.line.endswith('-b') or ' -b ' in event.line: |
|
294 | 293 | # return only bookmark completions |
|
295 | 294 | bkms = self.db.get('bookmarks', None) |
|
296 | 295 | if bkms: |
|
297 | 296 | return bkms.keys() |
|
298 | 297 | else: |
|
299 | 298 | return [] |
|
300 | 299 | |
|
301 | 300 | if event.symbol == '-': |
|
302 | 301 | width_dh = str(len(str(len(ip.user_ns['_dh']) + 1))) |
|
303 | 302 | # jump in directory history by number |
|
304 | 303 | fmt = '-%0' + width_dh +'d [%s]' |
|
305 | 304 | ents = [ fmt % (i,s) for i,s in enumerate(ip.user_ns['_dh'])] |
|
306 | 305 | if len(ents) > 1: |
|
307 | 306 | return ents |
|
308 | 307 | return [] |
|
309 | 308 | |
|
310 | 309 | if event.symbol.startswith('--'): |
|
311 | 310 | return ["--" + os.path.basename(d) for d in ip.user_ns['_dh']] |
|
312 | 311 | |
|
313 | 312 | # Expand ~ in path and normalize directory separators. |
|
314 | 313 | relpath, tilde_expand, tilde_val = expand_user(relpath) |
|
315 | 314 | relpath = relpath.replace('\\','/') |
|
316 | 315 | |
|
317 | 316 | found = [] |
|
318 | 317 | for d in [f.replace('\\','/') + '/' for f in glob.glob(relpath+'*') |
|
319 | 318 | if os.path.isdir(f)]: |
|
320 | 319 | if ' ' in d: |
|
321 | 320 | # we don't want to deal with any of that, complex code |
|
322 | 321 | # for this is elsewhere |
|
323 | 322 | raise TryNext |
|
324 | 323 | |
|
325 | 324 | found.append(d) |
|
326 | 325 | |
|
327 | 326 | if not found: |
|
328 | 327 | if os.path.isdir(relpath): |
|
329 | 328 | return [compress_user(relpath, tilde_expand, tilde_val)] |
|
330 | 329 | |
|
331 | 330 | # if no completions so far, try bookmarks |
|
332 | 331 | bks = self.db.get('bookmarks',{}) |
|
333 | 332 | bkmatches = [s for s in bks if s.startswith(event.symbol)] |
|
334 | 333 | if bkmatches: |
|
335 | 334 | return bkmatches |
|
336 | 335 | |
|
337 | 336 | raise TryNext |
|
338 | 337 | |
|
339 | 338 | return [compress_user(p, tilde_expand, tilde_val) for p in found] |
|
340 | 339 | |
|
341 | 340 | def reset_completer(self, event): |
|
342 | 341 | "A completer for %reset magic" |
|
343 | 342 | return '-f -s in out array dhist'.split() |
@@ -1,215 +1,215 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """sys.excepthook for IPython itself, leaves a detailed report on disk. |
|
3 | 3 | |
|
4 | 4 | Authors: |
|
5 | 5 | |
|
6 | 6 | * Fernando Perez |
|
7 | 7 | * Brian E. Granger |
|
8 | 8 | """ |
|
9 | 9 | |
|
10 | 10 | #----------------------------------------------------------------------------- |
|
11 | 11 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
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 os |
|
23 | 23 | import sys |
|
24 | 24 | import traceback |
|
25 | 25 | from pprint import pformat |
|
26 | 26 | |
|
27 | 27 | from IPython.core import ultratb |
|
28 | 28 | from IPython.core.release import author_email |
|
29 | 29 | from IPython.utils.sysinfo import sys_info |
|
30 |
from IPython.utils.py3compat import input |
|
|
30 | from IPython.utils.py3compat import input | |
|
31 | 31 | |
|
32 | 32 | #----------------------------------------------------------------------------- |
|
33 | 33 | # Code |
|
34 | 34 | #----------------------------------------------------------------------------- |
|
35 | 35 | |
|
36 | 36 | # Template for the user message. |
|
37 | 37 | _default_message_template = """\ |
|
38 | 38 | Oops, {app_name} crashed. We do our best to make it stable, but... |
|
39 | 39 | |
|
40 | 40 | A crash report was automatically generated with the following information: |
|
41 | 41 | - A verbatim copy of the crash traceback. |
|
42 | 42 | - A copy of your input history during this session. |
|
43 | 43 | - Data on your current {app_name} configuration. |
|
44 | 44 | |
|
45 | 45 | It was left in the file named: |
|
46 | 46 | \t'{crash_report_fname}' |
|
47 | 47 | If you can email this file to the developers, the information in it will help |
|
48 | 48 | them in understanding and correcting the problem. |
|
49 | 49 | |
|
50 | 50 | You can mail it to: {contact_name} at {contact_email} |
|
51 | 51 | with the subject '{app_name} Crash Report'. |
|
52 | 52 | |
|
53 | 53 | If you want to do it now, the following command will work (under Unix): |
|
54 | 54 | mail -s '{app_name} Crash Report' {contact_email} < {crash_report_fname} |
|
55 | 55 | |
|
56 | 56 | To ensure accurate tracking of this issue, please file a report about it at: |
|
57 | 57 | {bug_tracker} |
|
58 | 58 | """ |
|
59 | 59 | |
|
60 | 60 | _lite_message_template = """ |
|
61 | 61 | If you suspect this is an IPython bug, please report it at: |
|
62 | 62 | https://github.com/ipython/ipython/issues |
|
63 | 63 | or send an email to the mailing list at {email} |
|
64 | 64 | |
|
65 | 65 | You can print a more detailed traceback right now with "%tb", or use "%debug" |
|
66 | 66 | to interactively debug it. |
|
67 | 67 | |
|
68 | 68 | Extra-detailed tracebacks for bug-reporting purposes can be enabled via: |
|
69 | 69 | {config}Application.verbose_crash=True |
|
70 | 70 | """ |
|
71 | 71 | |
|
72 | 72 | |
|
73 | 73 | class CrashHandler(object): |
|
74 | 74 | """Customizable crash handlers for IPython applications. |
|
75 | 75 | |
|
76 | 76 | Instances of this class provide a :meth:`__call__` method which can be |
|
77 | 77 | used as a ``sys.excepthook``. The :meth:`__call__` signature is:: |
|
78 | 78 | |
|
79 | 79 | def __call__(self, etype, evalue, etb) |
|
80 | 80 | """ |
|
81 | 81 | |
|
82 | 82 | message_template = _default_message_template |
|
83 | 83 | section_sep = '\n\n'+'*'*75+'\n\n' |
|
84 | 84 | |
|
85 | 85 | def __init__(self, app, contact_name=None, contact_email=None, |
|
86 | 86 | bug_tracker=None, show_crash_traceback=True, call_pdb=False): |
|
87 | 87 | """Create a new crash handler |
|
88 | 88 | |
|
89 | 89 | Parameters |
|
90 | 90 | ---------- |
|
91 | 91 | app : Application |
|
92 | 92 | A running :class:`Application` instance, which will be queried at |
|
93 | 93 | crash time for internal information. |
|
94 | 94 | |
|
95 | 95 | contact_name : str |
|
96 | 96 | A string with the name of the person to contact. |
|
97 | 97 | |
|
98 | 98 | contact_email : str |
|
99 | 99 | A string with the email address of the contact. |
|
100 | 100 | |
|
101 | 101 | bug_tracker : str |
|
102 | 102 | A string with the URL for your project's bug tracker. |
|
103 | 103 | |
|
104 | 104 | show_crash_traceback : bool |
|
105 | 105 | If false, don't print the crash traceback on stderr, only generate |
|
106 | 106 | the on-disk report |
|
107 | 107 | |
|
108 | 108 | Non-argument instance attributes: |
|
109 | 109 | |
|
110 | 110 | These instances contain some non-argument attributes which allow for |
|
111 | 111 | further customization of the crash handler's behavior. Please see the |
|
112 | 112 | source for further details. |
|
113 | 113 | """ |
|
114 | 114 | self.crash_report_fname = "Crash_report_%s.txt" % app.name |
|
115 | 115 | self.app = app |
|
116 | 116 | self.call_pdb = call_pdb |
|
117 | 117 | #self.call_pdb = True # dbg |
|
118 | 118 | self.show_crash_traceback = show_crash_traceback |
|
119 | 119 | self.info = dict(app_name = app.name, |
|
120 | 120 | contact_name = contact_name, |
|
121 | 121 | contact_email = contact_email, |
|
122 | 122 | bug_tracker = bug_tracker, |
|
123 | 123 | crash_report_fname = self.crash_report_fname) |
|
124 | 124 | |
|
125 | 125 | |
|
126 | 126 | def __call__(self, etype, evalue, etb): |
|
127 | 127 | """Handle an exception, call for compatible with sys.excepthook""" |
|
128 | 128 | |
|
129 | 129 | # do not allow the crash handler to be called twice without reinstalling it |
|
130 | 130 | # this prevents unlikely errors in the crash handling from entering an |
|
131 | 131 | # infinite loop. |
|
132 | 132 | sys.excepthook = sys.__excepthook__ |
|
133 | 133 | |
|
134 | 134 | # Report tracebacks shouldn't use color in general (safer for users) |
|
135 | 135 | color_scheme = 'NoColor' |
|
136 | 136 | |
|
137 | 137 | # Use this ONLY for developer debugging (keep commented out for release) |
|
138 | 138 | #color_scheme = 'Linux' # dbg |
|
139 | 139 | try: |
|
140 | 140 | rptdir = self.app.ipython_dir |
|
141 | 141 | except: |
|
142 | rptdir = getcwd() | |
|
142 | rptdir = os.getcwd() | |
|
143 | 143 | if rptdir is None or not os.path.isdir(rptdir): |
|
144 | rptdir = getcwd() | |
|
144 | rptdir = os.getcwd() | |
|
145 | 145 | report_name = os.path.join(rptdir,self.crash_report_fname) |
|
146 | 146 | # write the report filename into the instance dict so it can get |
|
147 | 147 | # properly expanded out in the user message template |
|
148 | 148 | self.crash_report_fname = report_name |
|
149 | 149 | self.info['crash_report_fname'] = report_name |
|
150 | 150 | TBhandler = ultratb.VerboseTB( |
|
151 | 151 | color_scheme=color_scheme, |
|
152 | 152 | long_header=1, |
|
153 | 153 | call_pdb=self.call_pdb, |
|
154 | 154 | ) |
|
155 | 155 | if self.call_pdb: |
|
156 | 156 | TBhandler(etype,evalue,etb) |
|
157 | 157 | return |
|
158 | 158 | else: |
|
159 | 159 | traceback = TBhandler.text(etype,evalue,etb,context=31) |
|
160 | 160 | |
|
161 | 161 | # print traceback to screen |
|
162 | 162 | if self.show_crash_traceback: |
|
163 | 163 | print(traceback, file=sys.stderr) |
|
164 | 164 | |
|
165 | 165 | # and generate a complete report on disk |
|
166 | 166 | try: |
|
167 | 167 | report = open(report_name,'w') |
|
168 | 168 | except: |
|
169 | 169 | print('Could not create crash report on disk.', file=sys.stderr) |
|
170 | 170 | return |
|
171 | 171 | |
|
172 | 172 | # Inform user on stderr of what happened |
|
173 | 173 | print('\n'+'*'*70+'\n', file=sys.stderr) |
|
174 | 174 | print(self.message_template.format(**self.info), file=sys.stderr) |
|
175 | 175 | |
|
176 | 176 | # Construct report on disk |
|
177 | 177 | report.write(self.make_report(traceback)) |
|
178 | 178 | report.close() |
|
179 | 179 | input("Hit <Enter> to quit (your terminal may close):") |
|
180 | 180 | |
|
181 | 181 | def make_report(self,traceback): |
|
182 | 182 | """Return a string containing a crash report.""" |
|
183 | 183 | |
|
184 | 184 | sec_sep = self.section_sep |
|
185 | 185 | |
|
186 | 186 | report = ['*'*75+'\n\n'+'IPython post-mortem report\n\n'] |
|
187 | 187 | rpt_add = report.append |
|
188 | 188 | rpt_add(sys_info()) |
|
189 | 189 | |
|
190 | 190 | try: |
|
191 | 191 | config = pformat(self.app.config) |
|
192 | 192 | rpt_add(sec_sep) |
|
193 | 193 | rpt_add('Application name: %s\n\n' % self.app_name) |
|
194 | 194 | rpt_add('Current user configuration structure:\n\n') |
|
195 | 195 | rpt_add(config) |
|
196 | 196 | except: |
|
197 | 197 | pass |
|
198 | 198 | rpt_add(sec_sep+'Crash traceback:\n\n' + traceback) |
|
199 | 199 | |
|
200 | 200 | return ''.join(report) |
|
201 | 201 | |
|
202 | 202 | |
|
203 | 203 | def crash_handler_lite(etype, evalue, tb): |
|
204 | 204 | """a light excepthook, adding a small message to the usual traceback""" |
|
205 | 205 | traceback.print_exception(etype, evalue, tb) |
|
206 | 206 | |
|
207 | 207 | from IPython.core.interactiveshell import InteractiveShell |
|
208 | 208 | if InteractiveShell.initialized(): |
|
209 | 209 | # we are in a Shell environment, give %magic example |
|
210 | 210 | config = "%config " |
|
211 | 211 | else: |
|
212 | 212 | # we are not in a shell, show generic config |
|
213 | 213 | config = "c." |
|
214 | 214 | print(_lite_message_template.format(email=author_email, config=config), file=sys.stderr) |
|
215 | 215 |
@@ -1,1136 +1,1135 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 | |
|
8 | 8 | try: |
|
9 | 9 | from base64 import encodebytes as base64_encode |
|
10 | 10 | except ImportError: |
|
11 | 11 | from base64 import encodestring as base64_encode |
|
12 | 12 | |
|
13 | 13 | from binascii import b2a_hex |
|
14 | 14 | import json |
|
15 | 15 | import mimetypes |
|
16 | 16 | import os |
|
17 | 17 | import struct |
|
18 | 18 | import sys |
|
19 | 19 | import warnings |
|
20 | 20 | |
|
21 |
from IPython.utils.py3compat import |
|
|
22 | unicode_type) | |
|
21 | from IPython.utils.py3compat import cast_bytes_py2, cast_unicode | |
|
23 | 22 | from IPython.testing.skipdoctest import skip_doctest |
|
24 | 23 | |
|
25 | 24 | __all__ = ['display', 'display_pretty', 'display_html', 'display_markdown', |
|
26 | 25 | 'display_svg', 'display_png', 'display_jpeg', 'display_latex', 'display_json', |
|
27 | 26 | 'display_javascript', 'display_pdf', 'DisplayObject', 'TextDisplayObject', |
|
28 | 27 | 'Pretty', 'HTML', 'Markdown', 'Math', 'Latex', 'SVG', 'JSON', 'Javascript', |
|
29 | 28 | 'Image', 'clear_output', 'set_matplotlib_formats', 'set_matplotlib_close', |
|
30 | 29 | 'publish_display_data', 'update_display', 'DisplayHandle'] |
|
31 | 30 | |
|
32 | 31 | #----------------------------------------------------------------------------- |
|
33 | 32 | # utility functions |
|
34 | 33 | #----------------------------------------------------------------------------- |
|
35 | 34 | |
|
36 | 35 | def _safe_exists(path): |
|
37 | 36 | """Check path, but don't let exceptions raise""" |
|
38 | 37 | try: |
|
39 | 38 | return os.path.exists(path) |
|
40 | 39 | except Exception: |
|
41 | 40 | return False |
|
42 | 41 | |
|
43 | 42 | def _merge(d1, d2): |
|
44 | 43 | """Like update, but merges sub-dicts instead of clobbering at the top level. |
|
45 | 44 | |
|
46 | 45 | Updates d1 in-place |
|
47 | 46 | """ |
|
48 | 47 | |
|
49 | 48 | if not isinstance(d2, dict) or not isinstance(d1, dict): |
|
50 | 49 | return d2 |
|
51 | 50 | for key, value in d2.items(): |
|
52 | 51 | d1[key] = _merge(d1.get(key), value) |
|
53 | 52 | return d1 |
|
54 | 53 | |
|
55 | 54 | def _display_mimetype(mimetype, objs, raw=False, metadata=None): |
|
56 | 55 | """internal implementation of all display_foo methods |
|
57 | 56 | |
|
58 | 57 | Parameters |
|
59 | 58 | ---------- |
|
60 | 59 | mimetype : str |
|
61 | 60 | The mimetype to be published (e.g. 'image/png') |
|
62 | 61 | objs : tuple of objects |
|
63 | 62 | The Python objects to display, or if raw=True raw text data to |
|
64 | 63 | display. |
|
65 | 64 | raw : bool |
|
66 | 65 | Are the data objects raw data or Python objects that need to be |
|
67 | 66 | formatted before display? [default: False] |
|
68 | 67 | metadata : dict (optional) |
|
69 | 68 | Metadata to be associated with the specific mimetype output. |
|
70 | 69 | """ |
|
71 | 70 | if metadata: |
|
72 | 71 | metadata = {mimetype: metadata} |
|
73 | 72 | if raw: |
|
74 | 73 | # turn list of pngdata into list of { 'image/png': pngdata } |
|
75 | 74 | objs = [ {mimetype: obj} for obj in objs ] |
|
76 | 75 | display(*objs, raw=raw, metadata=metadata, include=[mimetype]) |
|
77 | 76 | |
|
78 | 77 | #----------------------------------------------------------------------------- |
|
79 | 78 | # Main functions |
|
80 | 79 | #----------------------------------------------------------------------------- |
|
81 | 80 | |
|
82 | 81 | # use * to indicate transient is keyword-only |
|
83 | 82 | def publish_display_data(data, metadata=None, source=None, *, transient=None, **kwargs): |
|
84 | 83 | """Publish data and metadata to all frontends. |
|
85 | 84 | |
|
86 | 85 | See the ``display_data`` message in the messaging documentation for |
|
87 | 86 | more details about this message type. |
|
88 | 87 | |
|
89 | 88 | The following MIME types are currently implemented: |
|
90 | 89 | |
|
91 | 90 | * text/plain |
|
92 | 91 | * text/html |
|
93 | 92 | * text/markdown |
|
94 | 93 | * text/latex |
|
95 | 94 | * application/json |
|
96 | 95 | * application/javascript |
|
97 | 96 | * image/png |
|
98 | 97 | * image/jpeg |
|
99 | 98 | * image/svg+xml |
|
100 | 99 | |
|
101 | 100 | Parameters |
|
102 | 101 | ---------- |
|
103 | 102 | data : dict |
|
104 | 103 | A dictionary having keys that are valid MIME types (like |
|
105 | 104 | 'text/plain' or 'image/svg+xml') and values that are the data for |
|
106 | 105 | that MIME type. The data itself must be a JSON'able data |
|
107 | 106 | structure. Minimally all data should have the 'text/plain' data, |
|
108 | 107 | which can be displayed by all frontends. If more than the plain |
|
109 | 108 | text is given, it is up to the frontend to decide which |
|
110 | 109 | representation to use. |
|
111 | 110 | metadata : dict |
|
112 | 111 | A dictionary for metadata related to the data. This can contain |
|
113 | 112 | arbitrary key, value pairs that frontends can use to interpret |
|
114 | 113 | the data. mime-type keys matching those in data can be used |
|
115 | 114 | to specify metadata about particular representations. |
|
116 | 115 | source : str, deprecated |
|
117 | 116 | Unused. |
|
118 | 117 | transient : dict, keyword-only |
|
119 | 118 | A dictionary of transient data, such as display_id. |
|
120 | 119 | """ |
|
121 | 120 | from IPython.core.interactiveshell import InteractiveShell |
|
122 | 121 | |
|
123 | 122 | display_pub = InteractiveShell.instance().display_pub |
|
124 | 123 | |
|
125 | 124 | # only pass transient if supplied, |
|
126 | 125 | # to avoid errors with older ipykernel. |
|
127 | 126 | # TODO: We could check for ipykernel version and provide a detailed upgrade message. |
|
128 | 127 | if transient: |
|
129 | 128 | kwargs['transient'] = transient |
|
130 | 129 | |
|
131 | 130 | display_pub.publish( |
|
132 | 131 | data=data, |
|
133 | 132 | metadata=metadata, |
|
134 | 133 | **kwargs |
|
135 | 134 | ) |
|
136 | 135 | |
|
137 | 136 | |
|
138 | 137 | def _new_id(): |
|
139 | 138 | """Generate a new random text id with urandom""" |
|
140 | 139 | return b2a_hex(os.urandom(16)).decode('ascii') |
|
141 | 140 | |
|
142 | 141 | |
|
143 | 142 | def display(*objs, include=None, exclude=None, metadata=None, transient=None, display_id=None, **kwargs): |
|
144 | 143 | """Display a Python object in all frontends. |
|
145 | 144 | |
|
146 | 145 | By default all representations will be computed and sent to the frontends. |
|
147 | 146 | Frontends can decide which representation is used and how. |
|
148 | 147 | |
|
149 | 148 | Parameters |
|
150 | 149 | ---------- |
|
151 | 150 | objs : tuple of objects |
|
152 | 151 | The Python objects to display. |
|
153 | 152 | raw : bool, optional |
|
154 | 153 | Are the objects to be displayed already mimetype-keyed dicts of raw display data, |
|
155 | 154 | or Python objects that need to be formatted before display? [default: False] |
|
156 | 155 | include : list or tuple, optional |
|
157 | 156 | A list of format type strings (MIME types) to include in the |
|
158 | 157 | format data dict. If this is set *only* the format types included |
|
159 | 158 | in this list will be computed. |
|
160 | 159 | exclude : list or tuple, optional |
|
161 | 160 | A list of format type strings (MIME types) to exclude in the format |
|
162 | 161 | data dict. If this is set all format types will be computed, |
|
163 | 162 | except for those included in this argument. |
|
164 | 163 | metadata : dict, optional |
|
165 | 164 | A dictionary of metadata to associate with the output. |
|
166 | 165 | mime-type keys in this dictionary will be associated with the individual |
|
167 | 166 | representation formats, if they exist. |
|
168 | 167 | transient : dict, optional |
|
169 | 168 | A dictionary of transient data to associate with the output. |
|
170 | 169 | Data in this dict should not be persisted to files (e.g. notebooks). |
|
171 | 170 | display_id : str, optional |
|
172 | 171 | Set an id for the display. |
|
173 | 172 | This id can be used for updating this display area later via update_display. |
|
174 | 173 | If given as True, generate a new display_id |
|
175 | 174 | kwargs: additional keyword-args, optional |
|
176 | 175 | Additional keyword-arguments are passed through to the display publisher. |
|
177 | 176 | |
|
178 | 177 | Returns |
|
179 | 178 | ------- |
|
180 | 179 | |
|
181 | 180 | handle: DisplayHandle |
|
182 | 181 | Returns a handle on updatable displays, if display_id is given. |
|
183 | 182 | Returns None if no display_id is given (default). |
|
184 | 183 | """ |
|
185 | 184 | raw = kwargs.pop('raw', False) |
|
186 | 185 | if transient is None: |
|
187 | 186 | transient = {} |
|
188 | 187 | if display_id: |
|
189 | 188 | if display_id == True: |
|
190 | 189 | display_id = _new_id() |
|
191 | 190 | transient['display_id'] = display_id |
|
192 | 191 | if kwargs.get('update') and 'display_id' not in transient: |
|
193 | 192 | raise TypeError('display_id required for update_display') |
|
194 | 193 | if transient: |
|
195 | 194 | kwargs['transient'] = transient |
|
196 | 195 | |
|
197 | 196 | from IPython.core.interactiveshell import InteractiveShell |
|
198 | 197 | |
|
199 | 198 | if not raw: |
|
200 | 199 | format = InteractiveShell.instance().display_formatter.format |
|
201 | 200 | |
|
202 | 201 | for obj in objs: |
|
203 | 202 | if raw: |
|
204 | 203 | publish_display_data(data=obj, metadata=metadata, **kwargs) |
|
205 | 204 | else: |
|
206 | 205 | format_dict, md_dict = format(obj, include=include, exclude=exclude) |
|
207 | 206 | if not format_dict: |
|
208 | 207 | # nothing to display (e.g. _ipython_display_ took over) |
|
209 | 208 | continue |
|
210 | 209 | if metadata: |
|
211 | 210 | # kwarg-specified metadata gets precedence |
|
212 | 211 | _merge(md_dict, metadata) |
|
213 | 212 | publish_display_data(data=format_dict, metadata=md_dict, **kwargs) |
|
214 | 213 | if display_id: |
|
215 | 214 | return DisplayHandle(display_id) |
|
216 | 215 | |
|
217 | 216 | |
|
218 | 217 | # use * for keyword-only display_id arg |
|
219 | 218 | def update_display(obj, *, display_id, **kwargs): |
|
220 | 219 | """Update an existing display by id |
|
221 | 220 | |
|
222 | 221 | Parameters |
|
223 | 222 | ---------- |
|
224 | 223 | |
|
225 | 224 | obj: |
|
226 | 225 | The object with which to update the display |
|
227 | 226 | display_id: keyword-only |
|
228 | 227 | The id of the display to update |
|
229 | 228 | """ |
|
230 | 229 | kwargs['update'] = True |
|
231 | 230 | display(obj, display_id=display_id, **kwargs) |
|
232 | 231 | |
|
233 | 232 | |
|
234 | 233 | class DisplayHandle(object): |
|
235 | 234 | """A handle on an updatable display |
|
236 | 235 | |
|
237 | 236 | Call .update(obj) to display a new object. |
|
238 | 237 | |
|
239 | 238 | Call .display(obj) to add a new instance of this display, |
|
240 | 239 | and update existing instances. |
|
241 | 240 | """ |
|
242 | 241 | |
|
243 | 242 | def __init__(self, display_id=None): |
|
244 | 243 | if display_id is None: |
|
245 | 244 | display_id = _new_id() |
|
246 | 245 | self.display_id = display_id |
|
247 | 246 | |
|
248 | 247 | def __repr__(self): |
|
249 | 248 | return "<%s display_id=%s>" % (self.__class__.__name__, self.display_id) |
|
250 | 249 | |
|
251 | 250 | def display(self, obj, **kwargs): |
|
252 | 251 | """Make a new display with my id, updating existing instances. |
|
253 | 252 | |
|
254 | 253 | Parameters |
|
255 | 254 | ---------- |
|
256 | 255 | |
|
257 | 256 | obj: |
|
258 | 257 | object to display |
|
259 | 258 | **kwargs: |
|
260 | 259 | additional keyword arguments passed to display |
|
261 | 260 | """ |
|
262 | 261 | display(obj, display_id=self.display_id, **kwargs) |
|
263 | 262 | |
|
264 | 263 | def update(self, obj, **kwargs): |
|
265 | 264 | """Update existing displays with my id |
|
266 | 265 | |
|
267 | 266 | Parameters |
|
268 | 267 | ---------- |
|
269 | 268 | |
|
270 | 269 | obj: |
|
271 | 270 | object to display |
|
272 | 271 | **kwargs: |
|
273 | 272 | additional keyword arguments passed to update_display |
|
274 | 273 | """ |
|
275 | 274 | update_display(obj, display_id=self.display_id, **kwargs) |
|
276 | 275 | |
|
277 | 276 | |
|
278 | 277 | def display_pretty(*objs, **kwargs): |
|
279 | 278 | """Display the pretty (default) representation of an object. |
|
280 | 279 | |
|
281 | 280 | Parameters |
|
282 | 281 | ---------- |
|
283 | 282 | objs : tuple of objects |
|
284 | 283 | The Python objects to display, or if raw=True raw text data to |
|
285 | 284 | display. |
|
286 | 285 | raw : bool |
|
287 | 286 | Are the data objects raw data or Python objects that need to be |
|
288 | 287 | formatted before display? [default: False] |
|
289 | 288 | metadata : dict (optional) |
|
290 | 289 | Metadata to be associated with the specific mimetype output. |
|
291 | 290 | """ |
|
292 | 291 | _display_mimetype('text/plain', objs, **kwargs) |
|
293 | 292 | |
|
294 | 293 | |
|
295 | 294 | def display_html(*objs, **kwargs): |
|
296 | 295 | """Display the HTML representation of an object. |
|
297 | 296 | |
|
298 | 297 | Note: If raw=False and the object does not have a HTML |
|
299 | 298 | representation, no HTML will be shown. |
|
300 | 299 | |
|
301 | 300 | Parameters |
|
302 | 301 | ---------- |
|
303 | 302 | objs : tuple of objects |
|
304 | 303 | The Python objects to display, or if raw=True raw HTML data to |
|
305 | 304 | display. |
|
306 | 305 | raw : bool |
|
307 | 306 | Are the data objects raw data or Python objects that need to be |
|
308 | 307 | formatted before display? [default: False] |
|
309 | 308 | metadata : dict (optional) |
|
310 | 309 | Metadata to be associated with the specific mimetype output. |
|
311 | 310 | """ |
|
312 | 311 | _display_mimetype('text/html', objs, **kwargs) |
|
313 | 312 | |
|
314 | 313 | |
|
315 | 314 | def display_markdown(*objs, **kwargs): |
|
316 | 315 | """Displays the Markdown representation of an object. |
|
317 | 316 | |
|
318 | 317 | Parameters |
|
319 | 318 | ---------- |
|
320 | 319 | objs : tuple of objects |
|
321 | 320 | The Python objects to display, or if raw=True raw markdown data to |
|
322 | 321 | display. |
|
323 | 322 | raw : bool |
|
324 | 323 | Are the data objects raw data or Python objects that need to be |
|
325 | 324 | formatted before display? [default: False] |
|
326 | 325 | metadata : dict (optional) |
|
327 | 326 | Metadata to be associated with the specific mimetype output. |
|
328 | 327 | """ |
|
329 | 328 | |
|
330 | 329 | _display_mimetype('text/markdown', objs, **kwargs) |
|
331 | 330 | |
|
332 | 331 | |
|
333 | 332 | def display_svg(*objs, **kwargs): |
|
334 | 333 | """Display the SVG representation of an object. |
|
335 | 334 | |
|
336 | 335 | Parameters |
|
337 | 336 | ---------- |
|
338 | 337 | objs : tuple of objects |
|
339 | 338 | The Python objects to display, or if raw=True raw svg data to |
|
340 | 339 | display. |
|
341 | 340 | raw : bool |
|
342 | 341 | Are the data objects raw data or Python objects that need to be |
|
343 | 342 | formatted before display? [default: False] |
|
344 | 343 | metadata : dict (optional) |
|
345 | 344 | Metadata to be associated with the specific mimetype output. |
|
346 | 345 | """ |
|
347 | 346 | _display_mimetype('image/svg+xml', objs, **kwargs) |
|
348 | 347 | |
|
349 | 348 | |
|
350 | 349 | def display_png(*objs, **kwargs): |
|
351 | 350 | """Display the PNG representation of an object. |
|
352 | 351 | |
|
353 | 352 | Parameters |
|
354 | 353 | ---------- |
|
355 | 354 | objs : tuple of objects |
|
356 | 355 | The Python objects to display, or if raw=True raw png data to |
|
357 | 356 | display. |
|
358 | 357 | raw : bool |
|
359 | 358 | Are the data objects raw data or Python objects that need to be |
|
360 | 359 | formatted before display? [default: False] |
|
361 | 360 | metadata : dict (optional) |
|
362 | 361 | Metadata to be associated with the specific mimetype output. |
|
363 | 362 | """ |
|
364 | 363 | _display_mimetype('image/png', objs, **kwargs) |
|
365 | 364 | |
|
366 | 365 | |
|
367 | 366 | def display_jpeg(*objs, **kwargs): |
|
368 | 367 | """Display the JPEG representation of an object. |
|
369 | 368 | |
|
370 | 369 | Parameters |
|
371 | 370 | ---------- |
|
372 | 371 | objs : tuple of objects |
|
373 | 372 | The Python objects to display, or if raw=True raw JPEG data to |
|
374 | 373 | display. |
|
375 | 374 | raw : bool |
|
376 | 375 | Are the data objects raw data or Python objects that need to be |
|
377 | 376 | formatted before display? [default: False] |
|
378 | 377 | metadata : dict (optional) |
|
379 | 378 | Metadata to be associated with the specific mimetype output. |
|
380 | 379 | """ |
|
381 | 380 | _display_mimetype('image/jpeg', objs, **kwargs) |
|
382 | 381 | |
|
383 | 382 | |
|
384 | 383 | def display_latex(*objs, **kwargs): |
|
385 | 384 | """Display the LaTeX representation of an object. |
|
386 | 385 | |
|
387 | 386 | Parameters |
|
388 | 387 | ---------- |
|
389 | 388 | objs : tuple of objects |
|
390 | 389 | The Python objects to display, or if raw=True raw latex data to |
|
391 | 390 | display. |
|
392 | 391 | raw : bool |
|
393 | 392 | Are the data objects raw data or Python objects that need to be |
|
394 | 393 | formatted before display? [default: False] |
|
395 | 394 | metadata : dict (optional) |
|
396 | 395 | Metadata to be associated with the specific mimetype output. |
|
397 | 396 | """ |
|
398 | 397 | _display_mimetype('text/latex', objs, **kwargs) |
|
399 | 398 | |
|
400 | 399 | |
|
401 | 400 | def display_json(*objs, **kwargs): |
|
402 | 401 | """Display the JSON representation of an object. |
|
403 | 402 | |
|
404 | 403 | Note that not many frontends support displaying JSON. |
|
405 | 404 | |
|
406 | 405 | Parameters |
|
407 | 406 | ---------- |
|
408 | 407 | objs : tuple of objects |
|
409 | 408 | The Python objects to display, or if raw=True raw json data to |
|
410 | 409 | display. |
|
411 | 410 | raw : bool |
|
412 | 411 | Are the data objects raw data or Python objects that need to be |
|
413 | 412 | formatted before display? [default: False] |
|
414 | 413 | metadata : dict (optional) |
|
415 | 414 | Metadata to be associated with the specific mimetype output. |
|
416 | 415 | """ |
|
417 | 416 | _display_mimetype('application/json', objs, **kwargs) |
|
418 | 417 | |
|
419 | 418 | |
|
420 | 419 | def display_javascript(*objs, **kwargs): |
|
421 | 420 | """Display the Javascript representation of an object. |
|
422 | 421 | |
|
423 | 422 | Parameters |
|
424 | 423 | ---------- |
|
425 | 424 | objs : tuple of objects |
|
426 | 425 | The Python objects to display, or if raw=True raw javascript data to |
|
427 | 426 | display. |
|
428 | 427 | raw : bool |
|
429 | 428 | Are the data objects raw data or Python objects that need to be |
|
430 | 429 | formatted before display? [default: False] |
|
431 | 430 | metadata : dict (optional) |
|
432 | 431 | Metadata to be associated with the specific mimetype output. |
|
433 | 432 | """ |
|
434 | 433 | _display_mimetype('application/javascript', objs, **kwargs) |
|
435 | 434 | |
|
436 | 435 | |
|
437 | 436 | def display_pdf(*objs, **kwargs): |
|
438 | 437 | """Display the PDF representation of an object. |
|
439 | 438 | |
|
440 | 439 | Parameters |
|
441 | 440 | ---------- |
|
442 | 441 | objs : tuple of objects |
|
443 | 442 | The Python objects to display, or if raw=True raw javascript data to |
|
444 | 443 | display. |
|
445 | 444 | raw : bool |
|
446 | 445 | Are the data objects raw data or Python objects that need to be |
|
447 | 446 | formatted before display? [default: False] |
|
448 | 447 | metadata : dict (optional) |
|
449 | 448 | Metadata to be associated with the specific mimetype output. |
|
450 | 449 | """ |
|
451 | 450 | _display_mimetype('application/pdf', objs, **kwargs) |
|
452 | 451 | |
|
453 | 452 | |
|
454 | 453 | #----------------------------------------------------------------------------- |
|
455 | 454 | # Smart classes |
|
456 | 455 | #----------------------------------------------------------------------------- |
|
457 | 456 | |
|
458 | 457 | |
|
459 | 458 | class DisplayObject(object): |
|
460 | 459 | """An object that wraps data to be displayed.""" |
|
461 | 460 | |
|
462 | 461 | _read_flags = 'r' |
|
463 | 462 | _show_mem_addr = False |
|
464 | 463 | |
|
465 | 464 | def __init__(self, data=None, url=None, filename=None): |
|
466 | 465 | """Create a display object given raw data. |
|
467 | 466 | |
|
468 | 467 | When this object is returned by an expression or passed to the |
|
469 | 468 | display function, it will result in the data being displayed |
|
470 | 469 | in the frontend. The MIME type of the data should match the |
|
471 | 470 | subclasses used, so the Png subclass should be used for 'image/png' |
|
472 | 471 | data. If the data is a URL, the data will first be downloaded |
|
473 | 472 | and then displayed. If |
|
474 | 473 | |
|
475 | 474 | Parameters |
|
476 | 475 | ---------- |
|
477 | 476 | data : unicode, str or bytes |
|
478 | 477 | The raw data or a URL or file to load the data from |
|
479 | 478 | url : unicode |
|
480 | 479 | A URL to download the data from. |
|
481 | 480 | filename : unicode |
|
482 | 481 | Path to a local file to load the data from. |
|
483 | 482 | """ |
|
484 |
if data is not None and isinstance(data, str |
|
|
483 | if data is not None and isinstance(data, str): | |
|
485 | 484 | if data.startswith('http') and url is None: |
|
486 | 485 | url = data |
|
487 | 486 | filename = None |
|
488 | 487 | data = None |
|
489 | 488 | elif _safe_exists(data) and filename is None: |
|
490 | 489 | url = None |
|
491 | 490 | filename = data |
|
492 | 491 | data = None |
|
493 | 492 | |
|
494 | 493 | self.data = data |
|
495 | 494 | self.url = url |
|
496 | self.filename = None if filename is None else unicode_type(filename) | |
|
495 | self.filename = filename | |
|
497 | 496 | |
|
498 | 497 | self.reload() |
|
499 | 498 | self._check_data() |
|
500 | 499 | |
|
501 | 500 | def __repr__(self): |
|
502 | 501 | if not self._show_mem_addr: |
|
503 | 502 | cls = self.__class__ |
|
504 | 503 | r = "<%s.%s object>" % (cls.__module__, cls.__name__) |
|
505 | 504 | else: |
|
506 | 505 | r = super(DisplayObject, self).__repr__() |
|
507 | 506 | return r |
|
508 | 507 | |
|
509 | 508 | def _check_data(self): |
|
510 | 509 | """Override in subclasses if there's something to check.""" |
|
511 | 510 | pass |
|
512 | 511 | |
|
513 | 512 | def reload(self): |
|
514 | 513 | """Reload the raw data from file or URL.""" |
|
515 | 514 | if self.filename is not None: |
|
516 | 515 | with open(self.filename, self._read_flags) as f: |
|
517 | 516 | self.data = f.read() |
|
518 | 517 | elif self.url is not None: |
|
519 | 518 | try: |
|
520 | 519 | try: |
|
521 | 520 | from urllib.request import urlopen # Py3 |
|
522 | 521 | except ImportError: |
|
523 | 522 | from urllib2 import urlopen |
|
524 | 523 | response = urlopen(self.url) |
|
525 | 524 | self.data = response.read() |
|
526 | 525 | # extract encoding from header, if there is one: |
|
527 | 526 | encoding = None |
|
528 | 527 | for sub in response.headers['content-type'].split(';'): |
|
529 | 528 | sub = sub.strip() |
|
530 | 529 | if sub.startswith('charset'): |
|
531 | 530 | encoding = sub.split('=')[-1].strip() |
|
532 | 531 | break |
|
533 | 532 | # decode data, if an encoding was specified |
|
534 | 533 | if encoding: |
|
535 | 534 | self.data = self.data.decode(encoding, 'replace') |
|
536 | 535 | except: |
|
537 | 536 | self.data = None |
|
538 | 537 | |
|
539 | 538 | class TextDisplayObject(DisplayObject): |
|
540 | 539 | """Validate that display data is text""" |
|
541 | 540 | def _check_data(self): |
|
542 |
if self.data is not None and not isinstance(self.data, str |
|
|
541 | if self.data is not None and not isinstance(self.data, str): | |
|
543 | 542 | raise TypeError("%s expects text, not %r" % (self.__class__.__name__, self.data)) |
|
544 | 543 | |
|
545 | 544 | class Pretty(TextDisplayObject): |
|
546 | 545 | |
|
547 | 546 | def _repr_pretty_(self): |
|
548 | 547 | return self.data |
|
549 | 548 | |
|
550 | 549 | |
|
551 | 550 | class HTML(TextDisplayObject): |
|
552 | 551 | |
|
553 | 552 | def _repr_html_(self): |
|
554 | 553 | return self.data |
|
555 | 554 | |
|
556 | 555 | def __html__(self): |
|
557 | 556 | """ |
|
558 | 557 | This method exists to inform other HTML-using modules (e.g. Markupsafe, |
|
559 | 558 | htmltag, etc) that this object is HTML and does not need things like |
|
560 | 559 | special characters (<>&) escaped. |
|
561 | 560 | """ |
|
562 | 561 | return self._repr_html_() |
|
563 | 562 | |
|
564 | 563 | |
|
565 | 564 | class Markdown(TextDisplayObject): |
|
566 | 565 | |
|
567 | 566 | def _repr_markdown_(self): |
|
568 | 567 | return self.data |
|
569 | 568 | |
|
570 | 569 | |
|
571 | 570 | class Math(TextDisplayObject): |
|
572 | 571 | |
|
573 | 572 | def _repr_latex_(self): |
|
574 | 573 | s = self.data.strip('$') |
|
575 | 574 | return "$$%s$$" % s |
|
576 | 575 | |
|
577 | 576 | |
|
578 | 577 | class Latex(TextDisplayObject): |
|
579 | 578 | |
|
580 | 579 | def _repr_latex_(self): |
|
581 | 580 | return self.data |
|
582 | 581 | |
|
583 | 582 | |
|
584 | 583 | class SVG(DisplayObject): |
|
585 | 584 | |
|
586 | 585 | _read_flags = 'rb' |
|
587 | 586 | # wrap data in a property, which extracts the <svg> tag, discarding |
|
588 | 587 | # document headers |
|
589 | 588 | _data = None |
|
590 | 589 | |
|
591 | 590 | @property |
|
592 | 591 | def data(self): |
|
593 | 592 | return self._data |
|
594 | 593 | |
|
595 | 594 | @data.setter |
|
596 | 595 | def data(self, svg): |
|
597 | 596 | if svg is None: |
|
598 | 597 | self._data = None |
|
599 | 598 | return |
|
600 | 599 | # parse into dom object |
|
601 | 600 | from xml.dom import minidom |
|
602 | 601 | svg = cast_bytes_py2(svg) |
|
603 | 602 | x = minidom.parseString(svg) |
|
604 | 603 | # get svg tag (should be 1) |
|
605 | 604 | found_svg = x.getElementsByTagName('svg') |
|
606 | 605 | if found_svg: |
|
607 | 606 | svg = found_svg[0].toxml() |
|
608 | 607 | else: |
|
609 | 608 | # fallback on the input, trust the user |
|
610 | 609 | # but this is probably an error. |
|
611 | 610 | pass |
|
612 | 611 | svg = cast_unicode(svg) |
|
613 | 612 | self._data = svg |
|
614 | 613 | |
|
615 | 614 | def _repr_svg_(self): |
|
616 | 615 | return self.data |
|
617 | 616 | |
|
618 | 617 | |
|
619 | 618 | class JSON(DisplayObject): |
|
620 | 619 | """JSON expects a JSON-able dict or list |
|
621 | 620 | |
|
622 | 621 | not an already-serialized JSON string. |
|
623 | 622 | |
|
624 | 623 | Scalar types (None, number, string) are not allowed, only dict or list containers. |
|
625 | 624 | """ |
|
626 | 625 | # wrap data in a property, which warns about passing already-serialized JSON |
|
627 | 626 | _data = None |
|
628 | 627 | def __init__(self, data=None, url=None, filename=None, expanded=False, metadata=None): |
|
629 | 628 | """Create a JSON display object given raw data. |
|
630 | 629 | |
|
631 | 630 | Parameters |
|
632 | 631 | ---------- |
|
633 | 632 | data : dict or list |
|
634 | 633 | JSON data to display. Not an already-serialized JSON string. |
|
635 | 634 | Scalar types (None, number, string) are not allowed, only dict |
|
636 | 635 | or list containers. |
|
637 | 636 | url : unicode |
|
638 | 637 | A URL to download the data from. |
|
639 | 638 | filename : unicode |
|
640 | 639 | Path to a local file to load the data from. |
|
641 | 640 | expanded : boolean |
|
642 | 641 | Metadata to control whether a JSON display component is expanded. |
|
643 | 642 | metadata: dict |
|
644 | 643 | Specify extra metadata to attach to the json display object. |
|
645 | 644 | """ |
|
646 | 645 | self.expanded = expanded |
|
647 | 646 | self.metadata = metadata |
|
648 | 647 | super(JSON, self).__init__(data=data, url=url, filename=filename) |
|
649 | 648 | |
|
650 | 649 | def _check_data(self): |
|
651 | 650 | if self.data is not None and not isinstance(self.data, (dict, list)): |
|
652 | 651 | raise TypeError("%s expects JSONable dict or list, not %r" % (self.__class__.__name__, self.data)) |
|
653 | 652 | |
|
654 | 653 | @property |
|
655 | 654 | def data(self): |
|
656 | 655 | return self._data |
|
657 | 656 | |
|
658 | 657 | @data.setter |
|
659 | 658 | def data(self, data): |
|
660 |
if isinstance(data, str |
|
|
659 | if isinstance(data, str): | |
|
661 | 660 | warnings.warn("JSON expects JSONable dict or list, not JSON strings") |
|
662 | 661 | data = json.loads(data) |
|
663 | 662 | self._data = data |
|
664 | 663 | |
|
665 | 664 | def _data_and_metadata(self): |
|
666 | 665 | md = {'expanded': self.expanded} |
|
667 | 666 | if self.metadata: |
|
668 | 667 | md.update(self.metadata) |
|
669 | 668 | return self.data, md |
|
670 | 669 | |
|
671 | 670 | def _repr_json_(self): |
|
672 | 671 | return self._data_and_metadata() |
|
673 | 672 | |
|
674 | 673 | css_t = """$("head").append($("<link/>").attr({ |
|
675 | 674 | rel: "stylesheet", |
|
676 | 675 | type: "text/css", |
|
677 | 676 | href: "%s" |
|
678 | 677 | })); |
|
679 | 678 | """ |
|
680 | 679 | |
|
681 | 680 | lib_t1 = """$.getScript("%s", function () { |
|
682 | 681 | """ |
|
683 | 682 | lib_t2 = """}); |
|
684 | 683 | """ |
|
685 | 684 | |
|
686 | 685 | class Javascript(TextDisplayObject): |
|
687 | 686 | |
|
688 | 687 | def __init__(self, data=None, url=None, filename=None, lib=None, css=None): |
|
689 | 688 | """Create a Javascript display object given raw data. |
|
690 | 689 | |
|
691 | 690 | When this object is returned by an expression or passed to the |
|
692 | 691 | display function, it will result in the data being displayed |
|
693 | 692 | in the frontend. If the data is a URL, the data will first be |
|
694 | 693 | downloaded and then displayed. |
|
695 | 694 | |
|
696 | 695 | In the Notebook, the containing element will be available as `element`, |
|
697 | 696 | and jQuery will be available. Content appended to `element` will be |
|
698 | 697 | visible in the output area. |
|
699 | 698 | |
|
700 | 699 | Parameters |
|
701 | 700 | ---------- |
|
702 | 701 | data : unicode, str or bytes |
|
703 | 702 | The Javascript source code or a URL to download it from. |
|
704 | 703 | url : unicode |
|
705 | 704 | A URL to download the data from. |
|
706 | 705 | filename : unicode |
|
707 | 706 | Path to a local file to load the data from. |
|
708 | 707 | lib : list or str |
|
709 | 708 | A sequence of Javascript library URLs to load asynchronously before |
|
710 | 709 | running the source code. The full URLs of the libraries should |
|
711 | 710 | be given. A single Javascript library URL can also be given as a |
|
712 | 711 | string. |
|
713 | 712 | css: : list or str |
|
714 | 713 | A sequence of css files to load before running the source code. |
|
715 | 714 | The full URLs of the css files should be given. A single css URL |
|
716 | 715 | can also be given as a string. |
|
717 | 716 | """ |
|
718 |
if isinstance(lib, str |
|
|
717 | if isinstance(lib, str): | |
|
719 | 718 | lib = [lib] |
|
720 | 719 | elif lib is None: |
|
721 | 720 | lib = [] |
|
722 |
if isinstance(css, str |
|
|
721 | if isinstance(css, str): | |
|
723 | 722 | css = [css] |
|
724 | 723 | elif css is None: |
|
725 | 724 | css = [] |
|
726 | 725 | if not isinstance(lib, (list,tuple)): |
|
727 | 726 | raise TypeError('expected sequence, got: %r' % lib) |
|
728 | 727 | if not isinstance(css, (list,tuple)): |
|
729 | 728 | raise TypeError('expected sequence, got: %r' % css) |
|
730 | 729 | self.lib = lib |
|
731 | 730 | self.css = css |
|
732 | 731 | super(Javascript, self).__init__(data=data, url=url, filename=filename) |
|
733 | 732 | |
|
734 | 733 | def _repr_javascript_(self): |
|
735 | 734 | r = '' |
|
736 | 735 | for c in self.css: |
|
737 | 736 | r += css_t % c |
|
738 | 737 | for l in self.lib: |
|
739 | 738 | r += lib_t1 % l |
|
740 | 739 | r += self.data |
|
741 | 740 | r += lib_t2*len(self.lib) |
|
742 | 741 | return r |
|
743 | 742 | |
|
744 | 743 | # constants for identifying png/jpeg data |
|
745 | 744 | _PNG = b'\x89PNG\r\n\x1a\n' |
|
746 | 745 | _JPEG = b'\xff\xd8' |
|
747 | 746 | |
|
748 | 747 | def _pngxy(data): |
|
749 | 748 | """read the (width, height) from a PNG header""" |
|
750 | 749 | ihdr = data.index(b'IHDR') |
|
751 | 750 | # next 8 bytes are width/height |
|
752 | 751 | w4h4 = data[ihdr+4:ihdr+12] |
|
753 | 752 | return struct.unpack('>ii', w4h4) |
|
754 | 753 | |
|
755 | 754 | def _jpegxy(data): |
|
756 | 755 | """read the (width, height) from a JPEG header""" |
|
757 | 756 | # adapted from http://www.64lines.com/jpeg-width-height |
|
758 | 757 | |
|
759 | 758 | idx = 4 |
|
760 | 759 | while True: |
|
761 | 760 | block_size = struct.unpack('>H', data[idx:idx+2])[0] |
|
762 | 761 | idx = idx + block_size |
|
763 | 762 | if data[idx:idx+2] == b'\xFF\xC0': |
|
764 | 763 | # found Start of Frame |
|
765 | 764 | iSOF = idx |
|
766 | 765 | break |
|
767 | 766 | else: |
|
768 | 767 | # read another block |
|
769 | 768 | idx += 2 |
|
770 | 769 | |
|
771 | 770 | h, w = struct.unpack('>HH', data[iSOF+5:iSOF+9]) |
|
772 | 771 | return w, h |
|
773 | 772 | |
|
774 | 773 | class Image(DisplayObject): |
|
775 | 774 | |
|
776 | 775 | _read_flags = 'rb' |
|
777 | 776 | _FMT_JPEG = u'jpeg' |
|
778 | 777 | _FMT_PNG = u'png' |
|
779 | 778 | _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG] |
|
780 | 779 | |
|
781 | 780 | def __init__(self, data=None, url=None, filename=None, format=None, |
|
782 | 781 | embed=None, width=None, height=None, retina=False, |
|
783 | 782 | unconfined=False, metadata=None): |
|
784 | 783 | """Create a PNG/JPEG image object given raw data. |
|
785 | 784 | |
|
786 | 785 | When this object is returned by an input cell or passed to the |
|
787 | 786 | display function, it will result in the image being displayed |
|
788 | 787 | in the frontend. |
|
789 | 788 | |
|
790 | 789 | Parameters |
|
791 | 790 | ---------- |
|
792 | 791 | data : unicode, str or bytes |
|
793 | 792 | The raw image data or a URL or filename to load the data from. |
|
794 | 793 | This always results in embedded image data. |
|
795 | 794 | url : unicode |
|
796 | 795 | A URL to download the data from. If you specify `url=`, |
|
797 | 796 | the image data will not be embedded unless you also specify `embed=True`. |
|
798 | 797 | filename : unicode |
|
799 | 798 | Path to a local file to load the data from. |
|
800 | 799 | Images from a file are always embedded. |
|
801 | 800 | format : unicode |
|
802 | 801 | The format of the image data (png/jpeg/jpg). If a filename or URL is given |
|
803 | 802 | for format will be inferred from the filename extension. |
|
804 | 803 | embed : bool |
|
805 | 804 | Should the image data be embedded using a data URI (True) or be |
|
806 | 805 | loaded using an <img> tag. Set this to True if you want the image |
|
807 | 806 | to be viewable later with no internet connection in the notebook. |
|
808 | 807 | |
|
809 | 808 | Default is `True`, unless the keyword argument `url` is set, then |
|
810 | 809 | default value is `False`. |
|
811 | 810 | |
|
812 | 811 | Note that QtConsole is not able to display images if `embed` is set to `False` |
|
813 | 812 | width : int |
|
814 | 813 | Width in pixels to which to constrain the image in html |
|
815 | 814 | height : int |
|
816 | 815 | Height in pixels to which to constrain the image in html |
|
817 | 816 | retina : bool |
|
818 | 817 | Automatically set the width and height to half of the measured |
|
819 | 818 | width and height. |
|
820 | 819 | This only works for embedded images because it reads the width/height |
|
821 | 820 | from image data. |
|
822 | 821 | For non-embedded images, you can just set the desired display width |
|
823 | 822 | and height directly. |
|
824 | 823 | unconfined: bool |
|
825 | 824 | Set unconfined=True to disable max-width confinement of the image. |
|
826 | 825 | metadata: dict |
|
827 | 826 | Specify extra metadata to attach to the image. |
|
828 | 827 | |
|
829 | 828 | Examples |
|
830 | 829 | -------- |
|
831 | 830 | # embedded image data, works in qtconsole and notebook |
|
832 | 831 | # when passed positionally, the first arg can be any of raw image data, |
|
833 | 832 | # a URL, or a filename from which to load image data. |
|
834 | 833 | # The result is always embedding image data for inline images. |
|
835 | 834 | Image('http://www.google.fr/images/srpr/logo3w.png') |
|
836 | 835 | Image('/path/to/image.jpg') |
|
837 | 836 | Image(b'RAW_PNG_DATA...') |
|
838 | 837 | |
|
839 | 838 | # Specifying Image(url=...) does not embed the image data, |
|
840 | 839 | # it only generates `<img>` tag with a link to the source. |
|
841 | 840 | # This will not work in the qtconsole or offline. |
|
842 | 841 | Image(url='http://www.google.fr/images/srpr/logo3w.png') |
|
843 | 842 | |
|
844 | 843 | """ |
|
845 | 844 | if filename is not None: |
|
846 | 845 | ext = self._find_ext(filename) |
|
847 | 846 | elif url is not None: |
|
848 | 847 | ext = self._find_ext(url) |
|
849 | 848 | elif data is None: |
|
850 | 849 | raise ValueError("No image data found. Expecting filename, url, or data.") |
|
851 |
elif isinstance(data, str |
|
|
850 | elif isinstance(data, str) and ( | |
|
852 | 851 | data.startswith('http') or _safe_exists(data) |
|
853 | 852 | ): |
|
854 | 853 | ext = self._find_ext(data) |
|
855 | 854 | else: |
|
856 | 855 | ext = None |
|
857 | 856 | |
|
858 | 857 | if format is None: |
|
859 | 858 | if ext is not None: |
|
860 | 859 | if ext == u'jpg' or ext == u'jpeg': |
|
861 | 860 | format = self._FMT_JPEG |
|
862 | 861 | if ext == u'png': |
|
863 | 862 | format = self._FMT_PNG |
|
864 | 863 | else: |
|
865 | 864 | format = ext.lower() |
|
866 | 865 | elif isinstance(data, bytes): |
|
867 | 866 | # infer image type from image data header, |
|
868 | 867 | # only if format has not been specified. |
|
869 | 868 | if data[:2] == _JPEG: |
|
870 | 869 | format = self._FMT_JPEG |
|
871 | 870 | |
|
872 | 871 | # failed to detect format, default png |
|
873 | 872 | if format is None: |
|
874 | 873 | format = 'png' |
|
875 | 874 | |
|
876 | 875 | if format.lower() == 'jpg': |
|
877 | 876 | # jpg->jpeg |
|
878 | 877 | format = self._FMT_JPEG |
|
879 | 878 | |
|
880 |
self.format = |
|
|
879 | self.format = format.lower() | |
|
881 | 880 | self.embed = embed if embed is not None else (url is None) |
|
882 | 881 | |
|
883 | 882 | if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS: |
|
884 | 883 | raise ValueError("Cannot embed the '%s' image format" % (self.format)) |
|
885 | 884 | self.width = width |
|
886 | 885 | self.height = height |
|
887 | 886 | self.retina = retina |
|
888 | 887 | self.unconfined = unconfined |
|
889 | 888 | self.metadata = metadata |
|
890 | 889 | super(Image, self).__init__(data=data, url=url, filename=filename) |
|
891 | 890 | |
|
892 | 891 | if retina: |
|
893 | 892 | self._retina_shape() |
|
894 | 893 | |
|
895 | 894 | def _retina_shape(self): |
|
896 | 895 | """load pixel-doubled width and height from image data""" |
|
897 | 896 | if not self.embed: |
|
898 | 897 | return |
|
899 | 898 | if self.format == 'png': |
|
900 | 899 | w, h = _pngxy(self.data) |
|
901 | 900 | elif self.format == 'jpeg': |
|
902 | 901 | w, h = _jpegxy(self.data) |
|
903 | 902 | else: |
|
904 | 903 | # retina only supports png |
|
905 | 904 | return |
|
906 | 905 | self.width = w // 2 |
|
907 | 906 | self.height = h // 2 |
|
908 | 907 | |
|
909 | 908 | def reload(self): |
|
910 | 909 | """Reload the raw data from file or URL.""" |
|
911 | 910 | if self.embed: |
|
912 | 911 | super(Image,self).reload() |
|
913 | 912 | if self.retina: |
|
914 | 913 | self._retina_shape() |
|
915 | 914 | |
|
916 | 915 | def _repr_html_(self): |
|
917 | 916 | if not self.embed: |
|
918 | 917 | width = height = klass = '' |
|
919 | 918 | if self.width: |
|
920 | 919 | width = ' width="%d"' % self.width |
|
921 | 920 | if self.height: |
|
922 | 921 | height = ' height="%d"' % self.height |
|
923 | 922 | if self.unconfined: |
|
924 | 923 | klass = ' class="unconfined"' |
|
925 | 924 | return u'<img src="{url}"{width}{height}{klass}/>'.format( |
|
926 | 925 | url=self.url, |
|
927 | 926 | width=width, |
|
928 | 927 | height=height, |
|
929 | 928 | klass=klass, |
|
930 | 929 | ) |
|
931 | 930 | |
|
932 | 931 | def _data_and_metadata(self): |
|
933 | 932 | """shortcut for returning metadata with shape information, if defined""" |
|
934 | 933 | md = {} |
|
935 | 934 | if self.width: |
|
936 | 935 | md['width'] = self.width |
|
937 | 936 | if self.height: |
|
938 | 937 | md['height'] = self.height |
|
939 | 938 | if self.unconfined: |
|
940 | 939 | md['unconfined'] = self.unconfined |
|
941 | 940 | if self.metadata: |
|
942 | 941 | md.update(self.metadata) |
|
943 | 942 | if md: |
|
944 | 943 | return self.data, md |
|
945 | 944 | else: |
|
946 | 945 | return self.data |
|
947 | 946 | |
|
948 | 947 | def _repr_png_(self): |
|
949 | 948 | if self.embed and self.format == u'png': |
|
950 | 949 | return self._data_and_metadata() |
|
951 | 950 | |
|
952 | 951 | def _repr_jpeg_(self): |
|
953 | 952 | if self.embed and (self.format == u'jpeg' or self.format == u'jpg'): |
|
954 | 953 | return self._data_and_metadata() |
|
955 | 954 | |
|
956 | 955 | def _find_ext(self, s): |
|
957 |
return |
|
|
956 | return s.split('.')[-1].lower() | |
|
958 | 957 | |
|
959 | 958 | class Video(DisplayObject): |
|
960 | 959 | |
|
961 | 960 | def __init__(self, data=None, url=None, filename=None, embed=False, mimetype=None): |
|
962 | 961 | """Create a video object given raw data or an URL. |
|
963 | 962 | |
|
964 | 963 | When this object is returned by an input cell or passed to the |
|
965 | 964 | display function, it will result in the video being displayed |
|
966 | 965 | in the frontend. |
|
967 | 966 | |
|
968 | 967 | Parameters |
|
969 | 968 | ---------- |
|
970 | 969 | data : unicode, str or bytes |
|
971 | 970 | The raw video data or a URL or filename to load the data from. |
|
972 | 971 | Raw data will require passing `embed=True`. |
|
973 | 972 | url : unicode |
|
974 | 973 | A URL for the video. If you specify `url=`, |
|
975 | 974 | the image data will not be embedded. |
|
976 | 975 | filename : unicode |
|
977 | 976 | Path to a local file containing the video. |
|
978 | 977 | Will be interpreted as a local URL unless `embed=True`. |
|
979 | 978 | embed : bool |
|
980 | 979 | Should the video be embedded using a data URI (True) or be |
|
981 | 980 | loaded using a <video> tag (False). |
|
982 | 981 | |
|
983 | 982 | Since videos are large, embedding them should be avoided, if possible. |
|
984 | 983 | You must confirm embedding as your intention by passing `embed=True`. |
|
985 | 984 | |
|
986 | 985 | Local files can be displayed with URLs without embedding the content, via:: |
|
987 | 986 | |
|
988 | 987 | Video('./video.mp4') |
|
989 | 988 | |
|
990 | 989 | mimetype: unicode |
|
991 | 990 | Specify the mimetype for embedded videos. |
|
992 | 991 | Default will be guessed from file extension, if available. |
|
993 | 992 | |
|
994 | 993 | Examples |
|
995 | 994 | -------- |
|
996 | 995 | |
|
997 | 996 | Video('https://archive.org/download/Sita_Sings_the_Blues/Sita_Sings_the_Blues_small.mp4') |
|
998 | 997 | Video('path/to/video.mp4') |
|
999 | 998 | Video('path/to/video.mp4', embed=True) |
|
1000 | 999 | Video(b'raw-videodata', embed=True) |
|
1001 | 1000 | """ |
|
1002 |
if url is None and isinstance(data, str |
|
|
1001 | if url is None and isinstance(data, str) and data.startswith(('http:', 'https:')): | |
|
1003 | 1002 | url = data |
|
1004 | 1003 | data = None |
|
1005 | 1004 | elif os.path.exists(data): |
|
1006 | 1005 | filename = data |
|
1007 | 1006 | data = None |
|
1008 | 1007 | |
|
1009 | 1008 | if data and not embed: |
|
1010 | 1009 | msg = ''.join([ |
|
1011 | 1010 | "To embed videos, you must pass embed=True ", |
|
1012 | 1011 | "(this may make your notebook files huge)\n", |
|
1013 | 1012 | "Consider passing Video(url='...')", |
|
1014 | 1013 | ]) |
|
1015 | 1014 | raise ValueError(msg) |
|
1016 | 1015 | |
|
1017 | 1016 | self.mimetype = mimetype |
|
1018 | 1017 | self.embed = embed |
|
1019 | 1018 | super(Video, self).__init__(data=data, url=url, filename=filename) |
|
1020 | 1019 | |
|
1021 | 1020 | def _repr_html_(self): |
|
1022 | 1021 | # External URLs and potentially local files are not embedded into the |
|
1023 | 1022 | # notebook output. |
|
1024 | 1023 | if not self.embed: |
|
1025 | 1024 | url = self.url if self.url is not None else self.filename |
|
1026 | 1025 | output = """<video src="{0}" controls> |
|
1027 | 1026 | Your browser does not support the <code>video</code> element. |
|
1028 | 1027 | </video>""".format(url) |
|
1029 | 1028 | return output |
|
1030 | 1029 | |
|
1031 | 1030 | # Embedded videos are base64-encoded. |
|
1032 | 1031 | mimetype = self.mimetype |
|
1033 | 1032 | if self.filename is not None: |
|
1034 | 1033 | if not mimetype: |
|
1035 | 1034 | mimetype, _ = mimetypes.guess_type(self.filename) |
|
1036 | 1035 | |
|
1037 | 1036 | with open(self.filename, 'rb') as f: |
|
1038 | 1037 | video = f.read() |
|
1039 | 1038 | else: |
|
1040 | 1039 | video = self.data |
|
1041 |
if isinstance(video, |
|
|
1040 | if isinstance(video, str): | |
|
1042 | 1041 | # unicode input is already b64-encoded |
|
1043 | 1042 | b64_video = video |
|
1044 | 1043 | else: |
|
1045 | 1044 | b64_video = base64_encode(video).decode('ascii').rstrip() |
|
1046 | 1045 | |
|
1047 | 1046 | output = """<video controls> |
|
1048 | 1047 | <source src="data:{0};base64,{1}" type="{0}"> |
|
1049 | 1048 | Your browser does not support the video tag. |
|
1050 | 1049 | </video>""".format(mimetype, b64_video) |
|
1051 | 1050 | return output |
|
1052 | 1051 | |
|
1053 | 1052 | def reload(self): |
|
1054 | 1053 | # TODO |
|
1055 | 1054 | pass |
|
1056 | 1055 | |
|
1057 | 1056 | def _repr_png_(self): |
|
1058 | 1057 | # TODO |
|
1059 | 1058 | pass |
|
1060 | 1059 | def _repr_jpeg_(self): |
|
1061 | 1060 | # TODO |
|
1062 | 1061 | pass |
|
1063 | 1062 | |
|
1064 | 1063 | def clear_output(wait=False): |
|
1065 | 1064 | """Clear the output of the current cell receiving output. |
|
1066 | 1065 | |
|
1067 | 1066 | Parameters |
|
1068 | 1067 | ---------- |
|
1069 | 1068 | wait : bool [default: false] |
|
1070 | 1069 | Wait to clear the output until new output is available to replace it.""" |
|
1071 | 1070 | from IPython.core.interactiveshell import InteractiveShell |
|
1072 | 1071 | if InteractiveShell.initialized(): |
|
1073 | 1072 | InteractiveShell.instance().display_pub.clear_output(wait) |
|
1074 | 1073 | else: |
|
1075 | 1074 | print('\033[2K\r', end='') |
|
1076 | 1075 | sys.stdout.flush() |
|
1077 | 1076 | print('\033[2K\r', end='') |
|
1078 | 1077 | sys.stderr.flush() |
|
1079 | 1078 | |
|
1080 | 1079 | |
|
1081 | 1080 | @skip_doctest |
|
1082 | 1081 | def set_matplotlib_formats(*formats, **kwargs): |
|
1083 | 1082 | """Select figure formats for the inline backend. Optionally pass quality for JPEG. |
|
1084 | 1083 | |
|
1085 | 1084 | For example, this enables PNG and JPEG output with a JPEG quality of 90%:: |
|
1086 | 1085 | |
|
1087 | 1086 | In [1]: set_matplotlib_formats('png', 'jpeg', quality=90) |
|
1088 | 1087 | |
|
1089 | 1088 | To set this in your config files use the following:: |
|
1090 | 1089 | |
|
1091 | 1090 | c.InlineBackend.figure_formats = {'png', 'jpeg'} |
|
1092 | 1091 | c.InlineBackend.print_figure_kwargs.update({'quality' : 90}) |
|
1093 | 1092 | |
|
1094 | 1093 | Parameters |
|
1095 | 1094 | ---------- |
|
1096 | 1095 | *formats : strs |
|
1097 | 1096 | One or more figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'. |
|
1098 | 1097 | **kwargs : |
|
1099 | 1098 | Keyword args will be relayed to ``figure.canvas.print_figure``. |
|
1100 | 1099 | """ |
|
1101 | 1100 | from IPython.core.interactiveshell import InteractiveShell |
|
1102 | 1101 | from IPython.core.pylabtools import select_figure_formats |
|
1103 | 1102 | # build kwargs, starting with InlineBackend config |
|
1104 | 1103 | kw = {} |
|
1105 | 1104 | from ipykernel.pylab.config import InlineBackend |
|
1106 | 1105 | cfg = InlineBackend.instance() |
|
1107 | 1106 | kw.update(cfg.print_figure_kwargs) |
|
1108 | 1107 | kw.update(**kwargs) |
|
1109 | 1108 | shell = InteractiveShell.instance() |
|
1110 | 1109 | select_figure_formats(shell, formats, **kw) |
|
1111 | 1110 | |
|
1112 | 1111 | @skip_doctest |
|
1113 | 1112 | def set_matplotlib_close(close=True): |
|
1114 | 1113 | """Set whether the inline backend closes all figures automatically or not. |
|
1115 | 1114 | |
|
1116 | 1115 | By default, the inline backend used in the IPython Notebook will close all |
|
1117 | 1116 | matplotlib figures automatically after each cell is run. This means that |
|
1118 | 1117 | plots in different cells won't interfere. Sometimes, you may want to make |
|
1119 | 1118 | a plot in one cell and then refine it in later cells. This can be accomplished |
|
1120 | 1119 | by:: |
|
1121 | 1120 | |
|
1122 | 1121 | In [1]: set_matplotlib_close(False) |
|
1123 | 1122 | |
|
1124 | 1123 | To set this in your config files use the following:: |
|
1125 | 1124 | |
|
1126 | 1125 | c.InlineBackend.close_figures = False |
|
1127 | 1126 | |
|
1128 | 1127 | Parameters |
|
1129 | 1128 | ---------- |
|
1130 | 1129 | close : bool |
|
1131 | 1130 | Should all matplotlib figures be automatically closed after each cell is |
|
1132 | 1131 | run? |
|
1133 | 1132 | """ |
|
1134 | 1133 | from ipykernel.pylab.config import InlineBackend |
|
1135 | 1134 | cfg = InlineBackend.instance() |
|
1136 | 1135 | cfg.close_figures = close |
@@ -1,947 +1,947 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 json |
|
15 | 15 | import sys |
|
16 | 16 | import traceback |
|
17 | 17 | import warnings |
|
18 | 18 | |
|
19 | 19 | from decorator import decorator |
|
20 | 20 | |
|
21 | 21 | from traitlets.config.configurable import Configurable |
|
22 | 22 | from IPython.core.getipython import get_ipython |
|
23 | 23 | from IPython.utils.sentinel import Sentinel |
|
24 | 24 | from IPython.utils.dir2 import get_real_method |
|
25 | 25 | from IPython.lib import pretty |
|
26 | 26 | from traitlets import ( |
|
27 | 27 | Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List, |
|
28 | 28 | ForwardDeclaredInstance, |
|
29 | 29 | default, observe, |
|
30 | 30 | ) |
|
31 | 31 | from IPython.utils.py3compat import ( |
|
32 | with_metaclass, string_types, unicode_type, | |
|
32 | with_metaclass | |
|
33 | 33 | ) |
|
34 | 34 | |
|
35 | 35 | |
|
36 | 36 | class DisplayFormatter(Configurable): |
|
37 | 37 | |
|
38 | 38 | active_types = List(Unicode(), |
|
39 | 39 | help="""List of currently active mime-types to display. |
|
40 | 40 | You can use this to set a white-list for formats to display. |
|
41 | 41 | |
|
42 | 42 | Most users will not need to change this value. |
|
43 | 43 | """).tag(config=True) |
|
44 | 44 | |
|
45 | 45 | @default('active_types') |
|
46 | 46 | def _active_types_default(self): |
|
47 | 47 | return self.format_types |
|
48 | 48 | |
|
49 | 49 | @observe('active_types') |
|
50 | 50 | def _active_types_changed(self, change): |
|
51 | 51 | for key, formatter in self.formatters.items(): |
|
52 | 52 | if key in change['new']: |
|
53 | 53 | formatter.enabled = True |
|
54 | 54 | else: |
|
55 | 55 | formatter.enabled = False |
|
56 | 56 | |
|
57 | 57 | ipython_display_formatter = ForwardDeclaredInstance('FormatterABC') |
|
58 | 58 | @default('ipython_display_formatter') |
|
59 | 59 | def _default_formatter(self): |
|
60 | 60 | return IPythonDisplayFormatter(parent=self) |
|
61 | 61 | |
|
62 | 62 | # A dict of formatter whose keys are format types (MIME types) and whose |
|
63 | 63 | # values are subclasses of BaseFormatter. |
|
64 | 64 | formatters = Dict() |
|
65 | 65 | @default('formatters') |
|
66 | 66 | def _formatters_default(self): |
|
67 | 67 | """Activate the default formatters.""" |
|
68 | 68 | formatter_classes = [ |
|
69 | 69 | PlainTextFormatter, |
|
70 | 70 | HTMLFormatter, |
|
71 | 71 | MarkdownFormatter, |
|
72 | 72 | SVGFormatter, |
|
73 | 73 | PNGFormatter, |
|
74 | 74 | PDFFormatter, |
|
75 | 75 | JPEGFormatter, |
|
76 | 76 | LatexFormatter, |
|
77 | 77 | JSONFormatter, |
|
78 | 78 | JavascriptFormatter |
|
79 | 79 | ] |
|
80 | 80 | d = {} |
|
81 | 81 | for cls in formatter_classes: |
|
82 | 82 | f = cls(parent=self) |
|
83 | 83 | d[f.format_type] = f |
|
84 | 84 | return d |
|
85 | 85 | |
|
86 | 86 | def format(self, obj, include=None, exclude=None): |
|
87 | 87 | """Return a format data dict for an object. |
|
88 | 88 | |
|
89 | 89 | By default all format types will be computed. |
|
90 | 90 | |
|
91 | 91 | The following MIME types are currently implemented: |
|
92 | 92 | |
|
93 | 93 | * text/plain |
|
94 | 94 | * text/html |
|
95 | 95 | * text/markdown |
|
96 | 96 | * text/latex |
|
97 | 97 | * application/json |
|
98 | 98 | * application/javascript |
|
99 | 99 | * application/pdf |
|
100 | 100 | * image/png |
|
101 | 101 | * image/jpeg |
|
102 | 102 | * image/svg+xml |
|
103 | 103 | |
|
104 | 104 | Parameters |
|
105 | 105 | ---------- |
|
106 | 106 | obj : object |
|
107 | 107 | The Python object whose format data will be computed. |
|
108 | 108 | include : list or tuple, optional |
|
109 | 109 | A list of format type strings (MIME types) to include in the |
|
110 | 110 | format data dict. If this is set *only* the format types included |
|
111 | 111 | in this list will be computed. |
|
112 | 112 | exclude : list or tuple, optional |
|
113 | 113 | A list of format type string (MIME types) to exclude in the format |
|
114 | 114 | data dict. If this is set all format types will be computed, |
|
115 | 115 | except for those included in this argument. |
|
116 | 116 | |
|
117 | 117 | Returns |
|
118 | 118 | ------- |
|
119 | 119 | (format_dict, metadata_dict) : tuple of two dicts |
|
120 | 120 | |
|
121 | 121 | format_dict is a dictionary of key/value pairs, one of each format that was |
|
122 | 122 | generated for the object. The keys are the format types, which |
|
123 | 123 | will usually be MIME type strings and the values and JSON'able |
|
124 | 124 | data structure containing the raw data for the representation in |
|
125 | 125 | that format. |
|
126 | 126 | |
|
127 | 127 | metadata_dict is a dictionary of metadata about each mime-type output. |
|
128 | 128 | Its keys will be a strict subset of the keys in format_dict. |
|
129 | 129 | """ |
|
130 | 130 | format_dict = {} |
|
131 | 131 | md_dict = {} |
|
132 | 132 | |
|
133 | 133 | if self.ipython_display_formatter(obj): |
|
134 | 134 | # object handled itself, don't proceed |
|
135 | 135 | return {}, {} |
|
136 | 136 | |
|
137 | 137 | for format_type, formatter in self.formatters.items(): |
|
138 | 138 | if include and format_type not in include: |
|
139 | 139 | continue |
|
140 | 140 | if exclude and format_type in exclude: |
|
141 | 141 | continue |
|
142 | 142 | |
|
143 | 143 | md = None |
|
144 | 144 | try: |
|
145 | 145 | data = formatter(obj) |
|
146 | 146 | except: |
|
147 | 147 | # FIXME: log the exception |
|
148 | 148 | raise |
|
149 | 149 | |
|
150 | 150 | # formatters can return raw data or (data, metadata) |
|
151 | 151 | if isinstance(data, tuple) and len(data) == 2: |
|
152 | 152 | data, md = data |
|
153 | 153 | |
|
154 | 154 | if data is not None: |
|
155 | 155 | format_dict[format_type] = data |
|
156 | 156 | if md is not None: |
|
157 | 157 | md_dict[format_type] = md |
|
158 | 158 | |
|
159 | 159 | return format_dict, md_dict |
|
160 | 160 | |
|
161 | 161 | @property |
|
162 | 162 | def format_types(self): |
|
163 | 163 | """Return the format types (MIME types) of the active formatters.""" |
|
164 | 164 | return list(self.formatters.keys()) |
|
165 | 165 | |
|
166 | 166 | |
|
167 | 167 | #----------------------------------------------------------------------------- |
|
168 | 168 | # Formatters for specific format types (text, html, svg, etc.) |
|
169 | 169 | #----------------------------------------------------------------------------- |
|
170 | 170 | |
|
171 | 171 | |
|
172 | 172 | def _safe_repr(obj): |
|
173 | 173 | """Try to return a repr of an object |
|
174 | 174 | |
|
175 | 175 | always returns a string, at least. |
|
176 | 176 | """ |
|
177 | 177 | try: |
|
178 | 178 | return repr(obj) |
|
179 | 179 | except Exception as e: |
|
180 | 180 | return "un-repr-able object (%r)" % e |
|
181 | 181 | |
|
182 | 182 | |
|
183 | 183 | class FormatterWarning(UserWarning): |
|
184 | 184 | """Warning class for errors in formatters""" |
|
185 | 185 | |
|
186 | 186 | @decorator |
|
187 | 187 | def catch_format_error(method, self, *args, **kwargs): |
|
188 | 188 | """show traceback on failed format call""" |
|
189 | 189 | try: |
|
190 | 190 | r = method(self, *args, **kwargs) |
|
191 | 191 | except NotImplementedError: |
|
192 | 192 | # don't warn on NotImplementedErrors |
|
193 | 193 | return None |
|
194 | 194 | except Exception: |
|
195 | 195 | exc_info = sys.exc_info() |
|
196 | 196 | ip = get_ipython() |
|
197 | 197 | if ip is not None: |
|
198 | 198 | ip.showtraceback(exc_info) |
|
199 | 199 | else: |
|
200 | 200 | traceback.print_exception(*exc_info) |
|
201 | 201 | return None |
|
202 | 202 | return self._check_return(r, args[0]) |
|
203 | 203 | |
|
204 | 204 | |
|
205 | 205 | class FormatterABC(with_metaclass(abc.ABCMeta, object)): |
|
206 | 206 | """ Abstract base class for Formatters. |
|
207 | 207 | |
|
208 | 208 | A formatter is a callable class that is responsible for computing the |
|
209 | 209 | raw format data for a particular format type (MIME type). For example, |
|
210 | 210 | an HTML formatter would have a format type of `text/html` and would return |
|
211 | 211 | the HTML representation of the object when called. |
|
212 | 212 | """ |
|
213 | 213 | |
|
214 | 214 | # The format type of the data returned, usually a MIME type. |
|
215 | 215 | format_type = 'text/plain' |
|
216 | 216 | |
|
217 | 217 | # Is the formatter enabled... |
|
218 | 218 | enabled = True |
|
219 | 219 | |
|
220 | 220 | @abc.abstractmethod |
|
221 | 221 | def __call__(self, obj): |
|
222 | 222 | """Return a JSON'able representation of the object. |
|
223 | 223 | |
|
224 | 224 | If the object cannot be formatted by this formatter, |
|
225 | 225 | warn and return None. |
|
226 | 226 | """ |
|
227 | 227 | return repr(obj) |
|
228 | 228 | |
|
229 | 229 | |
|
230 | 230 | def _mod_name_key(typ): |
|
231 | 231 | """Return a (__module__, __name__) tuple for a type. |
|
232 | 232 | |
|
233 | 233 | Used as key in Formatter.deferred_printers. |
|
234 | 234 | """ |
|
235 | 235 | module = getattr(typ, '__module__', None) |
|
236 | 236 | name = getattr(typ, '__name__', None) |
|
237 | 237 | return (module, name) |
|
238 | 238 | |
|
239 | 239 | |
|
240 | 240 | def _get_type(obj): |
|
241 | 241 | """Return the type of an instance (old and new-style)""" |
|
242 | 242 | return getattr(obj, '__class__', None) or type(obj) |
|
243 | 243 | |
|
244 | 244 | |
|
245 | 245 | _raise_key_error = Sentinel('_raise_key_error', __name__, |
|
246 | 246 | """ |
|
247 | 247 | Special value to raise a KeyError |
|
248 | 248 | |
|
249 | 249 | Raise KeyError in `BaseFormatter.pop` if passed as the default value to `pop` |
|
250 | 250 | """) |
|
251 | 251 | |
|
252 | 252 | |
|
253 | 253 | class BaseFormatter(Configurable): |
|
254 | 254 | """A base formatter class that is configurable. |
|
255 | 255 | |
|
256 | 256 | This formatter should usually be used as the base class of all formatters. |
|
257 | 257 | It is a traited :class:`Configurable` class and includes an extensible |
|
258 | 258 | API for users to determine how their objects are formatted. The following |
|
259 | 259 | logic is used to find a function to format an given object. |
|
260 | 260 | |
|
261 | 261 | 1. The object is introspected to see if it has a method with the name |
|
262 | 262 | :attr:`print_method`. If is does, that object is passed to that method |
|
263 | 263 | for formatting. |
|
264 | 264 | 2. If no print method is found, three internal dictionaries are consulted |
|
265 | 265 | to find print method: :attr:`singleton_printers`, :attr:`type_printers` |
|
266 | 266 | and :attr:`deferred_printers`. |
|
267 | 267 | |
|
268 | 268 | Users should use these dictionaries to register functions that will be |
|
269 | 269 | used to compute the format data for their objects (if those objects don't |
|
270 | 270 | have the special print methods). The easiest way of using these |
|
271 | 271 | dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name` |
|
272 | 272 | methods. |
|
273 | 273 | |
|
274 | 274 | If no function/callable is found to compute the format data, ``None`` is |
|
275 | 275 | returned and this format type is not used. |
|
276 | 276 | """ |
|
277 | 277 | |
|
278 | 278 | format_type = Unicode('text/plain') |
|
279 |
_return_type = str |
|
|
279 | _return_type = str | |
|
280 | 280 | |
|
281 | 281 | enabled = Bool(True).tag(config=True) |
|
282 | 282 | |
|
283 | 283 | print_method = ObjectName('__repr__') |
|
284 | 284 | |
|
285 | 285 | # The singleton printers. |
|
286 | 286 | # Maps the IDs of the builtin singleton objects to the format functions. |
|
287 | 287 | singleton_printers = Dict().tag(config=True) |
|
288 | 288 | |
|
289 | 289 | # The type-specific printers. |
|
290 | 290 | # Map type objects to the format functions. |
|
291 | 291 | type_printers = Dict().tag(config=True) |
|
292 | 292 | |
|
293 | 293 | # The deferred-import type-specific printers. |
|
294 | 294 | # Map (modulename, classname) pairs to the format functions. |
|
295 | 295 | deferred_printers = Dict().tag(config=True) |
|
296 | 296 | |
|
297 | 297 | @catch_format_error |
|
298 | 298 | def __call__(self, obj): |
|
299 | 299 | """Compute the format for an object.""" |
|
300 | 300 | if self.enabled: |
|
301 | 301 | # lookup registered printer |
|
302 | 302 | try: |
|
303 | 303 | printer = self.lookup(obj) |
|
304 | 304 | except KeyError: |
|
305 | 305 | pass |
|
306 | 306 | else: |
|
307 | 307 | return printer(obj) |
|
308 | 308 | # Finally look for special method names |
|
309 | 309 | method = get_real_method(obj, self.print_method) |
|
310 | 310 | if method is not None: |
|
311 | 311 | return method() |
|
312 | 312 | return None |
|
313 | 313 | else: |
|
314 | 314 | return None |
|
315 | 315 | |
|
316 | 316 | def __contains__(self, typ): |
|
317 | 317 | """map in to lookup_by_type""" |
|
318 | 318 | try: |
|
319 | 319 | self.lookup_by_type(typ) |
|
320 | 320 | except KeyError: |
|
321 | 321 | return False |
|
322 | 322 | else: |
|
323 | 323 | return True |
|
324 | 324 | |
|
325 | 325 | def _check_return(self, r, obj): |
|
326 | 326 | """Check that a return value is appropriate |
|
327 | 327 | |
|
328 | 328 | Return the value if so, None otherwise, warning if invalid. |
|
329 | 329 | """ |
|
330 | 330 | if r is None or isinstance(r, self._return_type) or \ |
|
331 | 331 | (isinstance(r, tuple) and r and isinstance(r[0], self._return_type)): |
|
332 | 332 | return r |
|
333 | 333 | else: |
|
334 | 334 | warnings.warn( |
|
335 | 335 | "%s formatter returned invalid type %s (expected %s) for object: %s" % \ |
|
336 | 336 | (self.format_type, type(r), self._return_type, _safe_repr(obj)), |
|
337 | 337 | FormatterWarning |
|
338 | 338 | ) |
|
339 | 339 | |
|
340 | 340 | def lookup(self, obj): |
|
341 | 341 | """Look up the formatter for a given instance. |
|
342 | 342 | |
|
343 | 343 | Parameters |
|
344 | 344 | ---------- |
|
345 | 345 | obj : object instance |
|
346 | 346 | |
|
347 | 347 | Returns |
|
348 | 348 | ------- |
|
349 | 349 | f : callable |
|
350 | 350 | The registered formatting callable for the type. |
|
351 | 351 | |
|
352 | 352 | Raises |
|
353 | 353 | ------ |
|
354 | 354 | KeyError if the type has not been registered. |
|
355 | 355 | """ |
|
356 | 356 | # look for singleton first |
|
357 | 357 | obj_id = id(obj) |
|
358 | 358 | if obj_id in self.singleton_printers: |
|
359 | 359 | return self.singleton_printers[obj_id] |
|
360 | 360 | # then lookup by type |
|
361 | 361 | return self.lookup_by_type(_get_type(obj)) |
|
362 | 362 | |
|
363 | 363 | def lookup_by_type(self, typ): |
|
364 | 364 | """Look up the registered formatter for a type. |
|
365 | 365 | |
|
366 | 366 | Parameters |
|
367 | 367 | ---------- |
|
368 | 368 | typ : type or '__module__.__name__' string for a type |
|
369 | 369 | |
|
370 | 370 | Returns |
|
371 | 371 | ------- |
|
372 | 372 | f : callable |
|
373 | 373 | The registered formatting callable for the type. |
|
374 | 374 | |
|
375 | 375 | Raises |
|
376 | 376 | ------ |
|
377 | 377 | KeyError if the type has not been registered. |
|
378 | 378 | """ |
|
379 |
if isinstance(typ, str |
|
|
379 | if isinstance(typ, str): | |
|
380 | 380 | typ_key = tuple(typ.rsplit('.',1)) |
|
381 | 381 | if typ_key not in self.deferred_printers: |
|
382 | 382 | # We may have it cached in the type map. We will have to |
|
383 | 383 | # iterate over all of the types to check. |
|
384 | 384 | for cls in self.type_printers: |
|
385 | 385 | if _mod_name_key(cls) == typ_key: |
|
386 | 386 | return self.type_printers[cls] |
|
387 | 387 | else: |
|
388 | 388 | return self.deferred_printers[typ_key] |
|
389 | 389 | else: |
|
390 | 390 | for cls in pretty._get_mro(typ): |
|
391 | 391 | if cls in self.type_printers or self._in_deferred_types(cls): |
|
392 | 392 | return self.type_printers[cls] |
|
393 | 393 | |
|
394 | 394 | # If we have reached here, the lookup failed. |
|
395 | 395 | raise KeyError("No registered printer for {0!r}".format(typ)) |
|
396 | 396 | |
|
397 | 397 | def for_type(self, typ, func=None): |
|
398 | 398 | """Add a format function for a given type. |
|
399 | 399 | |
|
400 | 400 | Parameters |
|
401 | 401 | ----------- |
|
402 | 402 | typ : type or '__module__.__name__' string for a type |
|
403 | 403 | The class of the object that will be formatted using `func`. |
|
404 | 404 | func : callable |
|
405 | 405 | A callable for computing the format data. |
|
406 | 406 | `func` will be called with the object to be formatted, |
|
407 | 407 | and will return the raw data in this formatter's format. |
|
408 | 408 | Subclasses may use a different call signature for the |
|
409 | 409 | `func` argument. |
|
410 | 410 | |
|
411 | 411 | If `func` is None or not specified, there will be no change, |
|
412 | 412 | only returning the current value. |
|
413 | 413 | |
|
414 | 414 | Returns |
|
415 | 415 | ------- |
|
416 | 416 | oldfunc : callable |
|
417 | 417 | The currently registered callable. |
|
418 | 418 | If you are registering a new formatter, |
|
419 | 419 | this will be the previous value (to enable restoring later). |
|
420 | 420 | """ |
|
421 | 421 | # if string given, interpret as 'pkg.module.class_name' |
|
422 |
if isinstance(typ, str |
|
|
422 | if isinstance(typ, str): | |
|
423 | 423 | type_module, type_name = typ.rsplit('.', 1) |
|
424 | 424 | return self.for_type_by_name(type_module, type_name, func) |
|
425 | 425 | |
|
426 | 426 | try: |
|
427 | 427 | oldfunc = self.lookup_by_type(typ) |
|
428 | 428 | except KeyError: |
|
429 | 429 | oldfunc = None |
|
430 | 430 | |
|
431 | 431 | if func is not None: |
|
432 | 432 | self.type_printers[typ] = func |
|
433 | 433 | |
|
434 | 434 | return oldfunc |
|
435 | 435 | |
|
436 | 436 | def for_type_by_name(self, type_module, type_name, func=None): |
|
437 | 437 | """Add a format function for a type specified by the full dotted |
|
438 | 438 | module and name of the type, rather than the type of the object. |
|
439 | 439 | |
|
440 | 440 | Parameters |
|
441 | 441 | ---------- |
|
442 | 442 | type_module : str |
|
443 | 443 | The full dotted name of the module the type is defined in, like |
|
444 | 444 | ``numpy``. |
|
445 | 445 | type_name : str |
|
446 | 446 | The name of the type (the class name), like ``dtype`` |
|
447 | 447 | func : callable |
|
448 | 448 | A callable for computing the format data. |
|
449 | 449 | `func` will be called with the object to be formatted, |
|
450 | 450 | and will return the raw data in this formatter's format. |
|
451 | 451 | Subclasses may use a different call signature for the |
|
452 | 452 | `func` argument. |
|
453 | 453 | |
|
454 | 454 | If `func` is None or unspecified, there will be no change, |
|
455 | 455 | only returning the current value. |
|
456 | 456 | |
|
457 | 457 | Returns |
|
458 | 458 | ------- |
|
459 | 459 | oldfunc : callable |
|
460 | 460 | The currently registered callable. |
|
461 | 461 | If you are registering a new formatter, |
|
462 | 462 | this will be the previous value (to enable restoring later). |
|
463 | 463 | """ |
|
464 | 464 | key = (type_module, type_name) |
|
465 | 465 | |
|
466 | 466 | try: |
|
467 | 467 | oldfunc = self.lookup_by_type("%s.%s" % key) |
|
468 | 468 | except KeyError: |
|
469 | 469 | oldfunc = None |
|
470 | 470 | |
|
471 | 471 | if func is not None: |
|
472 | 472 | self.deferred_printers[key] = func |
|
473 | 473 | return oldfunc |
|
474 | 474 | |
|
475 | 475 | def pop(self, typ, default=_raise_key_error): |
|
476 | 476 | """Pop a formatter for the given type. |
|
477 | 477 | |
|
478 | 478 | Parameters |
|
479 | 479 | ---------- |
|
480 | 480 | typ : type or '__module__.__name__' string for a type |
|
481 | 481 | default : object |
|
482 | 482 | value to be returned if no formatter is registered for typ. |
|
483 | 483 | |
|
484 | 484 | Returns |
|
485 | 485 | ------- |
|
486 | 486 | obj : object |
|
487 | 487 | The last registered object for the type. |
|
488 | 488 | |
|
489 | 489 | Raises |
|
490 | 490 | ------ |
|
491 | 491 | KeyError if the type is not registered and default is not specified. |
|
492 | 492 | """ |
|
493 | 493 | |
|
494 |
if isinstance(typ, str |
|
|
494 | if isinstance(typ, str): | |
|
495 | 495 | typ_key = tuple(typ.rsplit('.',1)) |
|
496 | 496 | if typ_key not in self.deferred_printers: |
|
497 | 497 | # We may have it cached in the type map. We will have to |
|
498 | 498 | # iterate over all of the types to check. |
|
499 | 499 | for cls in self.type_printers: |
|
500 | 500 | if _mod_name_key(cls) == typ_key: |
|
501 | 501 | old = self.type_printers.pop(cls) |
|
502 | 502 | break |
|
503 | 503 | else: |
|
504 | 504 | old = default |
|
505 | 505 | else: |
|
506 | 506 | old = self.deferred_printers.pop(typ_key) |
|
507 | 507 | else: |
|
508 | 508 | if typ in self.type_printers: |
|
509 | 509 | old = self.type_printers.pop(typ) |
|
510 | 510 | else: |
|
511 | 511 | old = self.deferred_printers.pop(_mod_name_key(typ), default) |
|
512 | 512 | if old is _raise_key_error: |
|
513 | 513 | raise KeyError("No registered value for {0!r}".format(typ)) |
|
514 | 514 | return old |
|
515 | 515 | |
|
516 | 516 | def _in_deferred_types(self, cls): |
|
517 | 517 | """ |
|
518 | 518 | Check if the given class is specified in the deferred type registry. |
|
519 | 519 | |
|
520 | 520 | Successful matches will be moved to the regular type registry for future use. |
|
521 | 521 | """ |
|
522 | 522 | mod = getattr(cls, '__module__', None) |
|
523 | 523 | name = getattr(cls, '__name__', None) |
|
524 | 524 | key = (mod, name) |
|
525 | 525 | if key in self.deferred_printers: |
|
526 | 526 | # Move the printer over to the regular registry. |
|
527 | 527 | printer = self.deferred_printers.pop(key) |
|
528 | 528 | self.type_printers[cls] = printer |
|
529 | 529 | return True |
|
530 | 530 | return False |
|
531 | 531 | |
|
532 | 532 | |
|
533 | 533 | class PlainTextFormatter(BaseFormatter): |
|
534 | 534 | """The default pretty-printer. |
|
535 | 535 | |
|
536 | 536 | This uses :mod:`IPython.lib.pretty` to compute the format data of |
|
537 | 537 | the object. If the object cannot be pretty printed, :func:`repr` is used. |
|
538 | 538 | See the documentation of :mod:`IPython.lib.pretty` for details on |
|
539 | 539 | how to write pretty printers. Here is a simple example:: |
|
540 | 540 | |
|
541 | 541 | def dtype_pprinter(obj, p, cycle): |
|
542 | 542 | if cycle: |
|
543 | 543 | return p.text('dtype(...)') |
|
544 | 544 | if hasattr(obj, 'fields'): |
|
545 | 545 | if obj.fields is None: |
|
546 | 546 | p.text(repr(obj)) |
|
547 | 547 | else: |
|
548 | 548 | p.begin_group(7, 'dtype([') |
|
549 | 549 | for i, field in enumerate(obj.descr): |
|
550 | 550 | if i > 0: |
|
551 | 551 | p.text(',') |
|
552 | 552 | p.breakable() |
|
553 | 553 | p.pretty(field) |
|
554 | 554 | p.end_group(7, '])') |
|
555 | 555 | """ |
|
556 | 556 | |
|
557 | 557 | # The format type of data returned. |
|
558 | 558 | format_type = Unicode('text/plain') |
|
559 | 559 | |
|
560 | 560 | # This subclass ignores this attribute as it always need to return |
|
561 | 561 | # something. |
|
562 | 562 | enabled = Bool(True).tag(config=False) |
|
563 | 563 | |
|
564 | 564 | max_seq_length = Integer(pretty.MAX_SEQ_LENGTH, |
|
565 | 565 | help="""Truncate large collections (lists, dicts, tuples, sets) to this size. |
|
566 | 566 | |
|
567 | 567 | Set to 0 to disable truncation. |
|
568 | 568 | """ |
|
569 | 569 | ).tag(config=True) |
|
570 | 570 | |
|
571 | 571 | # Look for a _repr_pretty_ methods to use for pretty printing. |
|
572 | 572 | print_method = ObjectName('_repr_pretty_') |
|
573 | 573 | |
|
574 | 574 | # Whether to pretty-print or not. |
|
575 | 575 | pprint = Bool(True).tag(config=True) |
|
576 | 576 | |
|
577 | 577 | # Whether to be verbose or not. |
|
578 | 578 | verbose = Bool(False).tag(config=True) |
|
579 | 579 | |
|
580 | 580 | # The maximum width. |
|
581 | 581 | max_width = Integer(79).tag(config=True) |
|
582 | 582 | |
|
583 | 583 | # The newline character. |
|
584 | 584 | newline = Unicode('\n').tag(config=True) |
|
585 | 585 | |
|
586 | 586 | # format-string for pprinting floats |
|
587 | 587 | float_format = Unicode('%r') |
|
588 | 588 | # setter for float precision, either int or direct format-string |
|
589 | 589 | float_precision = CUnicode('').tag(config=True) |
|
590 | 590 | |
|
591 | 591 | @observe('float_precision') |
|
592 | 592 | def _float_precision_changed(self, change): |
|
593 | 593 | """float_precision changed, set float_format accordingly. |
|
594 | 594 | |
|
595 | 595 | float_precision can be set by int or str. |
|
596 | 596 | This will set float_format, after interpreting input. |
|
597 | 597 | If numpy has been imported, numpy print precision will also be set. |
|
598 | 598 | |
|
599 | 599 | integer `n` sets format to '%.nf', otherwise, format set directly. |
|
600 | 600 | |
|
601 | 601 | An empty string returns to defaults (repr for float, 8 for numpy). |
|
602 | 602 | |
|
603 | 603 | This parameter can be set via the '%precision' magic. |
|
604 | 604 | """ |
|
605 | 605 | |
|
606 | 606 | new = change['new'] |
|
607 | 607 | if '%' in new: |
|
608 | 608 | # got explicit format string |
|
609 | 609 | fmt = new |
|
610 | 610 | try: |
|
611 | 611 | fmt%3.14159 |
|
612 | 612 | except Exception: |
|
613 | 613 | raise ValueError("Precision must be int or format string, not %r"%new) |
|
614 | 614 | elif new: |
|
615 | 615 | # otherwise, should be an int |
|
616 | 616 | try: |
|
617 | 617 | i = int(new) |
|
618 | 618 | assert i >= 0 |
|
619 | 619 | except ValueError: |
|
620 | 620 | raise ValueError("Precision must be int or format string, not %r"%new) |
|
621 | 621 | except AssertionError: |
|
622 | 622 | raise ValueError("int precision must be non-negative, not %r"%i) |
|
623 | 623 | |
|
624 | 624 | fmt = '%%.%if'%i |
|
625 | 625 | if 'numpy' in sys.modules: |
|
626 | 626 | # set numpy precision if it has been imported |
|
627 | 627 | import numpy |
|
628 | 628 | numpy.set_printoptions(precision=i) |
|
629 | 629 | else: |
|
630 | 630 | # default back to repr |
|
631 | 631 | fmt = '%r' |
|
632 | 632 | if 'numpy' in sys.modules: |
|
633 | 633 | import numpy |
|
634 | 634 | # numpy default is 8 |
|
635 | 635 | numpy.set_printoptions(precision=8) |
|
636 | 636 | self.float_format = fmt |
|
637 | 637 | |
|
638 | 638 | # Use the default pretty printers from IPython.lib.pretty. |
|
639 | 639 | @default('singleton_printers') |
|
640 | 640 | def _singleton_printers_default(self): |
|
641 | 641 | return pretty._singleton_pprinters.copy() |
|
642 | 642 | |
|
643 | 643 | @default('type_printers') |
|
644 | 644 | def _type_printers_default(self): |
|
645 | 645 | d = pretty._type_pprinters.copy() |
|
646 | 646 | d[float] = lambda obj,p,cycle: p.text(self.float_format%obj) |
|
647 | 647 | return d |
|
648 | 648 | |
|
649 | 649 | @default('deferred_printers') |
|
650 | 650 | def _deferred_printers_default(self): |
|
651 | 651 | return pretty._deferred_type_pprinters.copy() |
|
652 | 652 | |
|
653 | 653 | #### FormatterABC interface #### |
|
654 | 654 | |
|
655 | 655 | @catch_format_error |
|
656 | 656 | def __call__(self, obj): |
|
657 | 657 | """Compute the pretty representation of the object.""" |
|
658 | 658 | if not self.pprint: |
|
659 | 659 | return repr(obj) |
|
660 | 660 | else: |
|
661 | 661 | # handle str and unicode on Python 2 |
|
662 | 662 | # io.StringIO only accepts unicode, |
|
663 | 663 | # cStringIO doesn't handle unicode on py2, |
|
664 | 664 | # StringIO allows str, unicode but only ascii str |
|
665 | 665 | stream = pretty.CUnicodeIO() |
|
666 | 666 | printer = pretty.RepresentationPrinter(stream, self.verbose, |
|
667 | 667 | self.max_width, self.newline, |
|
668 | 668 | max_seq_length=self.max_seq_length, |
|
669 | 669 | singleton_pprinters=self.singleton_printers, |
|
670 | 670 | type_pprinters=self.type_printers, |
|
671 | 671 | deferred_pprinters=self.deferred_printers) |
|
672 | 672 | printer.pretty(obj) |
|
673 | 673 | printer.flush() |
|
674 | 674 | return stream.getvalue() |
|
675 | 675 | |
|
676 | 676 | |
|
677 | 677 | class HTMLFormatter(BaseFormatter): |
|
678 | 678 | """An HTML formatter. |
|
679 | 679 | |
|
680 | 680 | To define the callables that compute the HTML representation of your |
|
681 | 681 | objects, define a :meth:`_repr_html_` method or use the :meth:`for_type` |
|
682 | 682 | or :meth:`for_type_by_name` methods to register functions that handle |
|
683 | 683 | this. |
|
684 | 684 | |
|
685 | 685 | The return value of this formatter should be a valid HTML snippet that |
|
686 | 686 | could be injected into an existing DOM. It should *not* include the |
|
687 | 687 | ```<html>`` or ```<body>`` tags. |
|
688 | 688 | """ |
|
689 | 689 | format_type = Unicode('text/html') |
|
690 | 690 | |
|
691 | 691 | print_method = ObjectName('_repr_html_') |
|
692 | 692 | |
|
693 | 693 | |
|
694 | 694 | class MarkdownFormatter(BaseFormatter): |
|
695 | 695 | """A Markdown formatter. |
|
696 | 696 | |
|
697 | 697 | To define the callables that compute the Markdown representation of your |
|
698 | 698 | objects, define a :meth:`_repr_markdown_` method or use the :meth:`for_type` |
|
699 | 699 | or :meth:`for_type_by_name` methods to register functions that handle |
|
700 | 700 | this. |
|
701 | 701 | |
|
702 | 702 | The return value of this formatter should be a valid Markdown. |
|
703 | 703 | """ |
|
704 | 704 | format_type = Unicode('text/markdown') |
|
705 | 705 | |
|
706 | 706 | print_method = ObjectName('_repr_markdown_') |
|
707 | 707 | |
|
708 | 708 | class SVGFormatter(BaseFormatter): |
|
709 | 709 | """An SVG formatter. |
|
710 | 710 | |
|
711 | 711 | To define the callables that compute the SVG representation of your |
|
712 | 712 | objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type` |
|
713 | 713 | or :meth:`for_type_by_name` methods to register functions that handle |
|
714 | 714 | this. |
|
715 | 715 | |
|
716 | 716 | The return value of this formatter should be valid SVG enclosed in |
|
717 | 717 | ```<svg>``` tags, that could be injected into an existing DOM. It should |
|
718 | 718 | *not* include the ```<html>`` or ```<body>`` tags. |
|
719 | 719 | """ |
|
720 | 720 | format_type = Unicode('image/svg+xml') |
|
721 | 721 | |
|
722 | 722 | print_method = ObjectName('_repr_svg_') |
|
723 | 723 | |
|
724 | 724 | |
|
725 | 725 | class PNGFormatter(BaseFormatter): |
|
726 | 726 | """A PNG formatter. |
|
727 | 727 | |
|
728 | 728 | To define the callables that compute the PNG representation of your |
|
729 | 729 | objects, define a :meth:`_repr_png_` method or use the :meth:`for_type` |
|
730 | 730 | or :meth:`for_type_by_name` methods to register functions that handle |
|
731 | 731 | this. |
|
732 | 732 | |
|
733 | 733 | The return value of this formatter should be raw PNG data, *not* |
|
734 | 734 | base64 encoded. |
|
735 | 735 | """ |
|
736 | 736 | format_type = Unicode('image/png') |
|
737 | 737 | |
|
738 | 738 | print_method = ObjectName('_repr_png_') |
|
739 | 739 | |
|
740 |
_return_type = (bytes, |
|
|
740 | _return_type = (bytes, str) | |
|
741 | 741 | |
|
742 | 742 | |
|
743 | 743 | class JPEGFormatter(BaseFormatter): |
|
744 | 744 | """A JPEG formatter. |
|
745 | 745 | |
|
746 | 746 | To define the callables that compute the JPEG representation of your |
|
747 | 747 | objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type` |
|
748 | 748 | or :meth:`for_type_by_name` methods to register functions that handle |
|
749 | 749 | this. |
|
750 | 750 | |
|
751 | 751 | The return value of this formatter should be raw JPEG data, *not* |
|
752 | 752 | base64 encoded. |
|
753 | 753 | """ |
|
754 | 754 | format_type = Unicode('image/jpeg') |
|
755 | 755 | |
|
756 | 756 | print_method = ObjectName('_repr_jpeg_') |
|
757 | 757 | |
|
758 |
_return_type = (bytes, |
|
|
758 | _return_type = (bytes, str) | |
|
759 | 759 | |
|
760 | 760 | |
|
761 | 761 | class LatexFormatter(BaseFormatter): |
|
762 | 762 | """A LaTeX formatter. |
|
763 | 763 | |
|
764 | 764 | To define the callables that compute the LaTeX representation of your |
|
765 | 765 | objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type` |
|
766 | 766 | or :meth:`for_type_by_name` methods to register functions that handle |
|
767 | 767 | this. |
|
768 | 768 | |
|
769 | 769 | The return value of this formatter should be a valid LaTeX equation, |
|
770 | 770 | enclosed in either ```$```, ```$$``` or another LaTeX equation |
|
771 | 771 | environment. |
|
772 | 772 | """ |
|
773 | 773 | format_type = Unicode('text/latex') |
|
774 | 774 | |
|
775 | 775 | print_method = ObjectName('_repr_latex_') |
|
776 | 776 | |
|
777 | 777 | |
|
778 | 778 | class JSONFormatter(BaseFormatter): |
|
779 | 779 | """A JSON string formatter. |
|
780 | 780 | |
|
781 | 781 | To define the callables that compute the JSONable representation of |
|
782 | 782 | your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type` |
|
783 | 783 | or :meth:`for_type_by_name` methods to register functions that handle |
|
784 | 784 | this. |
|
785 | 785 | |
|
786 | 786 | The return value of this formatter should be a JSONable list or dict. |
|
787 | 787 | JSON scalars (None, number, string) are not allowed, only dict or list containers. |
|
788 | 788 | """ |
|
789 | 789 | format_type = Unicode('application/json') |
|
790 | 790 | _return_type = (list, dict) |
|
791 | 791 | |
|
792 | 792 | print_method = ObjectName('_repr_json_') |
|
793 | 793 | |
|
794 | 794 | def _check_return(self, r, obj): |
|
795 | 795 | """Check that a return value is appropriate |
|
796 | 796 | |
|
797 | 797 | Return the value if so, None otherwise, warning if invalid. |
|
798 | 798 | """ |
|
799 | 799 | if r is None: |
|
800 | 800 | return |
|
801 | 801 | md = None |
|
802 | 802 | if isinstance(r, tuple): |
|
803 | 803 | # unpack data, metadata tuple for type checking on first element |
|
804 | 804 | r, md = r |
|
805 | 805 | |
|
806 | 806 | # handle deprecated JSON-as-string form from IPython < 3 |
|
807 |
if isinstance(r, str |
|
|
807 | if isinstance(r, str): | |
|
808 | 808 | warnings.warn("JSON expects JSONable list/dict containers, not JSON strings", |
|
809 | 809 | FormatterWarning) |
|
810 | 810 | r = json.loads(r) |
|
811 | 811 | |
|
812 | 812 | if md is not None: |
|
813 | 813 | # put the tuple back together |
|
814 | 814 | r = (r, md) |
|
815 | 815 | return super(JSONFormatter, self)._check_return(r, obj) |
|
816 | 816 | |
|
817 | 817 | |
|
818 | 818 | class JavascriptFormatter(BaseFormatter): |
|
819 | 819 | """A Javascript formatter. |
|
820 | 820 | |
|
821 | 821 | To define the callables that compute the Javascript representation of |
|
822 | 822 | your objects, define a :meth:`_repr_javascript_` method or use the |
|
823 | 823 | :meth:`for_type` or :meth:`for_type_by_name` methods to register functions |
|
824 | 824 | that handle this. |
|
825 | 825 | |
|
826 | 826 | The return value of this formatter should be valid Javascript code and |
|
827 | 827 | should *not* be enclosed in ```<script>``` tags. |
|
828 | 828 | """ |
|
829 | 829 | format_type = Unicode('application/javascript') |
|
830 | 830 | |
|
831 | 831 | print_method = ObjectName('_repr_javascript_') |
|
832 | 832 | |
|
833 | 833 | |
|
834 | 834 | class PDFFormatter(BaseFormatter): |
|
835 | 835 | """A PDF formatter. |
|
836 | 836 | |
|
837 | 837 | To define the callables that compute the PDF representation of your |
|
838 | 838 | objects, define a :meth:`_repr_pdf_` method or use the :meth:`for_type` |
|
839 | 839 | or :meth:`for_type_by_name` methods to register functions that handle |
|
840 | 840 | this. |
|
841 | 841 | |
|
842 | 842 | The return value of this formatter should be raw PDF data, *not* |
|
843 | 843 | base64 encoded. |
|
844 | 844 | """ |
|
845 | 845 | format_type = Unicode('application/pdf') |
|
846 | 846 | |
|
847 | 847 | print_method = ObjectName('_repr_pdf_') |
|
848 | 848 | |
|
849 |
_return_type = (bytes, |
|
|
849 | _return_type = (bytes, str) | |
|
850 | 850 | |
|
851 | 851 | class IPythonDisplayFormatter(BaseFormatter): |
|
852 | 852 | """A Formatter for objects that know how to display themselves. |
|
853 | 853 | |
|
854 | 854 | To define the callables that compute the representation of your |
|
855 | 855 | objects, define a :meth:`_ipython_display_` method or use the :meth:`for_type` |
|
856 | 856 | or :meth:`for_type_by_name` methods to register functions that handle |
|
857 | 857 | this. Unlike mime-type displays, this method should not return anything, |
|
858 | 858 | instead calling any appropriate display methods itself. |
|
859 | 859 | |
|
860 | 860 | This display formatter has highest priority. |
|
861 | 861 | If it fires, no other display formatter will be called. |
|
862 | 862 | """ |
|
863 | 863 | print_method = ObjectName('_ipython_display_') |
|
864 | 864 | _return_type = (type(None), bool) |
|
865 | 865 | |
|
866 | 866 | |
|
867 | 867 | @catch_format_error |
|
868 | 868 | def __call__(self, obj): |
|
869 | 869 | """Compute the format for an object.""" |
|
870 | 870 | if self.enabled: |
|
871 | 871 | # lookup registered printer |
|
872 | 872 | try: |
|
873 | 873 | printer = self.lookup(obj) |
|
874 | 874 | except KeyError: |
|
875 | 875 | pass |
|
876 | 876 | else: |
|
877 | 877 | printer(obj) |
|
878 | 878 | return True |
|
879 | 879 | # Finally look for special method names |
|
880 | 880 | method = get_real_method(obj, self.print_method) |
|
881 | 881 | if method is not None: |
|
882 | 882 | method() |
|
883 | 883 | return True |
|
884 | 884 | |
|
885 | 885 | |
|
886 | 886 | FormatterABC.register(BaseFormatter) |
|
887 | 887 | FormatterABC.register(PlainTextFormatter) |
|
888 | 888 | FormatterABC.register(HTMLFormatter) |
|
889 | 889 | FormatterABC.register(MarkdownFormatter) |
|
890 | 890 | FormatterABC.register(SVGFormatter) |
|
891 | 891 | FormatterABC.register(PNGFormatter) |
|
892 | 892 | FormatterABC.register(PDFFormatter) |
|
893 | 893 | FormatterABC.register(JPEGFormatter) |
|
894 | 894 | FormatterABC.register(LatexFormatter) |
|
895 | 895 | FormatterABC.register(JSONFormatter) |
|
896 | 896 | FormatterABC.register(JavascriptFormatter) |
|
897 | 897 | FormatterABC.register(IPythonDisplayFormatter) |
|
898 | 898 | |
|
899 | 899 | |
|
900 | 900 | def format_display_data(obj, include=None, exclude=None): |
|
901 | 901 | """Return a format data dict for an object. |
|
902 | 902 | |
|
903 | 903 | By default all format types will be computed. |
|
904 | 904 | |
|
905 | 905 | The following MIME types are currently implemented: |
|
906 | 906 | |
|
907 | 907 | * text/plain |
|
908 | 908 | * text/html |
|
909 | 909 | * text/markdown |
|
910 | 910 | * text/latex |
|
911 | 911 | * application/json |
|
912 | 912 | * application/javascript |
|
913 | 913 | * application/pdf |
|
914 | 914 | * image/png |
|
915 | 915 | * image/jpeg |
|
916 | 916 | * image/svg+xml |
|
917 | 917 | |
|
918 | 918 | Parameters |
|
919 | 919 | ---------- |
|
920 | 920 | obj : object |
|
921 | 921 | The Python object whose format data will be computed. |
|
922 | 922 | |
|
923 | 923 | Returns |
|
924 | 924 | ------- |
|
925 | 925 | format_dict : dict |
|
926 | 926 | A dictionary of key/value pairs, one or each format that was |
|
927 | 927 | generated for the object. The keys are the format types, which |
|
928 | 928 | will usually be MIME type strings and the values and JSON'able |
|
929 | 929 | data structure containing the raw data for the representation in |
|
930 | 930 | that format. |
|
931 | 931 | include : list or tuple, optional |
|
932 | 932 | A list of format type strings (MIME types) to include in the |
|
933 | 933 | format data dict. If this is set *only* the format types included |
|
934 | 934 | in this list will be computed. |
|
935 | 935 | exclude : list or tuple, optional |
|
936 | 936 | A list of format type string (MIME types) to exclue in the format |
|
937 | 937 | data dict. If this is set all format types will be computed, |
|
938 | 938 | except for those included in this argument. |
|
939 | 939 | """ |
|
940 | 940 | from IPython.core.interactiveshell import InteractiveShell |
|
941 | 941 | |
|
942 | 942 | return InteractiveShell.instance().display_formatter.format( |
|
943 | 943 | obj, |
|
944 | 944 | include, |
|
945 | 945 | exclude |
|
946 | 946 | ) |
|
947 | 947 |
@@ -1,910 +1,910 b'' | |||
|
1 | 1 | """ History related magics and functionality """ |
|
2 | 2 | |
|
3 | 3 | # Copyright (c) IPython Development Team. |
|
4 | 4 | # Distributed under the terms of the Modified BSD License. |
|
5 | 5 | |
|
6 | 6 | |
|
7 | 7 | import atexit |
|
8 | 8 | import datetime |
|
9 | 9 | import os |
|
10 | 10 | import re |
|
11 | 11 | try: |
|
12 | 12 | import sqlite3 |
|
13 | 13 | except ImportError: |
|
14 | 14 | try: |
|
15 | 15 | from pysqlite2 import dbapi2 as sqlite3 |
|
16 | 16 | except ImportError: |
|
17 | 17 | sqlite3 = None |
|
18 | 18 | import threading |
|
19 | 19 | |
|
20 | 20 | from traitlets.config.configurable import LoggingConfigurable |
|
21 | 21 | from decorator import decorator |
|
22 | 22 | from IPython.utils.decorators import undoc |
|
23 | 23 | from IPython.utils.path import locate_profile |
|
24 | 24 | from IPython.utils import py3compat |
|
25 | 25 | from traitlets import ( |
|
26 | 26 | Any, Bool, Dict, Instance, Integer, List, Unicode, TraitError, |
|
27 | 27 | default, observe, |
|
28 | 28 | ) |
|
29 | 29 | from warnings import warn |
|
30 | 30 | |
|
31 | 31 | #----------------------------------------------------------------------------- |
|
32 | 32 | # Classes and functions |
|
33 | 33 | #----------------------------------------------------------------------------- |
|
34 | 34 | |
|
35 | 35 | @undoc |
|
36 | 36 | class DummyDB(object): |
|
37 | 37 | """Dummy DB that will act as a black hole for history. |
|
38 | 38 | |
|
39 | 39 | Only used in the absence of sqlite""" |
|
40 | 40 | def execute(*args, **kwargs): |
|
41 | 41 | return [] |
|
42 | 42 | |
|
43 | 43 | def commit(self, *args, **kwargs): |
|
44 | 44 | pass |
|
45 | 45 | |
|
46 | 46 | def __enter__(self, *args, **kwargs): |
|
47 | 47 | pass |
|
48 | 48 | |
|
49 | 49 | def __exit__(self, *args, **kwargs): |
|
50 | 50 | pass |
|
51 | 51 | |
|
52 | 52 | |
|
53 | 53 | @decorator |
|
54 | 54 | def needs_sqlite(f, self, *a, **kw): |
|
55 | 55 | """Decorator: return an empty list in the absence of sqlite.""" |
|
56 | 56 | if sqlite3 is None or not self.enabled: |
|
57 | 57 | return [] |
|
58 | 58 | else: |
|
59 | 59 | return f(self, *a, **kw) |
|
60 | 60 | |
|
61 | 61 | |
|
62 | 62 | if sqlite3 is not None: |
|
63 | 63 | DatabaseError = sqlite3.DatabaseError |
|
64 | 64 | OperationalError = sqlite3.OperationalError |
|
65 | 65 | else: |
|
66 | 66 | @undoc |
|
67 | 67 | class DatabaseError(Exception): |
|
68 | 68 | "Dummy exception when sqlite could not be imported. Should never occur." |
|
69 | 69 | |
|
70 | 70 | @undoc |
|
71 | 71 | class OperationalError(Exception): |
|
72 | 72 | "Dummy exception when sqlite could not be imported. Should never occur." |
|
73 | 73 | |
|
74 | 74 | # use 16kB as threshold for whether a corrupt history db should be saved |
|
75 | 75 | # that should be at least 100 entries or so |
|
76 | 76 | _SAVE_DB_SIZE = 16384 |
|
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 | We avoid clobbering larger databases because this may be triggered due to filesystem issues, |
|
85 | 85 | not just a corrupt file. |
|
86 | 86 | """ |
|
87 | 87 | try: |
|
88 | 88 | return f(self, *a, **kw) |
|
89 | 89 | except (DatabaseError, OperationalError) as e: |
|
90 | 90 | self._corrupt_db_counter += 1 |
|
91 | 91 | self.log.error("Failed to open SQLite history %s (%s).", self.hist_file, e) |
|
92 | 92 | if self.hist_file != ':memory:': |
|
93 | 93 | if self._corrupt_db_counter > self._corrupt_db_limit: |
|
94 | 94 | self.hist_file = ':memory:' |
|
95 | 95 | self.log.error("Failed to load history too many times, history will not be saved.") |
|
96 | 96 | elif os.path.isfile(self.hist_file): |
|
97 | 97 | # move the file out of the way |
|
98 | 98 | base, ext = os.path.splitext(self.hist_file) |
|
99 | 99 | size = os.stat(self.hist_file).st_size |
|
100 | 100 | if size >= _SAVE_DB_SIZE: |
|
101 | 101 | # if there's significant content, avoid clobbering |
|
102 | 102 | now = datetime.datetime.now().isoformat().replace(':', '.') |
|
103 | 103 | newpath = base + '-corrupt-' + now + ext |
|
104 | 104 | # don't clobber previous corrupt backups |
|
105 | 105 | for i in range(100): |
|
106 | 106 | if not os.path.isfile(newpath): |
|
107 | 107 | break |
|
108 | 108 | else: |
|
109 | 109 | newpath = base + '-corrupt-' + now + (u'-%i' % i) + ext |
|
110 | 110 | else: |
|
111 | 111 | # not much content, possibly empty; don't worry about clobbering |
|
112 | 112 | # maybe we should just delete it? |
|
113 | 113 | newpath = base + '-corrupt' + ext |
|
114 | 114 | os.rename(self.hist_file, newpath) |
|
115 | 115 | self.log.error("History file was moved to %s and a new file created.", newpath) |
|
116 | 116 | self.init_db() |
|
117 | 117 | return [] |
|
118 | 118 | else: |
|
119 | 119 | # Failed with :memory:, something serious is wrong |
|
120 | 120 | raise |
|
121 | 121 | |
|
122 | 122 | class HistoryAccessorBase(LoggingConfigurable): |
|
123 | 123 | """An abstract class for History Accessors """ |
|
124 | 124 | |
|
125 | 125 | def get_tail(self, n=10, raw=True, output=False, include_latest=False): |
|
126 | 126 | raise NotImplementedError |
|
127 | 127 | |
|
128 | 128 | def search(self, pattern="*", raw=True, search_raw=True, |
|
129 | 129 | output=False, n=None, unique=False): |
|
130 | 130 | raise NotImplementedError |
|
131 | 131 | |
|
132 | 132 | def get_range(self, session, start=1, stop=None, raw=True,output=False): |
|
133 | 133 | raise NotImplementedError |
|
134 | 134 | |
|
135 | 135 | def get_range_by_str(self, rangestr, raw=True, output=False): |
|
136 | 136 | raise NotImplementedError |
|
137 | 137 | |
|
138 | 138 | |
|
139 | 139 | class HistoryAccessor(HistoryAccessorBase): |
|
140 | 140 | """Access the history database without adding to it. |
|
141 | 141 | |
|
142 | 142 | This is intended for use by standalone history tools. IPython shells use |
|
143 | 143 | HistoryManager, below, which is a subclass of this.""" |
|
144 | 144 | |
|
145 | 145 | # counter for init_db retries, so we don't keep trying over and over |
|
146 | 146 | _corrupt_db_counter = 0 |
|
147 | 147 | # after two failures, fallback on :memory: |
|
148 | 148 | _corrupt_db_limit = 2 |
|
149 | 149 | |
|
150 | 150 | # String holding the path to the history file |
|
151 | 151 | hist_file = Unicode( |
|
152 | 152 | help="""Path to file to use for SQLite history database. |
|
153 | 153 | |
|
154 | 154 | By default, IPython will put the history database in the IPython |
|
155 | 155 | profile directory. If you would rather share one history among |
|
156 | 156 | profiles, you can set this value in each, so that they are consistent. |
|
157 | 157 | |
|
158 | 158 | Due to an issue with fcntl, SQLite is known to misbehave on some NFS |
|
159 | 159 | mounts. If you see IPython hanging, try setting this to something on a |
|
160 | 160 | local disk, e.g:: |
|
161 | 161 | |
|
162 | 162 | ipython --HistoryManager.hist_file=/tmp/ipython_hist.sqlite |
|
163 | 163 | |
|
164 | 164 | you can also use the specific value `:memory:` (including the colon |
|
165 | 165 | at both end but not the back ticks), to avoid creating an history file. |
|
166 | 166 | |
|
167 | 167 | """).tag(config=True) |
|
168 | 168 | |
|
169 | 169 | enabled = Bool(True, |
|
170 | 170 | help="""enable the SQLite history |
|
171 | 171 | |
|
172 | 172 | set enabled=False to disable the SQLite history, |
|
173 | 173 | in which case there will be no stored history, no SQLite connection, |
|
174 | 174 | and no background saving thread. This may be necessary in some |
|
175 | 175 | threaded environments where IPython is embedded. |
|
176 | 176 | """ |
|
177 | 177 | ).tag(config=True) |
|
178 | 178 | |
|
179 | 179 | connection_options = Dict( |
|
180 | 180 | help="""Options for configuring the SQLite connection |
|
181 | 181 | |
|
182 | 182 | These options are passed as keyword args to sqlite3.connect |
|
183 | 183 | when establishing database conenctions. |
|
184 | 184 | """ |
|
185 | 185 | ).tag(config=True) |
|
186 | 186 | |
|
187 | 187 | # The SQLite database |
|
188 | 188 | db = Any() |
|
189 | 189 | @observe('db') |
|
190 | 190 | def _db_changed(self, change): |
|
191 | 191 | """validate the db, since it can be an Instance of two different types""" |
|
192 | 192 | new = change['new'] |
|
193 | 193 | connection_types = (DummyDB,) |
|
194 | 194 | if sqlite3 is not None: |
|
195 | 195 | connection_types = (DummyDB, sqlite3.Connection) |
|
196 | 196 | if not isinstance(new, connection_types): |
|
197 | 197 | msg = "%s.db must be sqlite3 Connection or DummyDB, not %r" % \ |
|
198 | 198 | (self.__class__.__name__, new) |
|
199 | 199 | raise TraitError(msg) |
|
200 | 200 | |
|
201 | 201 | def __init__(self, profile='default', hist_file=u'', **traits): |
|
202 | 202 | """Create a new history accessor. |
|
203 | 203 | |
|
204 | 204 | Parameters |
|
205 | 205 | ---------- |
|
206 | 206 | profile : str |
|
207 | 207 | The name of the profile from which to open history. |
|
208 | 208 | hist_file : str |
|
209 | 209 | Path to an SQLite history database stored by IPython. If specified, |
|
210 | 210 | hist_file overrides profile. |
|
211 | 211 | config : :class:`~traitlets.config.loader.Config` |
|
212 | 212 | Config object. hist_file can also be set through this. |
|
213 | 213 | """ |
|
214 | 214 | # We need a pointer back to the shell for various tasks. |
|
215 | 215 | super(HistoryAccessor, self).__init__(**traits) |
|
216 | 216 | # defer setting hist_file from kwarg until after init, |
|
217 | 217 | # otherwise the default kwarg value would clobber any value |
|
218 | 218 | # set by config |
|
219 | 219 | if hist_file: |
|
220 | 220 | self.hist_file = hist_file |
|
221 | 221 | |
|
222 | 222 | if self.hist_file == u'': |
|
223 | 223 | # No one has set the hist_file, yet. |
|
224 | 224 | self.hist_file = self._get_hist_file_name(profile) |
|
225 | 225 | |
|
226 | 226 | if sqlite3 is None and self.enabled: |
|
227 | 227 | warn("IPython History requires SQLite, your history will not be saved") |
|
228 | 228 | self.enabled = False |
|
229 | 229 | |
|
230 | 230 | self.init_db() |
|
231 | 231 | |
|
232 | 232 | def _get_hist_file_name(self, profile='default'): |
|
233 | 233 | """Find the history file for the given profile name. |
|
234 | 234 | |
|
235 | 235 | This is overridden by the HistoryManager subclass, to use the shell's |
|
236 | 236 | active profile. |
|
237 | 237 | |
|
238 | 238 | Parameters |
|
239 | 239 | ---------- |
|
240 | 240 | profile : str |
|
241 | 241 | The name of a profile which has a history file. |
|
242 | 242 | """ |
|
243 | 243 | return os.path.join(locate_profile(profile), 'history.sqlite') |
|
244 | 244 | |
|
245 | 245 | @catch_corrupt_db |
|
246 | 246 | def init_db(self): |
|
247 | 247 | """Connect to the database, and create tables if necessary.""" |
|
248 | 248 | if not self.enabled: |
|
249 | 249 | self.db = DummyDB() |
|
250 | 250 | return |
|
251 | 251 | |
|
252 | 252 | # use detect_types so that timestamps return datetime objects |
|
253 | 253 | kwargs = dict(detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES) |
|
254 | 254 | kwargs.update(self.connection_options) |
|
255 | 255 | self.db = sqlite3.connect(self.hist_file, **kwargs) |
|
256 | 256 | self.db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer |
|
257 | 257 | primary key autoincrement, start timestamp, |
|
258 | 258 | end timestamp, num_cmds integer, remark text)""") |
|
259 | 259 | self.db.execute("""CREATE TABLE IF NOT EXISTS history |
|
260 | 260 | (session integer, line integer, source text, source_raw text, |
|
261 | 261 | PRIMARY KEY (session, line))""") |
|
262 | 262 | # Output history is optional, but ensure the table's there so it can be |
|
263 | 263 | # enabled later. |
|
264 | 264 | self.db.execute("""CREATE TABLE IF NOT EXISTS output_history |
|
265 | 265 | (session integer, line integer, output text, |
|
266 | 266 | PRIMARY KEY (session, line))""") |
|
267 | 267 | self.db.commit() |
|
268 | 268 | # success! reset corrupt db count |
|
269 | 269 | self._corrupt_db_counter = 0 |
|
270 | 270 | |
|
271 | 271 | def writeout_cache(self): |
|
272 | 272 | """Overridden by HistoryManager to dump the cache before certain |
|
273 | 273 | database lookups.""" |
|
274 | 274 | pass |
|
275 | 275 | |
|
276 | 276 | ## ------------------------------- |
|
277 | 277 | ## Methods for retrieving history: |
|
278 | 278 | ## ------------------------------- |
|
279 | 279 | def _run_sql(self, sql, params, raw=True, output=False): |
|
280 | 280 | """Prepares and runs an SQL query for the history database. |
|
281 | 281 | |
|
282 | 282 | Parameters |
|
283 | 283 | ---------- |
|
284 | 284 | sql : str |
|
285 | 285 | Any filtering expressions to go after SELECT ... FROM ... |
|
286 | 286 | params : tuple |
|
287 | 287 | Parameters passed to the SQL query (to replace "?") |
|
288 | 288 | raw, output : bool |
|
289 | 289 | See :meth:`get_range` |
|
290 | 290 | |
|
291 | 291 | Returns |
|
292 | 292 | ------- |
|
293 | 293 | Tuples as :meth:`get_range` |
|
294 | 294 | """ |
|
295 | 295 | toget = 'source_raw' if raw else 'source' |
|
296 | 296 | sqlfrom = "history" |
|
297 | 297 | if output: |
|
298 | 298 | sqlfrom = "history LEFT JOIN output_history USING (session, line)" |
|
299 | 299 | toget = "history.%s, output_history.output" % toget |
|
300 | 300 | cur = self.db.execute("SELECT session, line, %s FROM %s " %\ |
|
301 | 301 | (toget, sqlfrom) + sql, params) |
|
302 | 302 | if output: # Regroup into 3-tuples, and parse JSON |
|
303 | 303 | return ((ses, lin, (inp, out)) for ses, lin, inp, out in cur) |
|
304 | 304 | return cur |
|
305 | 305 | |
|
306 | 306 | @needs_sqlite |
|
307 | 307 | @catch_corrupt_db |
|
308 | 308 | def get_session_info(self, session): |
|
309 | 309 | """Get info about a session. |
|
310 | 310 | |
|
311 | 311 | Parameters |
|
312 | 312 | ---------- |
|
313 | 313 | |
|
314 | 314 | session : int |
|
315 | 315 | Session number to retrieve. |
|
316 | 316 | |
|
317 | 317 | Returns |
|
318 | 318 | ------- |
|
319 | 319 | |
|
320 | 320 | session_id : int |
|
321 | 321 | Session ID number |
|
322 | 322 | start : datetime |
|
323 | 323 | Timestamp for the start of the session. |
|
324 | 324 | end : datetime |
|
325 | 325 | Timestamp for the end of the session, or None if IPython crashed. |
|
326 | 326 | num_cmds : int |
|
327 | 327 | Number of commands run, or None if IPython crashed. |
|
328 | 328 | remark : unicode |
|
329 | 329 | A manually set description. |
|
330 | 330 | """ |
|
331 | 331 | query = "SELECT * from sessions where session == ?" |
|
332 | 332 | return self.db.execute(query, (session,)).fetchone() |
|
333 | 333 | |
|
334 | 334 | @catch_corrupt_db |
|
335 | 335 | def get_last_session_id(self): |
|
336 | 336 | """Get the last session ID currently in the database. |
|
337 | 337 | |
|
338 | 338 | Within IPython, this should be the same as the value stored in |
|
339 | 339 | :attr:`HistoryManager.session_number`. |
|
340 | 340 | """ |
|
341 | 341 | for record in self.get_tail(n=1, include_latest=True): |
|
342 | 342 | return record[0] |
|
343 | 343 | |
|
344 | 344 | @catch_corrupt_db |
|
345 | 345 | def get_tail(self, n=10, raw=True, output=False, include_latest=False): |
|
346 | 346 | """Get the last n lines from the history database. |
|
347 | 347 | |
|
348 | 348 | Parameters |
|
349 | 349 | ---------- |
|
350 | 350 | n : int |
|
351 | 351 | The number of lines to get |
|
352 | 352 | raw, output : bool |
|
353 | 353 | See :meth:`get_range` |
|
354 | 354 | include_latest : bool |
|
355 | 355 | If False (default), n+1 lines are fetched, and the latest one |
|
356 | 356 | is discarded. This is intended to be used where the function |
|
357 | 357 | is called by a user command, which it should not return. |
|
358 | 358 | |
|
359 | 359 | Returns |
|
360 | 360 | ------- |
|
361 | 361 | Tuples as :meth:`get_range` |
|
362 | 362 | """ |
|
363 | 363 | self.writeout_cache() |
|
364 | 364 | if not include_latest: |
|
365 | 365 | n += 1 |
|
366 | 366 | cur = self._run_sql("ORDER BY session DESC, line DESC LIMIT ?", |
|
367 | 367 | (n,), raw=raw, output=output) |
|
368 | 368 | if not include_latest: |
|
369 | 369 | return reversed(list(cur)[1:]) |
|
370 | 370 | return reversed(list(cur)) |
|
371 | 371 | |
|
372 | 372 | @catch_corrupt_db |
|
373 | 373 | def search(self, pattern="*", raw=True, search_raw=True, |
|
374 | 374 | output=False, n=None, unique=False): |
|
375 | 375 | """Search the database using unix glob-style matching (wildcards |
|
376 | 376 | * and ?). |
|
377 | 377 | |
|
378 | 378 | Parameters |
|
379 | 379 | ---------- |
|
380 | 380 | pattern : str |
|
381 | 381 | The wildcarded pattern to match when searching |
|
382 | 382 | search_raw : bool |
|
383 | 383 | If True, search the raw input, otherwise, the parsed input |
|
384 | 384 | raw, output : bool |
|
385 | 385 | See :meth:`get_range` |
|
386 | 386 | n : None or int |
|
387 | 387 | If an integer is given, it defines the limit of |
|
388 | 388 | returned entries. |
|
389 | 389 | unique : bool |
|
390 | 390 | When it is true, return only unique entries. |
|
391 | 391 | |
|
392 | 392 | Returns |
|
393 | 393 | ------- |
|
394 | 394 | Tuples as :meth:`get_range` |
|
395 | 395 | """ |
|
396 | 396 | tosearch = "source_raw" if search_raw else "source" |
|
397 | 397 | if output: |
|
398 | 398 | tosearch = "history." + tosearch |
|
399 | 399 | self.writeout_cache() |
|
400 | 400 | sqlform = "WHERE %s GLOB ?" % tosearch |
|
401 | 401 | params = (pattern,) |
|
402 | 402 | if unique: |
|
403 | 403 | sqlform += ' GROUP BY {0}'.format(tosearch) |
|
404 | 404 | if n is not None: |
|
405 | 405 | sqlform += " ORDER BY session DESC, line DESC LIMIT ?" |
|
406 | 406 | params += (n,) |
|
407 | 407 | elif unique: |
|
408 | 408 | sqlform += " ORDER BY session, line" |
|
409 | 409 | cur = self._run_sql(sqlform, params, raw=raw, output=output) |
|
410 | 410 | if n is not None: |
|
411 | 411 | return reversed(list(cur)) |
|
412 | 412 | return cur |
|
413 | 413 | |
|
414 | 414 | @catch_corrupt_db |
|
415 | 415 | def get_range(self, session, start=1, stop=None, raw=True,output=False): |
|
416 | 416 | """Retrieve input by session. |
|
417 | 417 | |
|
418 | 418 | Parameters |
|
419 | 419 | ---------- |
|
420 | 420 | session : int |
|
421 | 421 | Session number to retrieve. |
|
422 | 422 | start : int |
|
423 | 423 | First line to retrieve. |
|
424 | 424 | stop : int |
|
425 | 425 | End of line range (excluded from output itself). If None, retrieve |
|
426 | 426 | to the end of the session. |
|
427 | 427 | raw : bool |
|
428 | 428 | If True, return untranslated input |
|
429 | 429 | output : bool |
|
430 | 430 | If True, attempt to include output. This will be 'real' Python |
|
431 | 431 | objects for the current session, or text reprs from previous |
|
432 | 432 | sessions if db_log_output was enabled at the time. Where no output |
|
433 | 433 | is found, None is used. |
|
434 | 434 | |
|
435 | 435 | Returns |
|
436 | 436 | ------- |
|
437 | 437 | entries |
|
438 | 438 | An iterator over the desired lines. Each line is a 3-tuple, either |
|
439 | 439 | (session, line, input) if output is False, or |
|
440 | 440 | (session, line, (input, output)) if output is True. |
|
441 | 441 | """ |
|
442 | 442 | if stop: |
|
443 | 443 | lineclause = "line >= ? AND line < ?" |
|
444 | 444 | params = (session, start, stop) |
|
445 | 445 | else: |
|
446 | 446 | lineclause = "line>=?" |
|
447 | 447 | params = (session, start) |
|
448 | 448 | |
|
449 | 449 | return self._run_sql("WHERE session==? AND %s" % lineclause, |
|
450 | 450 | params, raw=raw, output=output) |
|
451 | 451 | |
|
452 | 452 | def get_range_by_str(self, rangestr, raw=True, output=False): |
|
453 | 453 | """Get lines of history from a string of ranges, as used by magic |
|
454 | 454 | commands %hist, %save, %macro, etc. |
|
455 | 455 | |
|
456 | 456 | Parameters |
|
457 | 457 | ---------- |
|
458 | 458 | rangestr : str |
|
459 | 459 | A string specifying ranges, e.g. "5 ~2/1-4". See |
|
460 | 460 | :func:`magic_history` for full details. |
|
461 | 461 | raw, output : bool |
|
462 | 462 | As :meth:`get_range` |
|
463 | 463 | |
|
464 | 464 | Returns |
|
465 | 465 | ------- |
|
466 | 466 | Tuples as :meth:`get_range` |
|
467 | 467 | """ |
|
468 | 468 | for sess, s, e in extract_hist_ranges(rangestr): |
|
469 | 469 | for line in self.get_range(sess, s, e, raw=raw, output=output): |
|
470 | 470 | yield line |
|
471 | 471 | |
|
472 | 472 | |
|
473 | 473 | class HistoryManager(HistoryAccessor): |
|
474 | 474 | """A class to organize all history-related functionality in one place. |
|
475 | 475 | """ |
|
476 | 476 | # Public interface |
|
477 | 477 | |
|
478 | 478 | # An instance of the IPython shell we are attached to |
|
479 | 479 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', |
|
480 | 480 | allow_none=True) |
|
481 | 481 | # Lists to hold processed and raw history. These start with a blank entry |
|
482 | 482 | # so that we can index them starting from 1 |
|
483 | 483 | input_hist_parsed = List([""]) |
|
484 | 484 | input_hist_raw = List([""]) |
|
485 | 485 | # A list of directories visited during session |
|
486 | 486 | dir_hist = List() |
|
487 | 487 | @default('dir_hist') |
|
488 | 488 | def _dir_hist_default(self): |
|
489 | 489 | try: |
|
490 |
return [ |
|
|
490 | return [os.getcwd()] | |
|
491 | 491 | except OSError: |
|
492 | 492 | return [] |
|
493 | 493 | |
|
494 | 494 | # A dict of output history, keyed with ints from the shell's |
|
495 | 495 | # execution count. |
|
496 | 496 | output_hist = Dict() |
|
497 | 497 | # The text/plain repr of outputs. |
|
498 | 498 | output_hist_reprs = Dict() |
|
499 | 499 | |
|
500 | 500 | # The number of the current session in the history database |
|
501 | 501 | session_number = Integer() |
|
502 | 502 | |
|
503 | 503 | db_log_output = Bool(False, |
|
504 | 504 | help="Should the history database include output? (default: no)" |
|
505 | 505 | ).tag(config=True) |
|
506 | 506 | db_cache_size = Integer(0, |
|
507 | 507 | help="Write to database every x commands (higher values save disk access & power).\n" |
|
508 | 508 | "Values of 1 or less effectively disable caching." |
|
509 | 509 | ).tag(config=True) |
|
510 | 510 | # The input and output caches |
|
511 | 511 | db_input_cache = List() |
|
512 | 512 | db_output_cache = List() |
|
513 | 513 | |
|
514 | 514 | # History saving in separate thread |
|
515 | 515 | save_thread = Instance('IPython.core.history.HistorySavingThread', |
|
516 | 516 | allow_none=True) |
|
517 | 517 | try: # Event is a function returning an instance of _Event... |
|
518 | 518 | save_flag = Instance(threading._Event, allow_none=True) |
|
519 | 519 | except AttributeError: # ...until Python 3.3, when it's a class. |
|
520 | 520 | save_flag = Instance(threading.Event, allow_none=True) |
|
521 | 521 | |
|
522 | 522 | # Private interface |
|
523 | 523 | # Variables used to store the three last inputs from the user. On each new |
|
524 | 524 | # history update, we populate the user's namespace with these, shifted as |
|
525 | 525 | # necessary. |
|
526 | 526 | _i00 = Unicode(u'') |
|
527 | 527 | _i = Unicode(u'') |
|
528 | 528 | _ii = Unicode(u'') |
|
529 | 529 | _iii = Unicode(u'') |
|
530 | 530 | |
|
531 | 531 | # A regex matching all forms of the exit command, so that we don't store |
|
532 | 532 | # them in the history (it's annoying to rewind the first entry and land on |
|
533 | 533 | # an exit call). |
|
534 | 534 | _exit_re = re.compile(r"(exit|quit)(\s*\(.*\))?$") |
|
535 | 535 | |
|
536 | 536 | def __init__(self, shell=None, config=None, **traits): |
|
537 | 537 | """Create a new history manager associated with a shell instance. |
|
538 | 538 | """ |
|
539 | 539 | # We need a pointer back to the shell for various tasks. |
|
540 | 540 | super(HistoryManager, self).__init__(shell=shell, config=config, |
|
541 | 541 | **traits) |
|
542 | 542 | self.save_flag = threading.Event() |
|
543 | 543 | self.db_input_cache_lock = threading.Lock() |
|
544 | 544 | self.db_output_cache_lock = threading.Lock() |
|
545 | 545 | |
|
546 | 546 | try: |
|
547 | 547 | self.new_session() |
|
548 | 548 | except OperationalError: |
|
549 | 549 | self.log.error("Failed to create history session in %s. History will not be saved.", |
|
550 | 550 | self.hist_file, exc_info=True) |
|
551 | 551 | self.hist_file = ':memory:' |
|
552 | 552 | |
|
553 | 553 | if self.enabled and self.hist_file != ':memory:': |
|
554 | 554 | self.save_thread = HistorySavingThread(self) |
|
555 | 555 | self.save_thread.start() |
|
556 | 556 | |
|
557 | 557 | def _get_hist_file_name(self, profile=None): |
|
558 | 558 | """Get default history file name based on the Shell's profile. |
|
559 | 559 | |
|
560 | 560 | The profile parameter is ignored, but must exist for compatibility with |
|
561 | 561 | the parent class.""" |
|
562 | 562 | profile_dir = self.shell.profile_dir.location |
|
563 | 563 | return os.path.join(profile_dir, 'history.sqlite') |
|
564 | 564 | |
|
565 | 565 | @needs_sqlite |
|
566 | 566 | def new_session(self, conn=None): |
|
567 | 567 | """Get a new session number.""" |
|
568 | 568 | if conn is None: |
|
569 | 569 | conn = self.db |
|
570 | 570 | |
|
571 | 571 | with conn: |
|
572 | 572 | cur = conn.execute("""INSERT INTO sessions VALUES (NULL, ?, NULL, |
|
573 | 573 | NULL, "") """, (datetime.datetime.now(),)) |
|
574 | 574 | self.session_number = cur.lastrowid |
|
575 | 575 | |
|
576 | 576 | def end_session(self): |
|
577 | 577 | """Close the database session, filling in the end time and line count.""" |
|
578 | 578 | self.writeout_cache() |
|
579 | 579 | with self.db: |
|
580 | 580 | self.db.execute("""UPDATE sessions SET end=?, num_cmds=? WHERE |
|
581 | 581 | session==?""", (datetime.datetime.now(), |
|
582 | 582 | len(self.input_hist_parsed)-1, self.session_number)) |
|
583 | 583 | self.session_number = 0 |
|
584 | 584 | |
|
585 | 585 | def name_session(self, name): |
|
586 | 586 | """Give the current session a name in the history database.""" |
|
587 | 587 | with self.db: |
|
588 | 588 | self.db.execute("UPDATE sessions SET remark=? WHERE session==?", |
|
589 | 589 | (name, self.session_number)) |
|
590 | 590 | |
|
591 | 591 | def reset(self, new_session=True): |
|
592 | 592 | """Clear the session history, releasing all object references, and |
|
593 | 593 | optionally open a new session.""" |
|
594 | 594 | self.output_hist.clear() |
|
595 | 595 | # The directory history can't be completely empty |
|
596 |
self.dir_hist[:] = [ |
|
|
596 | self.dir_hist[:] = [os.getcwd()] | |
|
597 | 597 | |
|
598 | 598 | if new_session: |
|
599 | 599 | if self.session_number: |
|
600 | 600 | self.end_session() |
|
601 | 601 | self.input_hist_parsed[:] = [""] |
|
602 | 602 | self.input_hist_raw[:] = [""] |
|
603 | 603 | self.new_session() |
|
604 | 604 | |
|
605 | 605 | # ------------------------------ |
|
606 | 606 | # Methods for retrieving history |
|
607 | 607 | # ------------------------------ |
|
608 | 608 | def get_session_info(self, session=0): |
|
609 | 609 | """Get info about a session. |
|
610 | 610 | |
|
611 | 611 | Parameters |
|
612 | 612 | ---------- |
|
613 | 613 | |
|
614 | 614 | session : int |
|
615 | 615 | Session number to retrieve. The current session is 0, and negative |
|
616 | 616 | numbers count back from current session, so -1 is the previous session. |
|
617 | 617 | |
|
618 | 618 | Returns |
|
619 | 619 | ------- |
|
620 | 620 | |
|
621 | 621 | session_id : int |
|
622 | 622 | Session ID number |
|
623 | 623 | start : datetime |
|
624 | 624 | Timestamp for the start of the session. |
|
625 | 625 | end : datetime |
|
626 | 626 | Timestamp for the end of the session, or None if IPython crashed. |
|
627 | 627 | num_cmds : int |
|
628 | 628 | Number of commands run, or None if IPython crashed. |
|
629 | 629 | remark : unicode |
|
630 | 630 | A manually set description. |
|
631 | 631 | """ |
|
632 | 632 | if session <= 0: |
|
633 | 633 | session += self.session_number |
|
634 | 634 | |
|
635 | 635 | return super(HistoryManager, self).get_session_info(session=session) |
|
636 | 636 | |
|
637 | 637 | def _get_range_session(self, start=1, stop=None, raw=True, output=False): |
|
638 | 638 | """Get input and output history from the current session. Called by |
|
639 | 639 | get_range, and takes similar parameters.""" |
|
640 | 640 | input_hist = self.input_hist_raw if raw else self.input_hist_parsed |
|
641 | 641 | |
|
642 | 642 | n = len(input_hist) |
|
643 | 643 | if start < 0: |
|
644 | 644 | start += n |
|
645 | 645 | if not stop or (stop > n): |
|
646 | 646 | stop = n |
|
647 | 647 | elif stop < 0: |
|
648 | 648 | stop += n |
|
649 | 649 | |
|
650 | 650 | for i in range(start, stop): |
|
651 | 651 | if output: |
|
652 | 652 | line = (input_hist[i], self.output_hist_reprs.get(i)) |
|
653 | 653 | else: |
|
654 | 654 | line = input_hist[i] |
|
655 | 655 | yield (0, i, line) |
|
656 | 656 | |
|
657 | 657 | def get_range(self, session=0, start=1, stop=None, raw=True,output=False): |
|
658 | 658 | """Retrieve input by session. |
|
659 | 659 | |
|
660 | 660 | Parameters |
|
661 | 661 | ---------- |
|
662 | 662 | session : int |
|
663 | 663 | Session number to retrieve. The current session is 0, and negative |
|
664 | 664 | numbers count back from current session, so -1 is previous session. |
|
665 | 665 | start : int |
|
666 | 666 | First line to retrieve. |
|
667 | 667 | stop : int |
|
668 | 668 | End of line range (excluded from output itself). If None, retrieve |
|
669 | 669 | to the end of the session. |
|
670 | 670 | raw : bool |
|
671 | 671 | If True, return untranslated input |
|
672 | 672 | output : bool |
|
673 | 673 | If True, attempt to include output. This will be 'real' Python |
|
674 | 674 | objects for the current session, or text reprs from previous |
|
675 | 675 | sessions if db_log_output was enabled at the time. Where no output |
|
676 | 676 | is found, None is used. |
|
677 | 677 | |
|
678 | 678 | Returns |
|
679 | 679 | ------- |
|
680 | 680 | entries |
|
681 | 681 | An iterator over the desired lines. Each line is a 3-tuple, either |
|
682 | 682 | (session, line, input) if output is False, or |
|
683 | 683 | (session, line, (input, output)) if output is True. |
|
684 | 684 | """ |
|
685 | 685 | if session <= 0: |
|
686 | 686 | session += self.session_number |
|
687 | 687 | if session==self.session_number: # Current session |
|
688 | 688 | return self._get_range_session(start, stop, raw, output) |
|
689 | 689 | return super(HistoryManager, self).get_range(session, start, stop, raw, |
|
690 | 690 | output) |
|
691 | 691 | |
|
692 | 692 | ## ---------------------------- |
|
693 | 693 | ## Methods for storing history: |
|
694 | 694 | ## ---------------------------- |
|
695 | 695 | def store_inputs(self, line_num, source, source_raw=None): |
|
696 | 696 | """Store source and raw input in history and create input cache |
|
697 | 697 | variables ``_i*``. |
|
698 | 698 | |
|
699 | 699 | Parameters |
|
700 | 700 | ---------- |
|
701 | 701 | line_num : int |
|
702 | 702 | The prompt number of this input. |
|
703 | 703 | |
|
704 | 704 | source : str |
|
705 | 705 | Python input. |
|
706 | 706 | |
|
707 | 707 | source_raw : str, optional |
|
708 | 708 | If given, this is the raw input without any IPython transformations |
|
709 | 709 | applied to it. If not given, ``source`` is used. |
|
710 | 710 | """ |
|
711 | 711 | if source_raw is None: |
|
712 | 712 | source_raw = source |
|
713 | 713 | source = source.rstrip('\n') |
|
714 | 714 | source_raw = source_raw.rstrip('\n') |
|
715 | 715 | |
|
716 | 716 | # do not store exit/quit commands |
|
717 | 717 | if self._exit_re.match(source_raw.strip()): |
|
718 | 718 | return |
|
719 | 719 | |
|
720 | 720 | self.input_hist_parsed.append(source) |
|
721 | 721 | self.input_hist_raw.append(source_raw) |
|
722 | 722 | |
|
723 | 723 | with self.db_input_cache_lock: |
|
724 | 724 | self.db_input_cache.append((line_num, source, source_raw)) |
|
725 | 725 | # Trigger to flush cache and write to DB. |
|
726 | 726 | if len(self.db_input_cache) >= self.db_cache_size: |
|
727 | 727 | self.save_flag.set() |
|
728 | 728 | |
|
729 | 729 | # update the auto _i variables |
|
730 | 730 | self._iii = self._ii |
|
731 | 731 | self._ii = self._i |
|
732 | 732 | self._i = self._i00 |
|
733 | 733 | self._i00 = source_raw |
|
734 | 734 | |
|
735 | 735 | # hackish access to user namespace to create _i1,_i2... dynamically |
|
736 | 736 | new_i = '_i%s' % line_num |
|
737 | 737 | to_main = {'_i': self._i, |
|
738 | 738 | '_ii': self._ii, |
|
739 | 739 | '_iii': self._iii, |
|
740 | 740 | new_i : self._i00 } |
|
741 | 741 | |
|
742 | 742 | if self.shell is not None: |
|
743 | 743 | self.shell.push(to_main, interactive=False) |
|
744 | 744 | |
|
745 | 745 | def store_output(self, line_num): |
|
746 | 746 | """If database output logging is enabled, this saves all the |
|
747 | 747 | outputs from the indicated prompt number to the database. It's |
|
748 | 748 | called by run_cell after code has been executed. |
|
749 | 749 | |
|
750 | 750 | Parameters |
|
751 | 751 | ---------- |
|
752 | 752 | line_num : int |
|
753 | 753 | The line number from which to save outputs |
|
754 | 754 | """ |
|
755 | 755 | if (not self.db_log_output) or (line_num not in self.output_hist_reprs): |
|
756 | 756 | return |
|
757 | 757 | output = self.output_hist_reprs[line_num] |
|
758 | 758 | |
|
759 | 759 | with self.db_output_cache_lock: |
|
760 | 760 | self.db_output_cache.append((line_num, output)) |
|
761 | 761 | if self.db_cache_size <= 1: |
|
762 | 762 | self.save_flag.set() |
|
763 | 763 | |
|
764 | 764 | def _writeout_input_cache(self, conn): |
|
765 | 765 | with conn: |
|
766 | 766 | for line in self.db_input_cache: |
|
767 | 767 | conn.execute("INSERT INTO history VALUES (?, ?, ?, ?)", |
|
768 | 768 | (self.session_number,)+line) |
|
769 | 769 | |
|
770 | 770 | def _writeout_output_cache(self, conn): |
|
771 | 771 | with conn: |
|
772 | 772 | for line in self.db_output_cache: |
|
773 | 773 | conn.execute("INSERT INTO output_history VALUES (?, ?, ?)", |
|
774 | 774 | (self.session_number,)+line) |
|
775 | 775 | |
|
776 | 776 | @needs_sqlite |
|
777 | 777 | def writeout_cache(self, conn=None): |
|
778 | 778 | """Write any entries in the cache to the database.""" |
|
779 | 779 | if conn is None: |
|
780 | 780 | conn = self.db |
|
781 | 781 | |
|
782 | 782 | with self.db_input_cache_lock: |
|
783 | 783 | try: |
|
784 | 784 | self._writeout_input_cache(conn) |
|
785 | 785 | except sqlite3.IntegrityError: |
|
786 | 786 | self.new_session(conn) |
|
787 | 787 | print("ERROR! Session/line number was not unique in", |
|
788 | 788 | "database. History logging moved to new session", |
|
789 | 789 | self.session_number) |
|
790 | 790 | try: |
|
791 | 791 | # Try writing to the new session. If this fails, don't |
|
792 | 792 | # recurse |
|
793 | 793 | self._writeout_input_cache(conn) |
|
794 | 794 | except sqlite3.IntegrityError: |
|
795 | 795 | pass |
|
796 | 796 | finally: |
|
797 | 797 | self.db_input_cache = [] |
|
798 | 798 | |
|
799 | 799 | with self.db_output_cache_lock: |
|
800 | 800 | try: |
|
801 | 801 | self._writeout_output_cache(conn) |
|
802 | 802 | except sqlite3.IntegrityError: |
|
803 | 803 | print("!! Session/line number for output was not unique", |
|
804 | 804 | "in database. Output will not be stored.") |
|
805 | 805 | finally: |
|
806 | 806 | self.db_output_cache = [] |
|
807 | 807 | |
|
808 | 808 | |
|
809 | 809 | class HistorySavingThread(threading.Thread): |
|
810 | 810 | """This thread takes care of writing history to the database, so that |
|
811 | 811 | the UI isn't held up while that happens. |
|
812 | 812 | |
|
813 | 813 | It waits for the HistoryManager's save_flag to be set, then writes out |
|
814 | 814 | the history cache. The main thread is responsible for setting the flag when |
|
815 | 815 | the cache size reaches a defined threshold.""" |
|
816 | 816 | daemon = True |
|
817 | 817 | stop_now = False |
|
818 | 818 | enabled = True |
|
819 | 819 | def __init__(self, history_manager): |
|
820 | 820 | super(HistorySavingThread, self).__init__(name="IPythonHistorySavingThread") |
|
821 | 821 | self.history_manager = history_manager |
|
822 | 822 | self.enabled = history_manager.enabled |
|
823 | 823 | atexit.register(self.stop) |
|
824 | 824 | |
|
825 | 825 | @needs_sqlite |
|
826 | 826 | def run(self): |
|
827 | 827 | # We need a separate db connection per thread: |
|
828 | 828 | try: |
|
829 | 829 | self.db = sqlite3.connect(self.history_manager.hist_file, |
|
830 | 830 | **self.history_manager.connection_options |
|
831 | 831 | ) |
|
832 | 832 | while True: |
|
833 | 833 | self.history_manager.save_flag.wait() |
|
834 | 834 | if self.stop_now: |
|
835 | 835 | self.db.close() |
|
836 | 836 | return |
|
837 | 837 | self.history_manager.save_flag.clear() |
|
838 | 838 | self.history_manager.writeout_cache(self.db) |
|
839 | 839 | except Exception as e: |
|
840 | 840 | print(("The history saving thread hit an unexpected error (%s)." |
|
841 | 841 | "History will not be written to the database.") % repr(e)) |
|
842 | 842 | |
|
843 | 843 | def stop(self): |
|
844 | 844 | """This can be called from the main thread to safely stop this thread. |
|
845 | 845 | |
|
846 | 846 | Note that it does not attempt to write out remaining history before |
|
847 | 847 | exiting. That should be done by calling the HistoryManager's |
|
848 | 848 | end_session method.""" |
|
849 | 849 | self.stop_now = True |
|
850 | 850 | self.history_manager.save_flag.set() |
|
851 | 851 | self.join() |
|
852 | 852 | |
|
853 | 853 | |
|
854 | 854 | # To match, e.g. ~5/8-~2/3 |
|
855 | 855 | range_re = re.compile(r""" |
|
856 | 856 | ((?P<startsess>~?\d+)/)? |
|
857 | 857 | (?P<start>\d+)? |
|
858 | 858 | ((?P<sep>[\-:]) |
|
859 | 859 | ((?P<endsess>~?\d+)/)? |
|
860 | 860 | (?P<end>\d+))? |
|
861 | 861 | $""", re.VERBOSE) |
|
862 | 862 | |
|
863 | 863 | |
|
864 | 864 | def extract_hist_ranges(ranges_str): |
|
865 | 865 | """Turn a string of history ranges into 3-tuples of (session, start, stop). |
|
866 | 866 | |
|
867 | 867 | Examples |
|
868 | 868 | -------- |
|
869 | 869 | >>> list(extract_hist_ranges("~8/5-~7/4 2")) |
|
870 | 870 | [(-8, 5, None), (-7, 1, 5), (0, 2, 3)] |
|
871 | 871 | """ |
|
872 | 872 | for range_str in ranges_str.split(): |
|
873 | 873 | rmatch = range_re.match(range_str) |
|
874 | 874 | if not rmatch: |
|
875 | 875 | continue |
|
876 | 876 | start = rmatch.group("start") |
|
877 | 877 | if start: |
|
878 | 878 | start = int(start) |
|
879 | 879 | end = rmatch.group("end") |
|
880 | 880 | # If no end specified, get (a, a + 1) |
|
881 | 881 | end = int(end) if end else start + 1 |
|
882 | 882 | else: # start not specified |
|
883 | 883 | if not rmatch.group('startsess'): # no startsess |
|
884 | 884 | continue |
|
885 | 885 | start = 1 |
|
886 | 886 | end = None # provide the entire session hist |
|
887 | 887 | |
|
888 | 888 | if rmatch.group("sep") == "-": # 1-3 == 1:4 --> [1, 2, 3] |
|
889 | 889 | end += 1 |
|
890 | 890 | startsess = rmatch.group("startsess") or "0" |
|
891 | 891 | endsess = rmatch.group("endsess") or startsess |
|
892 | 892 | startsess = int(startsess.replace("~","-")) |
|
893 | 893 | endsess = int(endsess.replace("~","-")) |
|
894 | 894 | assert endsess >= startsess, "start session must be earlier than end session" |
|
895 | 895 | |
|
896 | 896 | if endsess == startsess: |
|
897 | 897 | yield (startsess, start, end) |
|
898 | 898 | continue |
|
899 | 899 | # Multiple sessions in one range: |
|
900 | 900 | yield (startsess, start, None) |
|
901 | 901 | for sess in range(startsess+1, endsess): |
|
902 | 902 | yield (sess, 1, None) |
|
903 | 903 | yield (endsess, 1, end) |
|
904 | 904 | |
|
905 | 905 | |
|
906 | 906 | def _format_lineno(session, line): |
|
907 | 907 | """Helper function to format line numbers properly.""" |
|
908 | 908 | if session == 0: |
|
909 | 909 | return str(line) |
|
910 | 910 | return "%s#%s" % (session, line) |
@@ -1,3226 +1,3223 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 | |
|
14 | 14 | import __future__ |
|
15 | 15 | import abc |
|
16 | 16 | import ast |
|
17 | 17 | import atexit |
|
18 | 18 | import functools |
|
19 | 19 | import os |
|
20 | 20 | import re |
|
21 | 21 | import runpy |
|
22 | 22 | import sys |
|
23 | 23 | import tempfile |
|
24 | 24 | import traceback |
|
25 | 25 | import types |
|
26 | 26 | import subprocess |
|
27 | 27 | import warnings |
|
28 | 28 | from io import open as io_open |
|
29 | 29 | |
|
30 | 30 | from pickleshare import PickleShareDB |
|
31 | 31 | |
|
32 | 32 | from traitlets.config.configurable import SingletonConfigurable |
|
33 | 33 | from IPython.core import 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.debugger import Pdb |
|
45 | 45 | from IPython.core.display_trap import DisplayTrap |
|
46 | 46 | from IPython.core.displayhook import DisplayHook |
|
47 | 47 | from IPython.core.displaypub import DisplayPublisher |
|
48 | 48 | from IPython.core.error import InputRejected, UsageError |
|
49 | 49 | from IPython.core.extensions import ExtensionManager |
|
50 | 50 | from IPython.core.formatters import DisplayFormatter |
|
51 | 51 | from IPython.core.history import HistoryManager |
|
52 | 52 | from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2 |
|
53 | 53 | from IPython.core.logger import Logger |
|
54 | 54 | from IPython.core.macro import Macro |
|
55 | 55 | from IPython.core.payload import PayloadManager |
|
56 | 56 | from IPython.core.prefilter import PrefilterManager |
|
57 | 57 | from IPython.core.profiledir import ProfileDir |
|
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 | 67 | from IPython.paths import get_ipython_dir |
|
68 | 68 | from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists |
|
69 | 69 | from IPython.utils.process import system, getoutput |
|
70 |
from IPython.utils.py3compat import |
|
|
71 | with_metaclass, iteritems) | |
|
70 | from IPython.utils.py3compat import builtin_mod, with_metaclass | |
|
72 | 71 | from IPython.utils.strdispatch import StrDispatch |
|
73 | 72 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
74 | 73 | from IPython.utils.text import format_screen, LSString, SList, DollarFormatter |
|
75 | 74 | from IPython.utils.tempdir import TemporaryDirectory |
|
76 | 75 | from traitlets import ( |
|
77 | 76 | Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type, |
|
78 | 77 | observe, default, |
|
79 | 78 | ) |
|
80 | 79 | from warnings import warn |
|
81 | 80 | from logging import error |
|
82 | 81 | import IPython.core.hooks |
|
83 | 82 | |
|
84 | 83 | # NoOpContext is deprecated, but ipykernel imports it from here. |
|
85 | 84 | # See https://github.com/ipython/ipykernel/issues/157 |
|
86 | 85 | from IPython.utils.contexts import NoOpContext |
|
87 | 86 | |
|
88 | 87 | try: |
|
89 | 88 | import docrepr.sphinxify as sphx |
|
90 | 89 | |
|
91 | 90 | def sphinxify(doc): |
|
92 | 91 | with TemporaryDirectory() as dirname: |
|
93 | 92 | return { |
|
94 | 93 | 'text/html': sphx.sphinxify(doc, dirname), |
|
95 | 94 | 'text/plain': doc |
|
96 | 95 | } |
|
97 | 96 | except ImportError: |
|
98 | 97 | sphinxify = None |
|
99 | 98 | |
|
100 | 99 | |
|
101 | 100 | class ProvisionalWarning(DeprecationWarning): |
|
102 | 101 | """ |
|
103 | 102 | Warning class for unstable features |
|
104 | 103 | """ |
|
105 | 104 | pass |
|
106 | 105 | |
|
107 | 106 | #----------------------------------------------------------------------------- |
|
108 | 107 | # Globals |
|
109 | 108 | #----------------------------------------------------------------------------- |
|
110 | 109 | |
|
111 | 110 | # compiled regexps for autoindent management |
|
112 | 111 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
113 | 112 | |
|
114 | 113 | #----------------------------------------------------------------------------- |
|
115 | 114 | # Utilities |
|
116 | 115 | #----------------------------------------------------------------------------- |
|
117 | 116 | |
|
118 | 117 | @undoc |
|
119 | 118 | def softspace(file, newvalue): |
|
120 | 119 | """Copied from code.py, to remove the dependency""" |
|
121 | 120 | |
|
122 | 121 | oldvalue = 0 |
|
123 | 122 | try: |
|
124 | 123 | oldvalue = file.softspace |
|
125 | 124 | except AttributeError: |
|
126 | 125 | pass |
|
127 | 126 | try: |
|
128 | 127 | file.softspace = newvalue |
|
129 | 128 | except (AttributeError, TypeError): |
|
130 | 129 | # "attribute-less object" or "read-only attributes" |
|
131 | 130 | pass |
|
132 | 131 | return oldvalue |
|
133 | 132 | |
|
134 | 133 | @undoc |
|
135 | 134 | def no_op(*a, **kw): pass |
|
136 | 135 | |
|
137 | 136 | |
|
138 | 137 | class SpaceInInput(Exception): pass |
|
139 | 138 | |
|
140 | 139 | |
|
141 | 140 | def get_default_colors(): |
|
142 | 141 | "DEPRECATED" |
|
143 | 142 | warn('get_default_color is Deprecated, and is `Neutral` on all platforms.', |
|
144 | 143 | DeprecationWarning, stacklevel=2) |
|
145 | 144 | return 'Neutral' |
|
146 | 145 | |
|
147 | 146 | |
|
148 | 147 | class SeparateUnicode(Unicode): |
|
149 | 148 | r"""A Unicode subclass to validate separate_in, separate_out, etc. |
|
150 | 149 | |
|
151 | 150 | This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``. |
|
152 | 151 | """ |
|
153 | 152 | |
|
154 | 153 | def validate(self, obj, value): |
|
155 | 154 | if value == '0': value = '' |
|
156 | 155 | value = value.replace('\\n','\n') |
|
157 | 156 | return super(SeparateUnicode, self).validate(obj, value) |
|
158 | 157 | |
|
159 | 158 | |
|
160 | 159 | @undoc |
|
161 | 160 | class DummyMod(object): |
|
162 | 161 | """A dummy module used for IPython's interactive module when |
|
163 | 162 | a namespace must be assigned to the module's __dict__.""" |
|
164 | 163 | pass |
|
165 | 164 | |
|
166 | 165 | |
|
167 | 166 | class ExecutionResult(object): |
|
168 | 167 | """The result of a call to :meth:`InteractiveShell.run_cell` |
|
169 | 168 | |
|
170 | 169 | Stores information about what took place. |
|
171 | 170 | """ |
|
172 | 171 | execution_count = None |
|
173 | 172 | error_before_exec = None |
|
174 | 173 | error_in_exec = None |
|
175 | 174 | result = None |
|
176 | 175 | |
|
177 | 176 | @property |
|
178 | 177 | def success(self): |
|
179 | 178 | return (self.error_before_exec is None) and (self.error_in_exec is None) |
|
180 | 179 | |
|
181 | 180 | def raise_error(self): |
|
182 | 181 | """Reraises error if `success` is `False`, otherwise does nothing""" |
|
183 | 182 | if self.error_before_exec is not None: |
|
184 | 183 | raise self.error_before_exec |
|
185 | 184 | if self.error_in_exec is not None: |
|
186 | 185 | raise self.error_in_exec |
|
187 | 186 | |
|
188 | 187 | def __repr__(self): |
|
189 | 188 | name = self.__class__.__qualname__ |
|
190 | 189 | return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\ |
|
191 | 190 | (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result)) |
|
192 | 191 | |
|
193 | 192 | |
|
194 | 193 | class InteractiveShell(SingletonConfigurable): |
|
195 | 194 | """An enhanced, interactive shell for Python.""" |
|
196 | 195 | |
|
197 | 196 | _instance = None |
|
198 | 197 | |
|
199 | 198 | ast_transformers = List([], help= |
|
200 | 199 | """ |
|
201 | 200 | A list of ast.NodeTransformer subclass instances, which will be applied |
|
202 | 201 | to user input before code is run. |
|
203 | 202 | """ |
|
204 | 203 | ).tag(config=True) |
|
205 | 204 | |
|
206 | 205 | autocall = Enum((0,1,2), default_value=0, help= |
|
207 | 206 | """ |
|
208 | 207 | Make IPython automatically call any callable object even if you didn't |
|
209 | 208 | type explicit parentheses. For example, 'str 43' becomes 'str(43)' |
|
210 | 209 | automatically. The value can be '0' to disable the feature, '1' for |
|
211 | 210 | 'smart' autocall, where it is not applied if there are no more |
|
212 | 211 | arguments on the line, and '2' for 'full' autocall, where all callable |
|
213 | 212 | objects are automatically called (even if no arguments are present). |
|
214 | 213 | """ |
|
215 | 214 | ).tag(config=True) |
|
216 | 215 | # TODO: remove all autoindent logic and put into frontends. |
|
217 | 216 | # We can't do this yet because even runlines uses the autoindent. |
|
218 | 217 | autoindent = Bool(True, help= |
|
219 | 218 | """ |
|
220 | 219 | Autoindent IPython code entered interactively. |
|
221 | 220 | """ |
|
222 | 221 | ).tag(config=True) |
|
223 | 222 | |
|
224 | 223 | automagic = Bool(True, help= |
|
225 | 224 | """ |
|
226 | 225 | Enable magic commands to be called without the leading %. |
|
227 | 226 | """ |
|
228 | 227 | ).tag(config=True) |
|
229 | 228 | |
|
230 | 229 | banner1 = Unicode(default_banner, |
|
231 | 230 | help="""The part of the banner to be printed before the profile""" |
|
232 | 231 | ).tag(config=True) |
|
233 | 232 | banner2 = Unicode('', |
|
234 | 233 | help="""The part of the banner to be printed after the profile""" |
|
235 | 234 | ).tag(config=True) |
|
236 | 235 | |
|
237 | 236 | cache_size = Integer(1000, help= |
|
238 | 237 | """ |
|
239 | 238 | Set the size of the output cache. The default is 1000, you can |
|
240 | 239 | change it permanently in your config file. Setting it to 0 completely |
|
241 | 240 | disables the caching system, and the minimum value accepted is 20 (if |
|
242 | 241 | you provide a value less than 20, it is reset to 0 and a warning is |
|
243 | 242 | issued). This limit is defined because otherwise you'll spend more |
|
244 | 243 | time re-flushing a too small cache than working |
|
245 | 244 | """ |
|
246 | 245 | ).tag(config=True) |
|
247 | 246 | color_info = Bool(True, help= |
|
248 | 247 | """ |
|
249 | 248 | Use colors for displaying information about objects. Because this |
|
250 | 249 | information is passed through a pager (like 'less'), and some pagers |
|
251 | 250 | get confused with color codes, this capability can be turned off. |
|
252 | 251 | """ |
|
253 | 252 | ).tag(config=True) |
|
254 | 253 | colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'), |
|
255 | 254 | default_value='Neutral', |
|
256 | 255 | help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)." |
|
257 | 256 | ).tag(config=True) |
|
258 | 257 | debug = Bool(False).tag(config=True) |
|
259 | 258 | disable_failing_post_execute = Bool(False, |
|
260 | 259 | help="Don't call post-execute functions that have failed in the past." |
|
261 | 260 | ).tag(config=True) |
|
262 | 261 | display_formatter = Instance(DisplayFormatter, allow_none=True) |
|
263 | 262 | displayhook_class = Type(DisplayHook) |
|
264 | 263 | display_pub_class = Type(DisplayPublisher) |
|
265 | 264 | |
|
266 | 265 | sphinxify_docstring = Bool(False, help= |
|
267 | 266 | """ |
|
268 | 267 | Enables rich html representation of docstrings. (This requires the |
|
269 | 268 | docrepr module). |
|
270 | 269 | """).tag(config=True) |
|
271 | 270 | |
|
272 | 271 | @observe("sphinxify_docstring") |
|
273 | 272 | def _sphinxify_docstring_changed(self, change): |
|
274 | 273 | if change['new']: |
|
275 | 274 | warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning) |
|
276 | 275 | |
|
277 | 276 | enable_html_pager = Bool(False, help= |
|
278 | 277 | """ |
|
279 | 278 | (Provisional API) enables html representation in mime bundles sent |
|
280 | 279 | to pagers. |
|
281 | 280 | """).tag(config=True) |
|
282 | 281 | |
|
283 | 282 | @observe("enable_html_pager") |
|
284 | 283 | def _enable_html_pager_changed(self, change): |
|
285 | 284 | if change['new']: |
|
286 | 285 | warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning) |
|
287 | 286 | |
|
288 | 287 | data_pub_class = None |
|
289 | 288 | |
|
290 | 289 | exit_now = Bool(False) |
|
291 | 290 | exiter = Instance(ExitAutocall) |
|
292 | 291 | @default('exiter') |
|
293 | 292 | def _exiter_default(self): |
|
294 | 293 | return ExitAutocall(self) |
|
295 | 294 | # Monotonically increasing execution counter |
|
296 | 295 | execution_count = Integer(1) |
|
297 | 296 | filename = Unicode("<ipython console>") |
|
298 | 297 | ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__ |
|
299 | 298 | |
|
300 | 299 | # Input splitter, to transform input line by line and detect when a block |
|
301 | 300 | # is ready to be executed. |
|
302 | 301 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', |
|
303 | 302 | (), {'line_input_checker': True}) |
|
304 | 303 | |
|
305 | 304 | # This InputSplitter instance is used to transform completed cells before |
|
306 | 305 | # running them. It allows cell magics to contain blank lines. |
|
307 | 306 | input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter', |
|
308 | 307 | (), {'line_input_checker': False}) |
|
309 | 308 | |
|
310 | 309 | logstart = Bool(False, help= |
|
311 | 310 | """ |
|
312 | 311 | Start logging to the default log file in overwrite mode. |
|
313 | 312 | Use `logappend` to specify a log file to **append** logs to. |
|
314 | 313 | """ |
|
315 | 314 | ).tag(config=True) |
|
316 | 315 | logfile = Unicode('', help= |
|
317 | 316 | """ |
|
318 | 317 | The name of the logfile to use. |
|
319 | 318 | """ |
|
320 | 319 | ).tag(config=True) |
|
321 | 320 | logappend = Unicode('', help= |
|
322 | 321 | """ |
|
323 | 322 | Start logging to the given file in append mode. |
|
324 | 323 | Use `logfile` to specify a log file to **overwrite** logs to. |
|
325 | 324 | """ |
|
326 | 325 | ).tag(config=True) |
|
327 | 326 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
328 | 327 | ).tag(config=True) |
|
329 | 328 | pdb = Bool(False, help= |
|
330 | 329 | """ |
|
331 | 330 | Automatically call the pdb debugger after every exception. |
|
332 | 331 | """ |
|
333 | 332 | ).tag(config=True) |
|
334 | 333 | display_page = Bool(False, |
|
335 | 334 | help="""If True, anything that would be passed to the pager |
|
336 | 335 | will be displayed as regular output instead.""" |
|
337 | 336 | ).tag(config=True) |
|
338 | 337 | |
|
339 | 338 | # deprecated prompt traits: |
|
340 | 339 | |
|
341 | 340 | prompt_in1 = Unicode('In [\\#]: ', |
|
342 | 341 | help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." |
|
343 | 342 | ).tag(config=True) |
|
344 | 343 | prompt_in2 = Unicode(' .\\D.: ', |
|
345 | 344 | help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." |
|
346 | 345 | ).tag(config=True) |
|
347 | 346 | prompt_out = Unicode('Out[\\#]: ', |
|
348 | 347 | help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." |
|
349 | 348 | ).tag(config=True) |
|
350 | 349 | prompts_pad_left = Bool(True, |
|
351 | 350 | help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." |
|
352 | 351 | ).tag(config=True) |
|
353 | 352 | |
|
354 | 353 | @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left') |
|
355 | 354 | def _prompt_trait_changed(self, change): |
|
356 | 355 | name = change['name'] |
|
357 | 356 | warn("InteractiveShell.{name} is deprecated since IPython 4.0" |
|
358 | 357 | " and ignored since 5.0, set TerminalInteractiveShell.prompts" |
|
359 | 358 | " object directly.".format(name=name)) |
|
360 | 359 | |
|
361 | 360 | # protect against weird cases where self.config may not exist: |
|
362 | 361 | |
|
363 | 362 | show_rewritten_input = Bool(True, |
|
364 | 363 | help="Show rewritten input, e.g. for autocall." |
|
365 | 364 | ).tag(config=True) |
|
366 | 365 | |
|
367 | 366 | quiet = Bool(False).tag(config=True) |
|
368 | 367 | |
|
369 | 368 | history_length = Integer(10000, |
|
370 | 369 | help='Total length of command history' |
|
371 | 370 | ).tag(config=True) |
|
372 | 371 | |
|
373 | 372 | history_load_length = Integer(1000, help= |
|
374 | 373 | """ |
|
375 | 374 | The number of saved history entries to be loaded |
|
376 | 375 | into the history buffer at startup. |
|
377 | 376 | """ |
|
378 | 377 | ).tag(config=True) |
|
379 | 378 | |
|
380 | 379 | ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'], |
|
381 | 380 | default_value='last_expr', |
|
382 | 381 | help=""" |
|
383 | 382 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be |
|
384 | 383 | run interactively (displaying output from expressions).""" |
|
385 | 384 | ).tag(config=True) |
|
386 | 385 | |
|
387 | 386 | # TODO: this part of prompt management should be moved to the frontends. |
|
388 | 387 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' |
|
389 | 388 | separate_in = SeparateUnicode('\n').tag(config=True) |
|
390 | 389 | separate_out = SeparateUnicode('').tag(config=True) |
|
391 | 390 | separate_out2 = SeparateUnicode('').tag(config=True) |
|
392 | 391 | wildcards_case_sensitive = Bool(True).tag(config=True) |
|
393 | 392 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
394 | 393 | default_value='Context').tag(config=True) |
|
395 | 394 | |
|
396 | 395 | # Subcomponents of InteractiveShell |
|
397 | 396 | alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True) |
|
398 | 397 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True) |
|
399 | 398 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True) |
|
400 | 399 | display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True) |
|
401 | 400 | extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True) |
|
402 | 401 | payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True) |
|
403 | 402 | history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True) |
|
404 | 403 | magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True) |
|
405 | 404 | |
|
406 | 405 | profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True) |
|
407 | 406 | @property |
|
408 | 407 | def profile(self): |
|
409 | 408 | if self.profile_dir is not None: |
|
410 | 409 | name = os.path.basename(self.profile_dir.location) |
|
411 | 410 | return name.replace('profile_','') |
|
412 | 411 | |
|
413 | 412 | |
|
414 | 413 | # Private interface |
|
415 | 414 | _post_execute = Dict() |
|
416 | 415 | |
|
417 | 416 | # Tracks any GUI loop loaded for pylab |
|
418 | 417 | pylab_gui_select = None |
|
419 | 418 | |
|
420 | 419 | last_execution_succeeded = Bool(True, help='Did last executed command succeeded') |
|
421 | 420 | |
|
422 | 421 | def __init__(self, ipython_dir=None, profile_dir=None, |
|
423 | 422 | user_module=None, user_ns=None, |
|
424 | 423 | custom_exceptions=((), None), **kwargs): |
|
425 | 424 | |
|
426 | 425 | # This is where traits with a config_key argument are updated |
|
427 | 426 | # from the values on config. |
|
428 | 427 | super(InteractiveShell, self).__init__(**kwargs) |
|
429 | 428 | if 'PromptManager' in self.config: |
|
430 | 429 | warn('As of IPython 5.0 `PromptManager` config will have no effect' |
|
431 | 430 | ' and has been replaced by TerminalInteractiveShell.prompts_class') |
|
432 | 431 | self.configurables = [self] |
|
433 | 432 | |
|
434 | 433 | # These are relatively independent and stateless |
|
435 | 434 | self.init_ipython_dir(ipython_dir) |
|
436 | 435 | self.init_profile_dir(profile_dir) |
|
437 | 436 | self.init_instance_attrs() |
|
438 | 437 | self.init_environment() |
|
439 | 438 | |
|
440 | 439 | # Check if we're in a virtualenv, and set up sys.path. |
|
441 | 440 | self.init_virtualenv() |
|
442 | 441 | |
|
443 | 442 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
444 | 443 | self.init_create_namespaces(user_module, user_ns) |
|
445 | 444 | # This has to be done after init_create_namespaces because it uses |
|
446 | 445 | # something in self.user_ns, but before init_sys_modules, which |
|
447 | 446 | # is the first thing to modify sys. |
|
448 | 447 | # TODO: When we override sys.stdout and sys.stderr before this class |
|
449 | 448 | # is created, we are saving the overridden ones here. Not sure if this |
|
450 | 449 | # is what we want to do. |
|
451 | 450 | self.save_sys_module_state() |
|
452 | 451 | self.init_sys_modules() |
|
453 | 452 | |
|
454 | 453 | # While we're trying to have each part of the code directly access what |
|
455 | 454 | # it needs without keeping redundant references to objects, we have too |
|
456 | 455 | # much legacy code that expects ip.db to exist. |
|
457 | 456 | self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db')) |
|
458 | 457 | |
|
459 | 458 | self.init_history() |
|
460 | 459 | self.init_encoding() |
|
461 | 460 | self.init_prefilter() |
|
462 | 461 | |
|
463 | 462 | self.init_syntax_highlighting() |
|
464 | 463 | self.init_hooks() |
|
465 | 464 | self.init_events() |
|
466 | 465 | self.init_pushd_popd_magic() |
|
467 | 466 | self.init_user_ns() |
|
468 | 467 | self.init_logger() |
|
469 | 468 | self.init_builtins() |
|
470 | 469 | |
|
471 | 470 | # The following was in post_config_initialization |
|
472 | 471 | self.init_inspector() |
|
473 | 472 | self.raw_input_original = input |
|
474 | 473 | self.init_completer() |
|
475 | 474 | # TODO: init_io() needs to happen before init_traceback handlers |
|
476 | 475 | # because the traceback handlers hardcode the stdout/stderr streams. |
|
477 | 476 | # This logic in in debugger.Pdb and should eventually be changed. |
|
478 | 477 | self.init_io() |
|
479 | 478 | self.init_traceback_handlers(custom_exceptions) |
|
480 | 479 | self.init_prompts() |
|
481 | 480 | self.init_display_formatter() |
|
482 | 481 | self.init_display_pub() |
|
483 | 482 | self.init_data_pub() |
|
484 | 483 | self.init_displayhook() |
|
485 | 484 | self.init_magics() |
|
486 | 485 | self.init_alias() |
|
487 | 486 | self.init_logstart() |
|
488 | 487 | self.init_pdb() |
|
489 | 488 | self.init_extension_manager() |
|
490 | 489 | self.init_payload() |
|
491 | 490 | self.init_deprecation_warnings() |
|
492 | 491 | self.hooks.late_startup_hook() |
|
493 | 492 | self.events.trigger('shell_initialized', self) |
|
494 | 493 | atexit.register(self.atexit_operations) |
|
495 | 494 | |
|
496 | 495 | def get_ipython(self): |
|
497 | 496 | """Return the currently running IPython instance.""" |
|
498 | 497 | return self |
|
499 | 498 | |
|
500 | 499 | #------------------------------------------------------------------------- |
|
501 | 500 | # Trait changed handlers |
|
502 | 501 | #------------------------------------------------------------------------- |
|
503 | 502 | @observe('ipython_dir') |
|
504 | 503 | def _ipython_dir_changed(self, change): |
|
505 | 504 | ensure_dir_exists(change['new']) |
|
506 | 505 | |
|
507 | 506 | def set_autoindent(self,value=None): |
|
508 | 507 | """Set the autoindent flag. |
|
509 | 508 | |
|
510 | 509 | If called with no arguments, it acts as a toggle.""" |
|
511 | 510 | if value is None: |
|
512 | 511 | self.autoindent = not self.autoindent |
|
513 | 512 | else: |
|
514 | 513 | self.autoindent = value |
|
515 | 514 | |
|
516 | 515 | #------------------------------------------------------------------------- |
|
517 | 516 | # init_* methods called by __init__ |
|
518 | 517 | #------------------------------------------------------------------------- |
|
519 | 518 | |
|
520 | 519 | def init_ipython_dir(self, ipython_dir): |
|
521 | 520 | if ipython_dir is not None: |
|
522 | 521 | self.ipython_dir = ipython_dir |
|
523 | 522 | return |
|
524 | 523 | |
|
525 | 524 | self.ipython_dir = get_ipython_dir() |
|
526 | 525 | |
|
527 | 526 | def init_profile_dir(self, profile_dir): |
|
528 | 527 | if profile_dir is not None: |
|
529 | 528 | self.profile_dir = profile_dir |
|
530 | 529 | return |
|
531 | 530 | self.profile_dir =\ |
|
532 | 531 | ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default') |
|
533 | 532 | |
|
534 | 533 | def init_instance_attrs(self): |
|
535 | 534 | self.more = False |
|
536 | 535 | |
|
537 | 536 | # command compiler |
|
538 | 537 | self.compile = CachingCompiler() |
|
539 | 538 | |
|
540 | 539 | # Make an empty namespace, which extension writers can rely on both |
|
541 | 540 | # existing and NEVER being used by ipython itself. This gives them a |
|
542 | 541 | # convenient location for storing additional information and state |
|
543 | 542 | # their extensions may require, without fear of collisions with other |
|
544 | 543 | # ipython names that may develop later. |
|
545 | 544 | self.meta = Struct() |
|
546 | 545 | |
|
547 | 546 | # Temporary files used for various purposes. Deleted at exit. |
|
548 | 547 | self.tempfiles = [] |
|
549 | 548 | self.tempdirs = [] |
|
550 | 549 | |
|
551 | 550 | # keep track of where we started running (mainly for crash post-mortem) |
|
552 | 551 | # This is not being used anywhere currently. |
|
553 |
self.starting_dir = |
|
|
552 | self.starting_dir = os.getcwd() | |
|
554 | 553 | |
|
555 | 554 | # Indentation management |
|
556 | 555 | self.indent_current_nsp = 0 |
|
557 | 556 | |
|
558 | 557 | # Dict to track post-execution functions that have been registered |
|
559 | 558 | self._post_execute = {} |
|
560 | 559 | |
|
561 | 560 | def init_environment(self): |
|
562 | 561 | """Any changes we need to make to the user's environment.""" |
|
563 | 562 | pass |
|
564 | 563 | |
|
565 | 564 | def init_encoding(self): |
|
566 | 565 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
567 | 566 | # under Win32 have it set to None, and we need to have a known valid |
|
568 | 567 | # encoding to use in the raw_input() method |
|
569 | 568 | try: |
|
570 | 569 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
571 | 570 | except AttributeError: |
|
572 | 571 | self.stdin_encoding = 'ascii' |
|
573 | 572 | |
|
574 | 573 | |
|
575 | 574 | @observe('colors') |
|
576 | 575 | def init_syntax_highlighting(self, changes=None): |
|
577 | 576 | # Python source parser/formatter for syntax highlighting |
|
578 | 577 | pyformat = PyColorize.Parser(style=self.colors, parent=self).format |
|
579 | 578 | self.pycolorize = lambda src: pyformat(src,'str') |
|
580 | 579 | |
|
581 | 580 | def refresh_style(self): |
|
582 | 581 | # No-op here, used in subclass |
|
583 | 582 | pass |
|
584 | 583 | |
|
585 | 584 | def init_pushd_popd_magic(self): |
|
586 | 585 | # for pushd/popd management |
|
587 | 586 | self.home_dir = get_home_dir() |
|
588 | 587 | |
|
589 | 588 | self.dir_stack = [] |
|
590 | 589 | |
|
591 | 590 | def init_logger(self): |
|
592 | 591 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', |
|
593 | 592 | logmode='rotate') |
|
594 | 593 | |
|
595 | 594 | def init_logstart(self): |
|
596 | 595 | """Initialize logging in case it was requested at the command line. |
|
597 | 596 | """ |
|
598 | 597 | if self.logappend: |
|
599 | 598 | self.magic('logstart %s append' % self.logappend) |
|
600 | 599 | elif self.logfile: |
|
601 | 600 | self.magic('logstart %s' % self.logfile) |
|
602 | 601 | elif self.logstart: |
|
603 | 602 | self.magic('logstart') |
|
604 | 603 | |
|
605 | 604 | def init_deprecation_warnings(self): |
|
606 | 605 | """ |
|
607 | 606 | register default filter for deprecation warning. |
|
608 | 607 | |
|
609 | 608 | This will allow deprecation warning of function used interactively to show |
|
610 | 609 | warning to users, and still hide deprecation warning from libraries import. |
|
611 | 610 | """ |
|
612 | 611 | warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__")) |
|
613 | 612 | |
|
614 | 613 | def init_builtins(self): |
|
615 | 614 | # A single, static flag that we set to True. Its presence indicates |
|
616 | 615 | # that an IPython shell has been created, and we make no attempts at |
|
617 | 616 | # removing on exit or representing the existence of more than one |
|
618 | 617 | # IPython at a time. |
|
619 | 618 | builtin_mod.__dict__['__IPYTHON__'] = True |
|
620 | 619 | |
|
621 | 620 | self.builtin_trap = BuiltinTrap(shell=self) |
|
622 | 621 | |
|
623 | 622 | def init_inspector(self): |
|
624 | 623 | # Object inspector |
|
625 | 624 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
626 | 625 | PyColorize.ANSICodeColors, |
|
627 | 626 | 'NoColor', |
|
628 | 627 | self.object_info_string_level) |
|
629 | 628 | |
|
630 | 629 | def init_io(self): |
|
631 | 630 | # This will just use sys.stdout and sys.stderr. If you want to |
|
632 | 631 | # override sys.stdout and sys.stderr themselves, you need to do that |
|
633 | 632 | # *before* instantiating this class, because io holds onto |
|
634 | 633 | # references to the underlying streams. |
|
635 | 634 | # io.std* are deprecated, but don't show our own deprecation warnings |
|
636 | 635 | # during initialization of the deprecated API. |
|
637 | 636 | with warnings.catch_warnings(): |
|
638 | 637 | warnings.simplefilter('ignore', DeprecationWarning) |
|
639 | 638 | io.stdout = io.IOStream(sys.stdout) |
|
640 | 639 | io.stderr = io.IOStream(sys.stderr) |
|
641 | 640 | |
|
642 | 641 | def init_prompts(self): |
|
643 | 642 | # Set system prompts, so that scripts can decide if they are running |
|
644 | 643 | # interactively. |
|
645 | 644 | sys.ps1 = 'In : ' |
|
646 | 645 | sys.ps2 = '...: ' |
|
647 | 646 | sys.ps3 = 'Out: ' |
|
648 | 647 | |
|
649 | 648 | def init_display_formatter(self): |
|
650 | 649 | self.display_formatter = DisplayFormatter(parent=self) |
|
651 | 650 | self.configurables.append(self.display_formatter) |
|
652 | 651 | |
|
653 | 652 | def init_display_pub(self): |
|
654 | 653 | self.display_pub = self.display_pub_class(parent=self) |
|
655 | 654 | self.configurables.append(self.display_pub) |
|
656 | 655 | |
|
657 | 656 | def init_data_pub(self): |
|
658 | 657 | if not self.data_pub_class: |
|
659 | 658 | self.data_pub = None |
|
660 | 659 | return |
|
661 | 660 | self.data_pub = self.data_pub_class(parent=self) |
|
662 | 661 | self.configurables.append(self.data_pub) |
|
663 | 662 | |
|
664 | 663 | def init_displayhook(self): |
|
665 | 664 | # Initialize displayhook, set in/out prompts and printing system |
|
666 | 665 | self.displayhook = self.displayhook_class( |
|
667 | 666 | parent=self, |
|
668 | 667 | shell=self, |
|
669 | 668 | cache_size=self.cache_size, |
|
670 | 669 | ) |
|
671 | 670 | self.configurables.append(self.displayhook) |
|
672 | 671 | # This is a context manager that installs/revmoes the displayhook at |
|
673 | 672 | # the appropriate time. |
|
674 | 673 | self.display_trap = DisplayTrap(hook=self.displayhook) |
|
675 | 674 | |
|
676 | 675 | def init_virtualenv(self): |
|
677 | 676 | """Add a virtualenv to sys.path so the user can import modules from it. |
|
678 | 677 | This isn't perfect: it doesn't use the Python interpreter with which the |
|
679 | 678 | virtualenv was built, and it ignores the --no-site-packages option. A |
|
680 | 679 | warning will appear suggesting the user installs IPython in the |
|
681 | 680 | virtualenv, but for many cases, it probably works well enough. |
|
682 | 681 | |
|
683 | 682 | Adapted from code snippets online. |
|
684 | 683 | |
|
685 | 684 | http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv |
|
686 | 685 | """ |
|
687 | 686 | if 'VIRTUAL_ENV' not in os.environ: |
|
688 | 687 | # Not in a virtualenv |
|
689 | 688 | return |
|
690 | 689 | |
|
691 | 690 | # venv detection: |
|
692 | 691 | # stdlib venv may symlink sys.executable, so we can't use realpath. |
|
693 | 692 | # but others can symlink *to* the venv Python, so we can't just use sys.executable. |
|
694 | 693 | # So we just check every item in the symlink tree (generally <= 3) |
|
695 | 694 | p = os.path.normcase(sys.executable) |
|
696 | 695 | paths = [p] |
|
697 | 696 | while os.path.islink(p): |
|
698 | 697 | p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p))) |
|
699 | 698 | paths.append(p) |
|
700 | 699 | p_venv = os.path.normcase(os.environ['VIRTUAL_ENV']) |
|
701 | 700 | if any(p.startswith(p_venv) for p in paths): |
|
702 | 701 | # Running properly in the virtualenv, don't need to do anything |
|
703 | 702 | return |
|
704 | 703 | |
|
705 | 704 | warn("Attempting to work in a virtualenv. If you encounter problems, please " |
|
706 | 705 | "install IPython inside the virtualenv.") |
|
707 | 706 | if sys.platform == "win32": |
|
708 | 707 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages') |
|
709 | 708 | else: |
|
710 | 709 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib', |
|
711 | 710 | 'python%d.%d' % sys.version_info[:2], 'site-packages') |
|
712 | 711 | |
|
713 | 712 | import site |
|
714 | 713 | sys.path.insert(0, virtual_env) |
|
715 | 714 | site.addsitedir(virtual_env) |
|
716 | 715 | |
|
717 | 716 | #------------------------------------------------------------------------- |
|
718 | 717 | # Things related to injections into the sys module |
|
719 | 718 | #------------------------------------------------------------------------- |
|
720 | 719 | |
|
721 | 720 | def save_sys_module_state(self): |
|
722 | 721 | """Save the state of hooks in the sys module. |
|
723 | 722 | |
|
724 | 723 | This has to be called after self.user_module is created. |
|
725 | 724 | """ |
|
726 | 725 | self._orig_sys_module_state = {'stdin': sys.stdin, |
|
727 | 726 | 'stdout': sys.stdout, |
|
728 | 727 | 'stderr': sys.stderr, |
|
729 | 728 | 'excepthook': sys.excepthook} |
|
730 | 729 | self._orig_sys_modules_main_name = self.user_module.__name__ |
|
731 | 730 | self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__) |
|
732 | 731 | |
|
733 | 732 | def restore_sys_module_state(self): |
|
734 | 733 | """Restore the state of the sys module.""" |
|
735 | 734 | try: |
|
736 |
for k, v in |
|
|
735 | for k, v in self._orig_sys_module_state.items(): | |
|
737 | 736 | setattr(sys, k, v) |
|
738 | 737 | except AttributeError: |
|
739 | 738 | pass |
|
740 | 739 | # Reset what what done in self.init_sys_modules |
|
741 | 740 | if self._orig_sys_modules_main_mod is not None: |
|
742 | 741 | sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod |
|
743 | 742 | |
|
744 | 743 | #------------------------------------------------------------------------- |
|
745 | 744 | # Things related to the banner |
|
746 | 745 | #------------------------------------------------------------------------- |
|
747 | 746 | |
|
748 | 747 | @property |
|
749 | 748 | def banner(self): |
|
750 | 749 | banner = self.banner1 |
|
751 | 750 | if self.profile and self.profile != 'default': |
|
752 | 751 | banner += '\nIPython profile: %s\n' % self.profile |
|
753 | 752 | if self.banner2: |
|
754 | 753 | banner += '\n' + self.banner2 |
|
755 | 754 | return banner |
|
756 | 755 | |
|
757 | 756 | def show_banner(self, banner=None): |
|
758 | 757 | if banner is None: |
|
759 | 758 | banner = self.banner |
|
760 | 759 | sys.stdout.write(banner) |
|
761 | 760 | |
|
762 | 761 | #------------------------------------------------------------------------- |
|
763 | 762 | # Things related to hooks |
|
764 | 763 | #------------------------------------------------------------------------- |
|
765 | 764 | |
|
766 | 765 | def init_hooks(self): |
|
767 | 766 | # hooks holds pointers used for user-side customizations |
|
768 | 767 | self.hooks = Struct() |
|
769 | 768 | |
|
770 | 769 | self.strdispatchers = {} |
|
771 | 770 | |
|
772 | 771 | # Set all default hooks, defined in the IPython.hooks module. |
|
773 | 772 | hooks = IPython.core.hooks |
|
774 | 773 | for hook_name in hooks.__all__: |
|
775 | 774 | # default hooks have priority 100, i.e. low; user hooks should have |
|
776 | 775 | # 0-100 priority |
|
777 | 776 | self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False) |
|
778 | 777 | |
|
779 | 778 | if self.display_page: |
|
780 | 779 | self.set_hook('show_in_pager', page.as_hook(page.display_page), 90) |
|
781 | 780 | |
|
782 | 781 | def set_hook(self,name,hook, priority=50, str_key=None, re_key=None, |
|
783 | 782 | _warn_deprecated=True): |
|
784 | 783 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
785 | 784 | |
|
786 | 785 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
787 | 786 | adding your function to one of these hooks, you can modify IPython's |
|
788 | 787 | behavior to call at runtime your own routines.""" |
|
789 | 788 | |
|
790 | 789 | # At some point in the future, this should validate the hook before it |
|
791 | 790 | # accepts it. Probably at least check that the hook takes the number |
|
792 | 791 | # of args it's supposed to. |
|
793 | 792 | |
|
794 | 793 | f = types.MethodType(hook,self) |
|
795 | 794 | |
|
796 | 795 | # check if the hook is for strdispatcher first |
|
797 | 796 | if str_key is not None: |
|
798 | 797 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
799 | 798 | sdp.add_s(str_key, f, priority ) |
|
800 | 799 | self.strdispatchers[name] = sdp |
|
801 | 800 | return |
|
802 | 801 | if re_key is not None: |
|
803 | 802 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
804 | 803 | sdp.add_re(re.compile(re_key), f, priority ) |
|
805 | 804 | self.strdispatchers[name] = sdp |
|
806 | 805 | return |
|
807 | 806 | |
|
808 | 807 | dp = getattr(self.hooks, name, None) |
|
809 | 808 | if name not in IPython.core.hooks.__all__: |
|
810 | 809 | print("Warning! Hook '%s' is not one of %s" % \ |
|
811 | 810 | (name, IPython.core.hooks.__all__ )) |
|
812 | 811 | |
|
813 | 812 | if _warn_deprecated and (name in IPython.core.hooks.deprecated): |
|
814 | 813 | alternative = IPython.core.hooks.deprecated[name] |
|
815 | 814 | warn("Hook {} is deprecated. Use {} instead.".format(name, alternative), stacklevel=2) |
|
816 | 815 | |
|
817 | 816 | if not dp: |
|
818 | 817 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
819 | 818 | |
|
820 | 819 | try: |
|
821 | 820 | dp.add(f,priority) |
|
822 | 821 | except AttributeError: |
|
823 | 822 | # it was not commandchain, plain old func - replace |
|
824 | 823 | dp = f |
|
825 | 824 | |
|
826 | 825 | setattr(self.hooks,name, dp) |
|
827 | 826 | |
|
828 | 827 | #------------------------------------------------------------------------- |
|
829 | 828 | # Things related to events |
|
830 | 829 | #------------------------------------------------------------------------- |
|
831 | 830 | |
|
832 | 831 | def init_events(self): |
|
833 | 832 | self.events = EventManager(self, available_events) |
|
834 | 833 | |
|
835 | 834 | self.events.register("pre_execute", self._clear_warning_registry) |
|
836 | 835 | |
|
837 | 836 | def register_post_execute(self, func): |
|
838 | 837 | """DEPRECATED: Use ip.events.register('post_run_cell', func) |
|
839 | 838 | |
|
840 | 839 | Register a function for calling after code execution. |
|
841 | 840 | """ |
|
842 | 841 | warn("ip.register_post_execute is deprecated, use " |
|
843 | 842 | "ip.events.register('post_run_cell', func) instead.", stacklevel=2) |
|
844 | 843 | self.events.register('post_run_cell', func) |
|
845 | 844 | |
|
846 | 845 | def _clear_warning_registry(self): |
|
847 | 846 | # clear the warning registry, so that different code blocks with |
|
848 | 847 | # overlapping line number ranges don't cause spurious suppression of |
|
849 | 848 | # warnings (see gh-6611 for details) |
|
850 | 849 | if "__warningregistry__" in self.user_global_ns: |
|
851 | 850 | del self.user_global_ns["__warningregistry__"] |
|
852 | 851 | |
|
853 | 852 | #------------------------------------------------------------------------- |
|
854 | 853 | # Things related to the "main" module |
|
855 | 854 | #------------------------------------------------------------------------- |
|
856 | 855 | |
|
857 | 856 | def new_main_mod(self, filename, modname): |
|
858 | 857 | """Return a new 'main' module object for user code execution. |
|
859 | 858 | |
|
860 | 859 | ``filename`` should be the path of the script which will be run in the |
|
861 | 860 | module. Requests with the same filename will get the same module, with |
|
862 | 861 | its namespace cleared. |
|
863 | 862 | |
|
864 | 863 | ``modname`` should be the module name - normally either '__main__' or |
|
865 | 864 | the basename of the file without the extension. |
|
866 | 865 | |
|
867 | 866 | When scripts are executed via %run, we must keep a reference to their |
|
868 | 867 | __main__ module around so that Python doesn't |
|
869 | 868 | clear it, rendering references to module globals useless. |
|
870 | 869 | |
|
871 | 870 | This method keeps said reference in a private dict, keyed by the |
|
872 | 871 | absolute path of the script. This way, for multiple executions of the |
|
873 | 872 | same script we only keep one copy of the namespace (the last one), |
|
874 | 873 | thus preventing memory leaks from old references while allowing the |
|
875 | 874 | objects from the last execution to be accessible. |
|
876 | 875 | """ |
|
877 | 876 | filename = os.path.abspath(filename) |
|
878 | 877 | try: |
|
879 | 878 | main_mod = self._main_mod_cache[filename] |
|
880 | 879 | except KeyError: |
|
881 | 880 | main_mod = self._main_mod_cache[filename] = types.ModuleType( |
|
882 | 881 | py3compat.cast_bytes_py2(modname), |
|
883 | 882 | doc="Module created for script run in IPython") |
|
884 | 883 | else: |
|
885 | 884 | main_mod.__dict__.clear() |
|
886 | 885 | main_mod.__name__ = modname |
|
887 | 886 | |
|
888 | 887 | main_mod.__file__ = filename |
|
889 | 888 | # It seems pydoc (and perhaps others) needs any module instance to |
|
890 | 889 | # implement a __nonzero__ method |
|
891 | 890 | main_mod.__nonzero__ = lambda : True |
|
892 | 891 | |
|
893 | 892 | return main_mod |
|
894 | 893 | |
|
895 | 894 | def clear_main_mod_cache(self): |
|
896 | 895 | """Clear the cache of main modules. |
|
897 | 896 | |
|
898 | 897 | Mainly for use by utilities like %reset. |
|
899 | 898 | |
|
900 | 899 | Examples |
|
901 | 900 | -------- |
|
902 | 901 | |
|
903 | 902 | In [15]: import IPython |
|
904 | 903 | |
|
905 | 904 | In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython') |
|
906 | 905 | |
|
907 | 906 | In [17]: len(_ip._main_mod_cache) > 0 |
|
908 | 907 | Out[17]: True |
|
909 | 908 | |
|
910 | 909 | In [18]: _ip.clear_main_mod_cache() |
|
911 | 910 | |
|
912 | 911 | In [19]: len(_ip._main_mod_cache) == 0 |
|
913 | 912 | Out[19]: True |
|
914 | 913 | """ |
|
915 | 914 | self._main_mod_cache.clear() |
|
916 | 915 | |
|
917 | 916 | #------------------------------------------------------------------------- |
|
918 | 917 | # Things related to debugging |
|
919 | 918 | #------------------------------------------------------------------------- |
|
920 | 919 | |
|
921 | 920 | def init_pdb(self): |
|
922 | 921 | # Set calling of pdb on exceptions |
|
923 | 922 | # self.call_pdb is a property |
|
924 | 923 | self.call_pdb = self.pdb |
|
925 | 924 | |
|
926 | 925 | def _get_call_pdb(self): |
|
927 | 926 | return self._call_pdb |
|
928 | 927 | |
|
929 | 928 | def _set_call_pdb(self,val): |
|
930 | 929 | |
|
931 | 930 | if val not in (0,1,False,True): |
|
932 | 931 | raise ValueError('new call_pdb value must be boolean') |
|
933 | 932 | |
|
934 | 933 | # store value in instance |
|
935 | 934 | self._call_pdb = val |
|
936 | 935 | |
|
937 | 936 | # notify the actual exception handlers |
|
938 | 937 | self.InteractiveTB.call_pdb = val |
|
939 | 938 | |
|
940 | 939 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
941 | 940 | 'Control auto-activation of pdb at exceptions') |
|
942 | 941 | |
|
943 | 942 | def debugger(self,force=False): |
|
944 | 943 | """Call the pdb debugger. |
|
945 | 944 | |
|
946 | 945 | Keywords: |
|
947 | 946 | |
|
948 | 947 | - force(False): by default, this routine checks the instance call_pdb |
|
949 | 948 | flag and does not actually invoke the debugger if the flag is false. |
|
950 | 949 | The 'force' option forces the debugger to activate even if the flag |
|
951 | 950 | is false. |
|
952 | 951 | """ |
|
953 | 952 | |
|
954 | 953 | if not (force or self.call_pdb): |
|
955 | 954 | return |
|
956 | 955 | |
|
957 | 956 | if not hasattr(sys,'last_traceback'): |
|
958 | 957 | error('No traceback has been produced, nothing to debug.') |
|
959 | 958 | return |
|
960 | 959 | |
|
961 | 960 | self.InteractiveTB.debugger(force=True) |
|
962 | 961 | |
|
963 | 962 | #------------------------------------------------------------------------- |
|
964 | 963 | # Things related to IPython's various namespaces |
|
965 | 964 | #------------------------------------------------------------------------- |
|
966 | 965 | default_user_namespaces = True |
|
967 | 966 | |
|
968 | 967 | def init_create_namespaces(self, user_module=None, user_ns=None): |
|
969 | 968 | # Create the namespace where the user will operate. user_ns is |
|
970 | 969 | # normally the only one used, and it is passed to the exec calls as |
|
971 | 970 | # the locals argument. But we do carry a user_global_ns namespace |
|
972 | 971 | # given as the exec 'globals' argument, This is useful in embedding |
|
973 | 972 | # situations where the ipython shell opens in a context where the |
|
974 | 973 | # distinction between locals and globals is meaningful. For |
|
975 | 974 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
976 | 975 | |
|
977 | 976 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
978 | 977 | # level as a dict instead of a module. This is a manual fix, but I |
|
979 | 978 | # should really track down where the problem is coming from. Alex |
|
980 | 979 | # Schmolck reported this problem first. |
|
981 | 980 | |
|
982 | 981 | # A useful post by Alex Martelli on this topic: |
|
983 | 982 | # Re: inconsistent value from __builtins__ |
|
984 | 983 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
985 | 984 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
986 | 985 | # Gruppen: comp.lang.python |
|
987 | 986 | |
|
988 | 987 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
989 | 988 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
990 | 989 | # > <type 'dict'> |
|
991 | 990 | # > >>> print type(__builtins__) |
|
992 | 991 | # > <type 'module'> |
|
993 | 992 | # > Is this difference in return value intentional? |
|
994 | 993 | |
|
995 | 994 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
996 | 995 | # or a module, and it's been that way for a long time. Whether it's |
|
997 | 996 | # intentional (or sensible), I don't know. In any case, the idea is |
|
998 | 997 | # that if you need to access the built-in namespace directly, you |
|
999 | 998 | # should start with "import __builtin__" (note, no 's') which will |
|
1000 | 999 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
1001 | 1000 | |
|
1002 | 1001 | # These routines return a properly built module and dict as needed by |
|
1003 | 1002 | # the rest of the code, and can also be used by extension writers to |
|
1004 | 1003 | # generate properly initialized namespaces. |
|
1005 | 1004 | if (user_ns is not None) or (user_module is not None): |
|
1006 | 1005 | self.default_user_namespaces = False |
|
1007 | 1006 | self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns) |
|
1008 | 1007 | |
|
1009 | 1008 | # A record of hidden variables we have added to the user namespace, so |
|
1010 | 1009 | # we can list later only variables defined in actual interactive use. |
|
1011 | 1010 | self.user_ns_hidden = {} |
|
1012 | 1011 | |
|
1013 | 1012 | # Now that FakeModule produces a real module, we've run into a nasty |
|
1014 | 1013 | # problem: after script execution (via %run), the module where the user |
|
1015 | 1014 | # code ran is deleted. Now that this object is a true module (needed |
|
1016 | 1015 | # so doctest and other tools work correctly), the Python module |
|
1017 | 1016 | # teardown mechanism runs over it, and sets to None every variable |
|
1018 | 1017 | # present in that module. Top-level references to objects from the |
|
1019 | 1018 | # script survive, because the user_ns is updated with them. However, |
|
1020 | 1019 | # calling functions defined in the script that use other things from |
|
1021 | 1020 | # the script will fail, because the function's closure had references |
|
1022 | 1021 | # to the original objects, which are now all None. So we must protect |
|
1023 | 1022 | # these modules from deletion by keeping a cache. |
|
1024 | 1023 | # |
|
1025 | 1024 | # To avoid keeping stale modules around (we only need the one from the |
|
1026 | 1025 | # last run), we use a dict keyed with the full path to the script, so |
|
1027 | 1026 | # only the last version of the module is held in the cache. Note, |
|
1028 | 1027 | # however, that we must cache the module *namespace contents* (their |
|
1029 | 1028 | # __dict__). Because if we try to cache the actual modules, old ones |
|
1030 | 1029 | # (uncached) could be destroyed while still holding references (such as |
|
1031 | 1030 | # those held by GUI objects that tend to be long-lived)> |
|
1032 | 1031 | # |
|
1033 | 1032 | # The %reset command will flush this cache. See the cache_main_mod() |
|
1034 | 1033 | # and clear_main_mod_cache() methods for details on use. |
|
1035 | 1034 | |
|
1036 | 1035 | # This is the cache used for 'main' namespaces |
|
1037 | 1036 | self._main_mod_cache = {} |
|
1038 | 1037 | |
|
1039 | 1038 | # A table holding all the namespaces IPython deals with, so that |
|
1040 | 1039 | # introspection facilities can search easily. |
|
1041 | 1040 | self.ns_table = {'user_global':self.user_module.__dict__, |
|
1042 | 1041 | 'user_local':self.user_ns, |
|
1043 | 1042 | 'builtin':builtin_mod.__dict__ |
|
1044 | 1043 | } |
|
1045 | 1044 | |
|
1046 | 1045 | @property |
|
1047 | 1046 | def user_global_ns(self): |
|
1048 | 1047 | return self.user_module.__dict__ |
|
1049 | 1048 | |
|
1050 | 1049 | def prepare_user_module(self, user_module=None, user_ns=None): |
|
1051 | 1050 | """Prepare the module and namespace in which user code will be run. |
|
1052 | 1051 | |
|
1053 | 1052 | When IPython is started normally, both parameters are None: a new module |
|
1054 | 1053 | is created automatically, and its __dict__ used as the namespace. |
|
1055 | 1054 | |
|
1056 | 1055 | If only user_module is provided, its __dict__ is used as the namespace. |
|
1057 | 1056 | If only user_ns is provided, a dummy module is created, and user_ns |
|
1058 | 1057 | becomes the global namespace. If both are provided (as they may be |
|
1059 | 1058 | when embedding), user_ns is the local namespace, and user_module |
|
1060 | 1059 | provides the global namespace. |
|
1061 | 1060 | |
|
1062 | 1061 | Parameters |
|
1063 | 1062 | ---------- |
|
1064 | 1063 | user_module : module, optional |
|
1065 | 1064 | The current user module in which IPython is being run. If None, |
|
1066 | 1065 | a clean module will be created. |
|
1067 | 1066 | user_ns : dict, optional |
|
1068 | 1067 | A namespace in which to run interactive commands. |
|
1069 | 1068 | |
|
1070 | 1069 | Returns |
|
1071 | 1070 | ------- |
|
1072 | 1071 | A tuple of user_module and user_ns, each properly initialised. |
|
1073 | 1072 | """ |
|
1074 | 1073 | if user_module is None and user_ns is not None: |
|
1075 | 1074 | user_ns.setdefault("__name__", "__main__") |
|
1076 | 1075 | user_module = DummyMod() |
|
1077 | 1076 | user_module.__dict__ = user_ns |
|
1078 | 1077 | |
|
1079 | 1078 | if user_module is None: |
|
1080 | 1079 | user_module = types.ModuleType("__main__", |
|
1081 | 1080 | doc="Automatically created module for IPython interactive environment") |
|
1082 | 1081 | |
|
1083 | 1082 | # We must ensure that __builtin__ (without the final 's') is always |
|
1084 | 1083 | # available and pointing to the __builtin__ *module*. For more details: |
|
1085 | 1084 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
1086 | 1085 | user_module.__dict__.setdefault('__builtin__', builtin_mod) |
|
1087 | 1086 | user_module.__dict__.setdefault('__builtins__', builtin_mod) |
|
1088 | 1087 | |
|
1089 | 1088 | if user_ns is None: |
|
1090 | 1089 | user_ns = user_module.__dict__ |
|
1091 | 1090 | |
|
1092 | 1091 | return user_module, user_ns |
|
1093 | 1092 | |
|
1094 | 1093 | def init_sys_modules(self): |
|
1095 | 1094 | # We need to insert into sys.modules something that looks like a |
|
1096 | 1095 | # module but which accesses the IPython namespace, for shelve and |
|
1097 | 1096 | # pickle to work interactively. Normally they rely on getting |
|
1098 | 1097 | # everything out of __main__, but for embedding purposes each IPython |
|
1099 | 1098 | # instance has its own private namespace, so we can't go shoving |
|
1100 | 1099 | # everything into __main__. |
|
1101 | 1100 | |
|
1102 | 1101 | # note, however, that we should only do this for non-embedded |
|
1103 | 1102 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
1104 | 1103 | # namespace. Embedded instances, on the other hand, should not do |
|
1105 | 1104 | # this because they need to manage the user local/global namespaces |
|
1106 | 1105 | # only, but they live within a 'normal' __main__ (meaning, they |
|
1107 | 1106 | # shouldn't overtake the execution environment of the script they're |
|
1108 | 1107 | # embedded in). |
|
1109 | 1108 | |
|
1110 | 1109 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
1111 | 1110 | main_name = self.user_module.__name__ |
|
1112 | 1111 | sys.modules[main_name] = self.user_module |
|
1113 | 1112 | |
|
1114 | 1113 | def init_user_ns(self): |
|
1115 | 1114 | """Initialize all user-visible namespaces to their minimum defaults. |
|
1116 | 1115 | |
|
1117 | 1116 | Certain history lists are also initialized here, as they effectively |
|
1118 | 1117 | act as user namespaces. |
|
1119 | 1118 | |
|
1120 | 1119 | Notes |
|
1121 | 1120 | ----- |
|
1122 | 1121 | All data structures here are only filled in, they are NOT reset by this |
|
1123 | 1122 | method. If they were not empty before, data will simply be added to |
|
1124 | 1123 | therm. |
|
1125 | 1124 | """ |
|
1126 | 1125 | # This function works in two parts: first we put a few things in |
|
1127 | 1126 | # user_ns, and we sync that contents into user_ns_hidden so that these |
|
1128 | 1127 | # initial variables aren't shown by %who. After the sync, we add the |
|
1129 | 1128 | # rest of what we *do* want the user to see with %who even on a new |
|
1130 | 1129 | # session (probably nothing, so they really only see their own stuff) |
|
1131 | 1130 | |
|
1132 | 1131 | # The user dict must *always* have a __builtin__ reference to the |
|
1133 | 1132 | # Python standard __builtin__ namespace, which must be imported. |
|
1134 | 1133 | # This is so that certain operations in prompt evaluation can be |
|
1135 | 1134 | # reliably executed with builtins. Note that we can NOT use |
|
1136 | 1135 | # __builtins__ (note the 's'), because that can either be a dict or a |
|
1137 | 1136 | # module, and can even mutate at runtime, depending on the context |
|
1138 | 1137 | # (Python makes no guarantees on it). In contrast, __builtin__ is |
|
1139 | 1138 | # always a module object, though it must be explicitly imported. |
|
1140 | 1139 | |
|
1141 | 1140 | # For more details: |
|
1142 | 1141 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
1143 | 1142 | ns = dict() |
|
1144 | 1143 | |
|
1145 | 1144 | # make global variables for user access to the histories |
|
1146 | 1145 | ns['_ih'] = self.history_manager.input_hist_parsed |
|
1147 | 1146 | ns['_oh'] = self.history_manager.output_hist |
|
1148 | 1147 | ns['_dh'] = self.history_manager.dir_hist |
|
1149 | 1148 | |
|
1150 | 1149 | ns['_sh'] = shadowns |
|
1151 | 1150 | |
|
1152 | 1151 | # user aliases to input and output histories. These shouldn't show up |
|
1153 | 1152 | # in %who, as they can have very large reprs. |
|
1154 | 1153 | ns['In'] = self.history_manager.input_hist_parsed |
|
1155 | 1154 | ns['Out'] = self.history_manager.output_hist |
|
1156 | 1155 | |
|
1157 | 1156 | # Store myself as the public api!!! |
|
1158 | 1157 | ns['get_ipython'] = self.get_ipython |
|
1159 | 1158 | |
|
1160 | 1159 | ns['exit'] = self.exiter |
|
1161 | 1160 | ns['quit'] = self.exiter |
|
1162 | 1161 | |
|
1163 | 1162 | # Sync what we've added so far to user_ns_hidden so these aren't seen |
|
1164 | 1163 | # by %who |
|
1165 | 1164 | self.user_ns_hidden.update(ns) |
|
1166 | 1165 | |
|
1167 | 1166 | # Anything put into ns now would show up in %who. Think twice before |
|
1168 | 1167 | # putting anything here, as we really want %who to show the user their |
|
1169 | 1168 | # stuff, not our variables. |
|
1170 | 1169 | |
|
1171 | 1170 | # Finally, update the real user's namespace |
|
1172 | 1171 | self.user_ns.update(ns) |
|
1173 | 1172 | |
|
1174 | 1173 | @property |
|
1175 | 1174 | def all_ns_refs(self): |
|
1176 | 1175 | """Get a list of references to all the namespace dictionaries in which |
|
1177 | 1176 | IPython might store a user-created object. |
|
1178 | 1177 | |
|
1179 | 1178 | Note that this does not include the displayhook, which also caches |
|
1180 | 1179 | objects from the output.""" |
|
1181 | 1180 | return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \ |
|
1182 | 1181 | [m.__dict__ for m in self._main_mod_cache.values()] |
|
1183 | 1182 | |
|
1184 | 1183 | def reset(self, new_session=True): |
|
1185 | 1184 | """Clear all internal namespaces, and attempt to release references to |
|
1186 | 1185 | user objects. |
|
1187 | 1186 | |
|
1188 | 1187 | If new_session is True, a new history session will be opened. |
|
1189 | 1188 | """ |
|
1190 | 1189 | # Clear histories |
|
1191 | 1190 | self.history_manager.reset(new_session) |
|
1192 | 1191 | # Reset counter used to index all histories |
|
1193 | 1192 | if new_session: |
|
1194 | 1193 | self.execution_count = 1 |
|
1195 | 1194 | |
|
1196 | 1195 | # Flush cached output items |
|
1197 | 1196 | if self.displayhook.do_full_cache: |
|
1198 | 1197 | self.displayhook.flush() |
|
1199 | 1198 | |
|
1200 | 1199 | # The main execution namespaces must be cleared very carefully, |
|
1201 | 1200 | # skipping the deletion of the builtin-related keys, because doing so |
|
1202 | 1201 | # would cause errors in many object's __del__ methods. |
|
1203 | 1202 | if self.user_ns is not self.user_global_ns: |
|
1204 | 1203 | self.user_ns.clear() |
|
1205 | 1204 | ns = self.user_global_ns |
|
1206 | 1205 | drop_keys = set(ns.keys()) |
|
1207 | 1206 | drop_keys.discard('__builtin__') |
|
1208 | 1207 | drop_keys.discard('__builtins__') |
|
1209 | 1208 | drop_keys.discard('__name__') |
|
1210 | 1209 | for k in drop_keys: |
|
1211 | 1210 | del ns[k] |
|
1212 | 1211 | |
|
1213 | 1212 | self.user_ns_hidden.clear() |
|
1214 | 1213 | |
|
1215 | 1214 | # Restore the user namespaces to minimal usability |
|
1216 | 1215 | self.init_user_ns() |
|
1217 | 1216 | |
|
1218 | 1217 | # Restore the default and user aliases |
|
1219 | 1218 | self.alias_manager.clear_aliases() |
|
1220 | 1219 | self.alias_manager.init_aliases() |
|
1221 | 1220 | |
|
1222 | 1221 | # Flush the private list of module references kept for script |
|
1223 | 1222 | # execution protection |
|
1224 | 1223 | self.clear_main_mod_cache() |
|
1225 | 1224 | |
|
1226 | 1225 | def del_var(self, varname, by_name=False): |
|
1227 | 1226 | """Delete a variable from the various namespaces, so that, as |
|
1228 | 1227 | far as possible, we're not keeping any hidden references to it. |
|
1229 | 1228 | |
|
1230 | 1229 | Parameters |
|
1231 | 1230 | ---------- |
|
1232 | 1231 | varname : str |
|
1233 | 1232 | The name of the variable to delete. |
|
1234 | 1233 | by_name : bool |
|
1235 | 1234 | If True, delete variables with the given name in each |
|
1236 | 1235 | namespace. If False (default), find the variable in the user |
|
1237 | 1236 | namespace, and delete references to it. |
|
1238 | 1237 | """ |
|
1239 | 1238 | if varname in ('__builtin__', '__builtins__'): |
|
1240 | 1239 | raise ValueError("Refusing to delete %s" % varname) |
|
1241 | 1240 | |
|
1242 | 1241 | ns_refs = self.all_ns_refs |
|
1243 | 1242 | |
|
1244 | 1243 | if by_name: # Delete by name |
|
1245 | 1244 | for ns in ns_refs: |
|
1246 | 1245 | try: |
|
1247 | 1246 | del ns[varname] |
|
1248 | 1247 | except KeyError: |
|
1249 | 1248 | pass |
|
1250 | 1249 | else: # Delete by object |
|
1251 | 1250 | try: |
|
1252 | 1251 | obj = self.user_ns[varname] |
|
1253 | 1252 | except KeyError: |
|
1254 | 1253 | raise NameError("name '%s' is not defined" % varname) |
|
1255 | 1254 | # Also check in output history |
|
1256 | 1255 | ns_refs.append(self.history_manager.output_hist) |
|
1257 | 1256 | for ns in ns_refs: |
|
1258 |
to_delete = [n for n, o in |
|
|
1257 | to_delete = [n for n, o in ns.items() if o is obj] | |
|
1259 | 1258 | for name in to_delete: |
|
1260 | 1259 | del ns[name] |
|
1261 | 1260 | |
|
1262 | 1261 | # displayhook keeps extra references, but not in a dictionary |
|
1263 | 1262 | for name in ('_', '__', '___'): |
|
1264 | 1263 | if getattr(self.displayhook, name) is obj: |
|
1265 | 1264 | setattr(self.displayhook, name, None) |
|
1266 | 1265 | |
|
1267 | 1266 | def reset_selective(self, regex=None): |
|
1268 | 1267 | """Clear selective variables from internal namespaces based on a |
|
1269 | 1268 | specified regular expression. |
|
1270 | 1269 | |
|
1271 | 1270 | Parameters |
|
1272 | 1271 | ---------- |
|
1273 | 1272 | regex : string or compiled pattern, optional |
|
1274 | 1273 | A regular expression pattern that will be used in searching |
|
1275 | 1274 | variable names in the users namespaces. |
|
1276 | 1275 | """ |
|
1277 | 1276 | if regex is not None: |
|
1278 | 1277 | try: |
|
1279 | 1278 | m = re.compile(regex) |
|
1280 | 1279 | except TypeError: |
|
1281 | 1280 | raise TypeError('regex must be a string or compiled pattern') |
|
1282 | 1281 | # Search for keys in each namespace that match the given regex |
|
1283 | 1282 | # If a match is found, delete the key/value pair. |
|
1284 | 1283 | for ns in self.all_ns_refs: |
|
1285 | 1284 | for var in ns: |
|
1286 | 1285 | if m.search(var): |
|
1287 | 1286 | del ns[var] |
|
1288 | 1287 | |
|
1289 | 1288 | def push(self, variables, interactive=True): |
|
1290 | 1289 | """Inject a group of variables into the IPython user namespace. |
|
1291 | 1290 | |
|
1292 | 1291 | Parameters |
|
1293 | 1292 | ---------- |
|
1294 | 1293 | variables : dict, str or list/tuple of str |
|
1295 | 1294 | The variables to inject into the user's namespace. If a dict, a |
|
1296 | 1295 | simple update is done. If a str, the string is assumed to have |
|
1297 | 1296 | variable names separated by spaces. A list/tuple of str can also |
|
1298 | 1297 | be used to give the variable names. If just the variable names are |
|
1299 | 1298 | give (list/tuple/str) then the variable values looked up in the |
|
1300 | 1299 | callers frame. |
|
1301 | 1300 | interactive : bool |
|
1302 | 1301 | If True (default), the variables will be listed with the ``who`` |
|
1303 | 1302 | magic. |
|
1304 | 1303 | """ |
|
1305 | 1304 | vdict = None |
|
1306 | 1305 | |
|
1307 | 1306 | # We need a dict of name/value pairs to do namespace updates. |
|
1308 | 1307 | if isinstance(variables, dict): |
|
1309 | 1308 | vdict = variables |
|
1310 |
elif isinstance(variables, |
|
|
1311 |
if isinstance(variables, str |
|
|
1309 | elif isinstance(variables, (str, list, tuple)): | |
|
1310 | if isinstance(variables, str): | |
|
1312 | 1311 | vlist = variables.split() |
|
1313 | 1312 | else: |
|
1314 | 1313 | vlist = variables |
|
1315 | 1314 | vdict = {} |
|
1316 | 1315 | cf = sys._getframe(1) |
|
1317 | 1316 | for name in vlist: |
|
1318 | 1317 | try: |
|
1319 | 1318 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1320 | 1319 | except: |
|
1321 | 1320 | print('Could not get variable %s from %s' % |
|
1322 | 1321 | (name,cf.f_code.co_name)) |
|
1323 | 1322 | else: |
|
1324 | 1323 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1325 | 1324 | |
|
1326 | 1325 | # Propagate variables to user namespace |
|
1327 | 1326 | self.user_ns.update(vdict) |
|
1328 | 1327 | |
|
1329 | 1328 | # And configure interactive visibility |
|
1330 | 1329 | user_ns_hidden = self.user_ns_hidden |
|
1331 | 1330 | if interactive: |
|
1332 | 1331 | for name in vdict: |
|
1333 | 1332 | user_ns_hidden.pop(name, None) |
|
1334 | 1333 | else: |
|
1335 | 1334 | user_ns_hidden.update(vdict) |
|
1336 | 1335 | |
|
1337 | 1336 | def drop_by_id(self, variables): |
|
1338 | 1337 | """Remove a dict of variables from the user namespace, if they are the |
|
1339 | 1338 | same as the values in the dictionary. |
|
1340 | 1339 | |
|
1341 | 1340 | This is intended for use by extensions: variables that they've added can |
|
1342 | 1341 | be taken back out if they are unloaded, without removing any that the |
|
1343 | 1342 | user has overwritten. |
|
1344 | 1343 | |
|
1345 | 1344 | Parameters |
|
1346 | 1345 | ---------- |
|
1347 | 1346 | variables : dict |
|
1348 | 1347 | A dictionary mapping object names (as strings) to the objects. |
|
1349 | 1348 | """ |
|
1350 |
for name, obj in |
|
|
1349 | for name, obj in variables.items(): | |
|
1351 | 1350 | if name in self.user_ns and self.user_ns[name] is obj: |
|
1352 | 1351 | del self.user_ns[name] |
|
1353 | 1352 | self.user_ns_hidden.pop(name, None) |
|
1354 | 1353 | |
|
1355 | 1354 | #------------------------------------------------------------------------- |
|
1356 | 1355 | # Things related to object introspection |
|
1357 | 1356 | #------------------------------------------------------------------------- |
|
1358 | 1357 | |
|
1359 | 1358 | def _ofind(self, oname, namespaces=None): |
|
1360 | 1359 | """Find an object in the available namespaces. |
|
1361 | 1360 | |
|
1362 | 1361 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
1363 | 1362 | |
|
1364 | 1363 | Has special code to detect magic functions. |
|
1365 | 1364 | """ |
|
1366 | 1365 | oname = oname.strip() |
|
1367 | 1366 | #print '1- oname: <%r>' % oname # dbg |
|
1368 | 1367 | if not oname.startswith(ESC_MAGIC) and \ |
|
1369 | 1368 | not oname.startswith(ESC_MAGIC2) and \ |
|
1370 | 1369 | not py3compat.isidentifier(oname, dotted=True): |
|
1371 | 1370 | return dict(found=False) |
|
1372 | 1371 | |
|
1373 | 1372 | if namespaces is None: |
|
1374 | 1373 | # Namespaces to search in: |
|
1375 | 1374 | # Put them in a list. The order is important so that we |
|
1376 | 1375 | # find things in the same order that Python finds them. |
|
1377 | 1376 | namespaces = [ ('Interactive', self.user_ns), |
|
1378 | 1377 | ('Interactive (global)', self.user_global_ns), |
|
1379 | 1378 | ('Python builtin', builtin_mod.__dict__), |
|
1380 | 1379 | ] |
|
1381 | 1380 | |
|
1382 | 1381 | # initialize results to 'null' |
|
1383 | 1382 | found = False; obj = None; ospace = None; |
|
1384 | 1383 | ismagic = False; isalias = False; parent = None |
|
1385 | 1384 | |
|
1386 | 1385 | # We need to special-case 'print', which as of python2.6 registers as a |
|
1387 | 1386 | # function but should only be treated as one if print_function was |
|
1388 | 1387 | # loaded with a future import. In this case, just bail. |
|
1389 | 1388 | if (oname == 'print' and not py3compat.PY3 and not \ |
|
1390 | 1389 | (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)): |
|
1391 | 1390 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1392 | 1391 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1393 | 1392 | |
|
1394 | 1393 | # Look for the given name by splitting it in parts. If the head is |
|
1395 | 1394 | # found, then we look for all the remaining parts as members, and only |
|
1396 | 1395 | # declare success if we can find them all. |
|
1397 | 1396 | oname_parts = oname.split('.') |
|
1398 | 1397 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
1399 | 1398 | for nsname,ns in namespaces: |
|
1400 | 1399 | try: |
|
1401 | 1400 | obj = ns[oname_head] |
|
1402 | 1401 | except KeyError: |
|
1403 | 1402 | continue |
|
1404 | 1403 | else: |
|
1405 | 1404 | #print 'oname_rest:', oname_rest # dbg |
|
1406 | 1405 | for idx, part in enumerate(oname_rest): |
|
1407 | 1406 | try: |
|
1408 | 1407 | parent = obj |
|
1409 | 1408 | # The last part is looked up in a special way to avoid |
|
1410 | 1409 | # descriptor invocation as it may raise or have side |
|
1411 | 1410 | # effects. |
|
1412 | 1411 | if idx == len(oname_rest) - 1: |
|
1413 | 1412 | obj = self._getattr_property(obj, part) |
|
1414 | 1413 | else: |
|
1415 | 1414 | obj = getattr(obj, part) |
|
1416 | 1415 | except: |
|
1417 | 1416 | # Blanket except b/c some badly implemented objects |
|
1418 | 1417 | # allow __getattr__ to raise exceptions other than |
|
1419 | 1418 | # AttributeError, which then crashes IPython. |
|
1420 | 1419 | break |
|
1421 | 1420 | else: |
|
1422 | 1421 | # If we finish the for loop (no break), we got all members |
|
1423 | 1422 | found = True |
|
1424 | 1423 | ospace = nsname |
|
1425 | 1424 | break # namespace loop |
|
1426 | 1425 | |
|
1427 | 1426 | # Try to see if it's magic |
|
1428 | 1427 | if not found: |
|
1429 | 1428 | obj = None |
|
1430 | 1429 | if oname.startswith(ESC_MAGIC2): |
|
1431 | 1430 | oname = oname.lstrip(ESC_MAGIC2) |
|
1432 | 1431 | obj = self.find_cell_magic(oname) |
|
1433 | 1432 | elif oname.startswith(ESC_MAGIC): |
|
1434 | 1433 | oname = oname.lstrip(ESC_MAGIC) |
|
1435 | 1434 | obj = self.find_line_magic(oname) |
|
1436 | 1435 | else: |
|
1437 | 1436 | # search without prefix, so run? will find %run? |
|
1438 | 1437 | obj = self.find_line_magic(oname) |
|
1439 | 1438 | if obj is None: |
|
1440 | 1439 | obj = self.find_cell_magic(oname) |
|
1441 | 1440 | if obj is not None: |
|
1442 | 1441 | found = True |
|
1443 | 1442 | ospace = 'IPython internal' |
|
1444 | 1443 | ismagic = True |
|
1445 | 1444 | isalias = isinstance(obj, Alias) |
|
1446 | 1445 | |
|
1447 | 1446 | # Last try: special-case some literals like '', [], {}, etc: |
|
1448 | 1447 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
1449 | 1448 | obj = eval(oname_head) |
|
1450 | 1449 | found = True |
|
1451 | 1450 | ospace = 'Interactive' |
|
1452 | 1451 | |
|
1453 | 1452 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1454 | 1453 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1455 | 1454 | |
|
1456 | 1455 | @staticmethod |
|
1457 | 1456 | def _getattr_property(obj, attrname): |
|
1458 | 1457 | """Property-aware getattr to use in object finding. |
|
1459 | 1458 | |
|
1460 | 1459 | If attrname represents a property, return it unevaluated (in case it has |
|
1461 | 1460 | side effects or raises an error. |
|
1462 | 1461 | |
|
1463 | 1462 | """ |
|
1464 | 1463 | if not isinstance(obj, type): |
|
1465 | 1464 | try: |
|
1466 | 1465 | # `getattr(type(obj), attrname)` is not guaranteed to return |
|
1467 | 1466 | # `obj`, but does so for property: |
|
1468 | 1467 | # |
|
1469 | 1468 | # property.__get__(self, None, cls) -> self |
|
1470 | 1469 | # |
|
1471 | 1470 | # The universal alternative is to traverse the mro manually |
|
1472 | 1471 | # searching for attrname in class dicts. |
|
1473 | 1472 | attr = getattr(type(obj), attrname) |
|
1474 | 1473 | except AttributeError: |
|
1475 | 1474 | pass |
|
1476 | 1475 | else: |
|
1477 | 1476 | # This relies on the fact that data descriptors (with both |
|
1478 | 1477 | # __get__ & __set__ magic methods) take precedence over |
|
1479 | 1478 | # instance-level attributes: |
|
1480 | 1479 | # |
|
1481 | 1480 | # class A(object): |
|
1482 | 1481 | # @property |
|
1483 | 1482 | # def foobar(self): return 123 |
|
1484 | 1483 | # a = A() |
|
1485 | 1484 | # a.__dict__['foobar'] = 345 |
|
1486 | 1485 | # a.foobar # == 123 |
|
1487 | 1486 | # |
|
1488 | 1487 | # So, a property may be returned right away. |
|
1489 | 1488 | if isinstance(attr, property): |
|
1490 | 1489 | return attr |
|
1491 | 1490 | |
|
1492 | 1491 | # Nothing helped, fall back. |
|
1493 | 1492 | return getattr(obj, attrname) |
|
1494 | 1493 | |
|
1495 | 1494 | def _object_find(self, oname, namespaces=None): |
|
1496 | 1495 | """Find an object and return a struct with info about it.""" |
|
1497 | 1496 | return Struct(self._ofind(oname, namespaces)) |
|
1498 | 1497 | |
|
1499 | 1498 | def _inspect(self, meth, oname, namespaces=None, **kw): |
|
1500 | 1499 | """Generic interface to the inspector system. |
|
1501 | 1500 | |
|
1502 | 1501 | This function is meant to be called by pdef, pdoc & friends. |
|
1503 | 1502 | """ |
|
1504 | 1503 | info = self._object_find(oname, namespaces) |
|
1505 | 1504 | docformat = sphinxify if self.sphinxify_docstring else None |
|
1506 | 1505 | if info.found: |
|
1507 | 1506 | pmethod = getattr(self.inspector, meth) |
|
1508 | 1507 | # TODO: only apply format_screen to the plain/text repr of the mime |
|
1509 | 1508 | # bundle. |
|
1510 | 1509 | formatter = format_screen if info.ismagic else docformat |
|
1511 | 1510 | if meth == 'pdoc': |
|
1512 | 1511 | pmethod(info.obj, oname, formatter) |
|
1513 | 1512 | elif meth == 'pinfo': |
|
1514 | 1513 | pmethod(info.obj, oname, formatter, info, |
|
1515 | 1514 | enable_html_pager=self.enable_html_pager, **kw) |
|
1516 | 1515 | else: |
|
1517 | 1516 | pmethod(info.obj, oname) |
|
1518 | 1517 | else: |
|
1519 | 1518 | print('Object `%s` not found.' % oname) |
|
1520 | 1519 | return 'not found' # so callers can take other action |
|
1521 | 1520 | |
|
1522 | 1521 | def object_inspect(self, oname, detail_level=0): |
|
1523 | 1522 | """Get object info about oname""" |
|
1524 | 1523 | with self.builtin_trap: |
|
1525 | 1524 | info = self._object_find(oname) |
|
1526 | 1525 | if info.found: |
|
1527 | 1526 | return self.inspector.info(info.obj, oname, info=info, |
|
1528 | 1527 | detail_level=detail_level |
|
1529 | 1528 | ) |
|
1530 | 1529 | else: |
|
1531 | 1530 | return oinspect.object_info(name=oname, found=False) |
|
1532 | 1531 | |
|
1533 | 1532 | def object_inspect_text(self, oname, detail_level=0): |
|
1534 | 1533 | """Get object info as formatted text""" |
|
1535 | 1534 | return self.object_inspect_mime(oname, detail_level)['text/plain'] |
|
1536 | 1535 | |
|
1537 | 1536 | def object_inspect_mime(self, oname, detail_level=0): |
|
1538 | 1537 | """Get object info as a mimebundle of formatted representations. |
|
1539 | 1538 | |
|
1540 | 1539 | A mimebundle is a dictionary, keyed by mime-type. |
|
1541 | 1540 | It must always have the key `'text/plain'`. |
|
1542 | 1541 | """ |
|
1543 | 1542 | with self.builtin_trap: |
|
1544 | 1543 | info = self._object_find(oname) |
|
1545 | 1544 | if info.found: |
|
1546 | 1545 | return self.inspector._get_info(info.obj, oname, info=info, |
|
1547 | 1546 | detail_level=detail_level |
|
1548 | 1547 | ) |
|
1549 | 1548 | else: |
|
1550 | 1549 | raise KeyError(oname) |
|
1551 | 1550 | |
|
1552 | 1551 | #------------------------------------------------------------------------- |
|
1553 | 1552 | # Things related to history management |
|
1554 | 1553 | #------------------------------------------------------------------------- |
|
1555 | 1554 | |
|
1556 | 1555 | def init_history(self): |
|
1557 | 1556 | """Sets up the command history, and starts regular autosaves.""" |
|
1558 | 1557 | self.history_manager = HistoryManager(shell=self, parent=self) |
|
1559 | 1558 | self.configurables.append(self.history_manager) |
|
1560 | 1559 | |
|
1561 | 1560 | #------------------------------------------------------------------------- |
|
1562 | 1561 | # Things related to exception handling and tracebacks (not debugging) |
|
1563 | 1562 | #------------------------------------------------------------------------- |
|
1564 | 1563 | |
|
1565 | 1564 | debugger_cls = Pdb |
|
1566 | 1565 | |
|
1567 | 1566 | def init_traceback_handlers(self, custom_exceptions): |
|
1568 | 1567 | # Syntax error handler. |
|
1569 | 1568 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self) |
|
1570 | 1569 | |
|
1571 | 1570 | # The interactive one is initialized with an offset, meaning we always |
|
1572 | 1571 | # want to remove the topmost item in the traceback, which is our own |
|
1573 | 1572 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1574 | 1573 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1575 | 1574 | color_scheme='NoColor', |
|
1576 | 1575 | tb_offset = 1, |
|
1577 | 1576 | check_cache=check_linecache_ipython, |
|
1578 | 1577 | debugger_cls=self.debugger_cls, parent=self) |
|
1579 | 1578 | |
|
1580 | 1579 | # The instance will store a pointer to the system-wide exception hook, |
|
1581 | 1580 | # so that runtime code (such as magics) can access it. This is because |
|
1582 | 1581 | # during the read-eval loop, it may get temporarily overwritten. |
|
1583 | 1582 | self.sys_excepthook = sys.excepthook |
|
1584 | 1583 | |
|
1585 | 1584 | # and add any custom exception handlers the user may have specified |
|
1586 | 1585 | self.set_custom_exc(*custom_exceptions) |
|
1587 | 1586 | |
|
1588 | 1587 | # Set the exception mode |
|
1589 | 1588 | self.InteractiveTB.set_mode(mode=self.xmode) |
|
1590 | 1589 | |
|
1591 | 1590 | def set_custom_exc(self, exc_tuple, handler): |
|
1592 | 1591 | """set_custom_exc(exc_tuple, handler) |
|
1593 | 1592 | |
|
1594 | 1593 | Set a custom exception handler, which will be called if any of the |
|
1595 | 1594 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1596 | 1595 | run_code() method). |
|
1597 | 1596 | |
|
1598 | 1597 | Parameters |
|
1599 | 1598 | ---------- |
|
1600 | 1599 | |
|
1601 | 1600 | exc_tuple : tuple of exception classes |
|
1602 | 1601 | A *tuple* of exception classes, for which to call the defined |
|
1603 | 1602 | handler. It is very important that you use a tuple, and NOT A |
|
1604 | 1603 | LIST here, because of the way Python's except statement works. If |
|
1605 | 1604 | you only want to trap a single exception, use a singleton tuple:: |
|
1606 | 1605 | |
|
1607 | 1606 | exc_tuple == (MyCustomException,) |
|
1608 | 1607 | |
|
1609 | 1608 | handler : callable |
|
1610 | 1609 | handler must have the following signature:: |
|
1611 | 1610 | |
|
1612 | 1611 | def my_handler(self, etype, value, tb, tb_offset=None): |
|
1613 | 1612 | ... |
|
1614 | 1613 | return structured_traceback |
|
1615 | 1614 | |
|
1616 | 1615 | Your handler must return a structured traceback (a list of strings), |
|
1617 | 1616 | or None. |
|
1618 | 1617 | |
|
1619 | 1618 | This will be made into an instance method (via types.MethodType) |
|
1620 | 1619 | of IPython itself, and it will be called if any of the exceptions |
|
1621 | 1620 | listed in the exc_tuple are caught. If the handler is None, an |
|
1622 | 1621 | internal basic one is used, which just prints basic info. |
|
1623 | 1622 | |
|
1624 | 1623 | To protect IPython from crashes, if your handler ever raises an |
|
1625 | 1624 | exception or returns an invalid result, it will be immediately |
|
1626 | 1625 | disabled. |
|
1627 | 1626 | |
|
1628 | 1627 | WARNING: by putting in your own exception handler into IPython's main |
|
1629 | 1628 | execution loop, you run a very good chance of nasty crashes. This |
|
1630 | 1629 | facility should only be used if you really know what you are doing.""" |
|
1631 | 1630 | |
|
1632 | 1631 | assert type(exc_tuple)==type(()) , \ |
|
1633 | 1632 | "The custom exceptions must be given AS A TUPLE." |
|
1634 | 1633 | |
|
1635 | 1634 | def dummy_handler(self, etype, value, tb, tb_offset=None): |
|
1636 | 1635 | print('*** Simple custom exception handler ***') |
|
1637 | 1636 | print('Exception type :',etype) |
|
1638 | 1637 | print('Exception value:',value) |
|
1639 | 1638 | print('Traceback :',tb) |
|
1640 | 1639 | #print 'Source code :','\n'.join(self.buffer) |
|
1641 | 1640 | |
|
1642 | 1641 | def validate_stb(stb): |
|
1643 | 1642 | """validate structured traceback return type |
|
1644 | 1643 | |
|
1645 | 1644 | return type of CustomTB *should* be a list of strings, but allow |
|
1646 | 1645 | single strings or None, which are harmless. |
|
1647 | 1646 | |
|
1648 | 1647 | This function will *always* return a list of strings, |
|
1649 | 1648 | and will raise a TypeError if stb is inappropriate. |
|
1650 | 1649 | """ |
|
1651 | 1650 | msg = "CustomTB must return list of strings, not %r" % stb |
|
1652 | 1651 | if stb is None: |
|
1653 | 1652 | return [] |
|
1654 |
elif isinstance(stb, str |
|
|
1653 | elif isinstance(stb, str): | |
|
1655 | 1654 | return [stb] |
|
1656 | 1655 | elif not isinstance(stb, list): |
|
1657 | 1656 | raise TypeError(msg) |
|
1658 | 1657 | # it's a list |
|
1659 | 1658 | for line in stb: |
|
1660 | 1659 | # check every element |
|
1661 |
if not isinstance(line, str |
|
|
1660 | if not isinstance(line, str): | |
|
1662 | 1661 | raise TypeError(msg) |
|
1663 | 1662 | return stb |
|
1664 | 1663 | |
|
1665 | 1664 | if handler is None: |
|
1666 | 1665 | wrapped = dummy_handler |
|
1667 | 1666 | else: |
|
1668 | 1667 | def wrapped(self,etype,value,tb,tb_offset=None): |
|
1669 | 1668 | """wrap CustomTB handler, to protect IPython from user code |
|
1670 | 1669 | |
|
1671 | 1670 | This makes it harder (but not impossible) for custom exception |
|
1672 | 1671 | handlers to crash IPython. |
|
1673 | 1672 | """ |
|
1674 | 1673 | try: |
|
1675 | 1674 | stb = handler(self,etype,value,tb,tb_offset=tb_offset) |
|
1676 | 1675 | return validate_stb(stb) |
|
1677 | 1676 | except: |
|
1678 | 1677 | # clear custom handler immediately |
|
1679 | 1678 | self.set_custom_exc((), None) |
|
1680 | 1679 | print("Custom TB Handler failed, unregistering", file=sys.stderr) |
|
1681 | 1680 | # show the exception in handler first |
|
1682 | 1681 | stb = self.InteractiveTB.structured_traceback(*sys.exc_info()) |
|
1683 | 1682 | print(self.InteractiveTB.stb2text(stb)) |
|
1684 | 1683 | print("The original exception:") |
|
1685 | 1684 | stb = self.InteractiveTB.structured_traceback( |
|
1686 | 1685 | (etype,value,tb), tb_offset=tb_offset |
|
1687 | 1686 | ) |
|
1688 | 1687 | return stb |
|
1689 | 1688 | |
|
1690 | 1689 | self.CustomTB = types.MethodType(wrapped,self) |
|
1691 | 1690 | self.custom_exceptions = exc_tuple |
|
1692 | 1691 | |
|
1693 | 1692 | def excepthook(self, etype, value, tb): |
|
1694 | 1693 | """One more defense for GUI apps that call sys.excepthook. |
|
1695 | 1694 | |
|
1696 | 1695 | GUI frameworks like wxPython trap exceptions and call |
|
1697 | 1696 | sys.excepthook themselves. I guess this is a feature that |
|
1698 | 1697 | enables them to keep running after exceptions that would |
|
1699 | 1698 | otherwise kill their mainloop. This is a bother for IPython |
|
1700 | 1699 | which excepts to catch all of the program exceptions with a try: |
|
1701 | 1700 | except: statement. |
|
1702 | 1701 | |
|
1703 | 1702 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1704 | 1703 | any app directly invokes sys.excepthook, it will look to the user like |
|
1705 | 1704 | IPython crashed. In order to work around this, we can disable the |
|
1706 | 1705 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1707 | 1706 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1708 | 1707 | call sys.excepthook will generate a regular-looking exception from |
|
1709 | 1708 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1710 | 1709 | crashes. |
|
1711 | 1710 | |
|
1712 | 1711 | This hook should be used sparingly, only in places which are not likely |
|
1713 | 1712 | to be true IPython errors. |
|
1714 | 1713 | """ |
|
1715 | 1714 | self.showtraceback((etype, value, tb), tb_offset=0) |
|
1716 | 1715 | |
|
1717 | 1716 | def _get_exc_info(self, exc_tuple=None): |
|
1718 | 1717 | """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc. |
|
1719 | 1718 | |
|
1720 | 1719 | Ensures sys.last_type,value,traceback hold the exc_info we found, |
|
1721 | 1720 | from whichever source. |
|
1722 | 1721 | |
|
1723 | 1722 | raises ValueError if none of these contain any information |
|
1724 | 1723 | """ |
|
1725 | 1724 | if exc_tuple is None: |
|
1726 | 1725 | etype, value, tb = sys.exc_info() |
|
1727 | 1726 | else: |
|
1728 | 1727 | etype, value, tb = exc_tuple |
|
1729 | 1728 | |
|
1730 | 1729 | if etype is None: |
|
1731 | 1730 | if hasattr(sys, 'last_type'): |
|
1732 | 1731 | etype, value, tb = sys.last_type, sys.last_value, \ |
|
1733 | 1732 | sys.last_traceback |
|
1734 | 1733 | |
|
1735 | 1734 | if etype is None: |
|
1736 | 1735 | raise ValueError("No exception to find") |
|
1737 | 1736 | |
|
1738 | 1737 | # Now store the exception info in sys.last_type etc. |
|
1739 | 1738 | # WARNING: these variables are somewhat deprecated and not |
|
1740 | 1739 | # necessarily safe to use in a threaded environment, but tools |
|
1741 | 1740 | # like pdb depend on their existence, so let's set them. If we |
|
1742 | 1741 | # find problems in the field, we'll need to revisit their use. |
|
1743 | 1742 | sys.last_type = etype |
|
1744 | 1743 | sys.last_value = value |
|
1745 | 1744 | sys.last_traceback = tb |
|
1746 | 1745 | |
|
1747 | 1746 | return etype, value, tb |
|
1748 | 1747 | |
|
1749 | 1748 | def show_usage_error(self, exc): |
|
1750 | 1749 | """Show a short message for UsageErrors |
|
1751 | 1750 | |
|
1752 | 1751 | These are special exceptions that shouldn't show a traceback. |
|
1753 | 1752 | """ |
|
1754 | 1753 | print("UsageError: %s" % exc, file=sys.stderr) |
|
1755 | 1754 | |
|
1756 | 1755 | def get_exception_only(self, exc_tuple=None): |
|
1757 | 1756 | """ |
|
1758 | 1757 | Return as a string (ending with a newline) the exception that |
|
1759 | 1758 | just occurred, without any traceback. |
|
1760 | 1759 | """ |
|
1761 | 1760 | etype, value, tb = self._get_exc_info(exc_tuple) |
|
1762 | 1761 | msg = traceback.format_exception_only(etype, value) |
|
1763 | 1762 | return ''.join(msg) |
|
1764 | 1763 | |
|
1765 | 1764 | def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None, |
|
1766 | 1765 | exception_only=False): |
|
1767 | 1766 | """Display the exception that just occurred. |
|
1768 | 1767 | |
|
1769 | 1768 | If nothing is known about the exception, this is the method which |
|
1770 | 1769 | should be used throughout the code for presenting user tracebacks, |
|
1771 | 1770 | rather than directly invoking the InteractiveTB object. |
|
1772 | 1771 | |
|
1773 | 1772 | A specific showsyntaxerror() also exists, but this method can take |
|
1774 | 1773 | care of calling it if needed, so unless you are explicitly catching a |
|
1775 | 1774 | SyntaxError exception, don't try to analyze the stack manually and |
|
1776 | 1775 | simply call this method.""" |
|
1777 | 1776 | |
|
1778 | 1777 | try: |
|
1779 | 1778 | try: |
|
1780 | 1779 | etype, value, tb = self._get_exc_info(exc_tuple) |
|
1781 | 1780 | except ValueError: |
|
1782 | 1781 | print('No traceback available to show.', file=sys.stderr) |
|
1783 | 1782 | return |
|
1784 | 1783 | |
|
1785 | 1784 | if issubclass(etype, SyntaxError): |
|
1786 | 1785 | # Though this won't be called by syntax errors in the input |
|
1787 | 1786 | # line, there may be SyntaxError cases with imported code. |
|
1788 | 1787 | self.showsyntaxerror(filename) |
|
1789 | 1788 | elif etype is UsageError: |
|
1790 | 1789 | self.show_usage_error(value) |
|
1791 | 1790 | else: |
|
1792 | 1791 | if exception_only: |
|
1793 | 1792 | stb = ['An exception has occurred, use %tb to see ' |
|
1794 | 1793 | 'the full traceback.\n'] |
|
1795 | 1794 | stb.extend(self.InteractiveTB.get_exception_only(etype, |
|
1796 | 1795 | value)) |
|
1797 | 1796 | else: |
|
1798 | 1797 | try: |
|
1799 | 1798 | # Exception classes can customise their traceback - we |
|
1800 | 1799 | # use this in IPython.parallel for exceptions occurring |
|
1801 | 1800 | # in the engines. This should return a list of strings. |
|
1802 | 1801 | stb = value._render_traceback_() |
|
1803 | 1802 | except Exception: |
|
1804 | 1803 | stb = self.InteractiveTB.structured_traceback(etype, |
|
1805 | 1804 | value, tb, tb_offset=tb_offset) |
|
1806 | 1805 | |
|
1807 | 1806 | self._showtraceback(etype, value, stb) |
|
1808 | 1807 | if self.call_pdb: |
|
1809 | 1808 | # drop into debugger |
|
1810 | 1809 | self.debugger(force=True) |
|
1811 | 1810 | return |
|
1812 | 1811 | |
|
1813 | 1812 | # Actually show the traceback |
|
1814 | 1813 | self._showtraceback(etype, value, stb) |
|
1815 | 1814 | |
|
1816 | 1815 | except KeyboardInterrupt: |
|
1817 | 1816 | print('\n' + self.get_exception_only(), file=sys.stderr) |
|
1818 | 1817 | |
|
1819 | 1818 | def _showtraceback(self, etype, evalue, stb): |
|
1820 | 1819 | """Actually show a traceback. |
|
1821 | 1820 | |
|
1822 | 1821 | Subclasses may override this method to put the traceback on a different |
|
1823 | 1822 | place, like a side channel. |
|
1824 | 1823 | """ |
|
1825 | 1824 | print(self.InteractiveTB.stb2text(stb)) |
|
1826 | 1825 | |
|
1827 | 1826 | def showsyntaxerror(self, filename=None): |
|
1828 | 1827 | """Display the syntax error that just occurred. |
|
1829 | 1828 | |
|
1830 | 1829 | This doesn't display a stack trace because there isn't one. |
|
1831 | 1830 | |
|
1832 | 1831 | If a filename is given, it is stuffed in the exception instead |
|
1833 | 1832 | of what was there before (because Python's parser always uses |
|
1834 | 1833 | "<string>" when reading from a string). |
|
1835 | 1834 | """ |
|
1836 | 1835 | etype, value, last_traceback = self._get_exc_info() |
|
1837 | 1836 | |
|
1838 | 1837 | if filename and issubclass(etype, SyntaxError): |
|
1839 | 1838 | try: |
|
1840 | 1839 | value.filename = filename |
|
1841 | 1840 | except: |
|
1842 | 1841 | # Not the format we expect; leave it alone |
|
1843 | 1842 | pass |
|
1844 | 1843 | |
|
1845 | 1844 | stb = self.SyntaxTB.structured_traceback(etype, value, []) |
|
1846 | 1845 | self._showtraceback(etype, value, stb) |
|
1847 | 1846 | |
|
1848 | 1847 | # This is overridden in TerminalInteractiveShell to show a message about |
|
1849 | 1848 | # the %paste magic. |
|
1850 | 1849 | def showindentationerror(self): |
|
1851 | 1850 | """Called by run_cell when there's an IndentationError in code entered |
|
1852 | 1851 | at the prompt. |
|
1853 | 1852 | |
|
1854 | 1853 | This is overridden in TerminalInteractiveShell to show a message about |
|
1855 | 1854 | the %paste magic.""" |
|
1856 | 1855 | self.showsyntaxerror() |
|
1857 | 1856 | |
|
1858 | 1857 | #------------------------------------------------------------------------- |
|
1859 | 1858 | # Things related to readline |
|
1860 | 1859 | #------------------------------------------------------------------------- |
|
1861 | 1860 | |
|
1862 | 1861 | def init_readline(self): |
|
1863 | 1862 | """DEPRECATED |
|
1864 | 1863 | |
|
1865 | 1864 | Moved to terminal subclass, here only to simplify the init logic.""" |
|
1866 | 1865 | # Set a number of methods that depend on readline to be no-op |
|
1867 | 1866 | warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated', |
|
1868 | 1867 | DeprecationWarning, stacklevel=2) |
|
1869 | 1868 | self.set_custom_completer = no_op |
|
1870 | 1869 | |
|
1871 | 1870 | @skip_doctest |
|
1872 | 1871 | def set_next_input(self, s, replace=False): |
|
1873 | 1872 | """ Sets the 'default' input string for the next command line. |
|
1874 | 1873 | |
|
1875 | 1874 | Example:: |
|
1876 | 1875 | |
|
1877 | 1876 | In [1]: _ip.set_next_input("Hello Word") |
|
1878 | 1877 | In [2]: Hello Word_ # cursor is here |
|
1879 | 1878 | """ |
|
1880 | 1879 | self.rl_next_input = py3compat.cast_bytes_py2(s) |
|
1881 | 1880 | |
|
1882 | 1881 | def _indent_current_str(self): |
|
1883 | 1882 | """return the current level of indentation as a string""" |
|
1884 | 1883 | return self.input_splitter.indent_spaces * ' ' |
|
1885 | 1884 | |
|
1886 | 1885 | #------------------------------------------------------------------------- |
|
1887 | 1886 | # Things related to text completion |
|
1888 | 1887 | #------------------------------------------------------------------------- |
|
1889 | 1888 | |
|
1890 | 1889 | def init_completer(self): |
|
1891 | 1890 | """Initialize the completion machinery. |
|
1892 | 1891 | |
|
1893 | 1892 | This creates completion machinery that can be used by client code, |
|
1894 | 1893 | either interactively in-process (typically triggered by the readline |
|
1895 | 1894 | library), programmatically (such as in test suites) or out-of-process |
|
1896 | 1895 | (typically over the network by remote frontends). |
|
1897 | 1896 | """ |
|
1898 | 1897 | from IPython.core.completer import IPCompleter |
|
1899 | 1898 | from IPython.core.completerlib import (module_completer, |
|
1900 | 1899 | magic_run_completer, cd_completer, reset_completer) |
|
1901 | 1900 | |
|
1902 | 1901 | self.Completer = IPCompleter(shell=self, |
|
1903 | 1902 | namespace=self.user_ns, |
|
1904 | 1903 | global_namespace=self.user_global_ns, |
|
1905 | 1904 | parent=self, |
|
1906 | 1905 | ) |
|
1907 | 1906 | self.configurables.append(self.Completer) |
|
1908 | 1907 | |
|
1909 | 1908 | # Add custom completers to the basic ones built into IPCompleter |
|
1910 | 1909 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1911 | 1910 | self.strdispatchers['complete_command'] = sdisp |
|
1912 | 1911 | self.Completer.custom_completers = sdisp |
|
1913 | 1912 | |
|
1914 | 1913 | self.set_hook('complete_command', module_completer, str_key = 'import') |
|
1915 | 1914 | self.set_hook('complete_command', module_completer, str_key = 'from') |
|
1916 | 1915 | self.set_hook('complete_command', module_completer, str_key = '%aimport') |
|
1917 | 1916 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') |
|
1918 | 1917 | self.set_hook('complete_command', cd_completer, str_key = '%cd') |
|
1919 | 1918 | self.set_hook('complete_command', reset_completer, str_key = '%reset') |
|
1920 | 1919 | |
|
1921 | 1920 | |
|
1922 | 1921 | def complete(self, text, line=None, cursor_pos=None): |
|
1923 | 1922 | """Return the completed text and a list of completions. |
|
1924 | 1923 | |
|
1925 | 1924 | Parameters |
|
1926 | 1925 | ---------- |
|
1927 | 1926 | |
|
1928 | 1927 | text : string |
|
1929 | 1928 | A string of text to be completed on. It can be given as empty and |
|
1930 | 1929 | instead a line/position pair are given. In this case, the |
|
1931 | 1930 | completer itself will split the line like readline does. |
|
1932 | 1931 | |
|
1933 | 1932 | line : string, optional |
|
1934 | 1933 | The complete line that text is part of. |
|
1935 | 1934 | |
|
1936 | 1935 | cursor_pos : int, optional |
|
1937 | 1936 | The position of the cursor on the input line. |
|
1938 | 1937 | |
|
1939 | 1938 | Returns |
|
1940 | 1939 | ------- |
|
1941 | 1940 | text : string |
|
1942 | 1941 | The actual text that was completed. |
|
1943 | 1942 | |
|
1944 | 1943 | matches : list |
|
1945 | 1944 | A sorted list with all possible completions. |
|
1946 | 1945 | |
|
1947 | 1946 | The optional arguments allow the completion to take more context into |
|
1948 | 1947 | account, and are part of the low-level completion API. |
|
1949 | 1948 | |
|
1950 | 1949 | This is a wrapper around the completion mechanism, similar to what |
|
1951 | 1950 | readline does at the command line when the TAB key is hit. By |
|
1952 | 1951 | exposing it as a method, it can be used by other non-readline |
|
1953 | 1952 | environments (such as GUIs) for text completion. |
|
1954 | 1953 | |
|
1955 | 1954 | Simple usage example: |
|
1956 | 1955 | |
|
1957 | 1956 | In [1]: x = 'hello' |
|
1958 | 1957 | |
|
1959 | 1958 | In [2]: _ip.complete('x.l') |
|
1960 | 1959 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) |
|
1961 | 1960 | """ |
|
1962 | 1961 | |
|
1963 | 1962 | # Inject names into __builtin__ so we can complete on the added names. |
|
1964 | 1963 | with self.builtin_trap: |
|
1965 | 1964 | return self.Completer.complete(text, line, cursor_pos) |
|
1966 | 1965 | |
|
1967 | 1966 | def set_custom_completer(self, completer, pos=0): |
|
1968 | 1967 | """Adds a new custom completer function. |
|
1969 | 1968 | |
|
1970 | 1969 | The position argument (defaults to 0) is the index in the completers |
|
1971 | 1970 | list where you want the completer to be inserted.""" |
|
1972 | 1971 | |
|
1973 | 1972 | newcomp = types.MethodType(completer,self.Completer) |
|
1974 | 1973 | self.Completer.matchers.insert(pos,newcomp) |
|
1975 | 1974 | |
|
1976 | 1975 | def set_completer_frame(self, frame=None): |
|
1977 | 1976 | """Set the frame of the completer.""" |
|
1978 | 1977 | if frame: |
|
1979 | 1978 | self.Completer.namespace = frame.f_locals |
|
1980 | 1979 | self.Completer.global_namespace = frame.f_globals |
|
1981 | 1980 | else: |
|
1982 | 1981 | self.Completer.namespace = self.user_ns |
|
1983 | 1982 | self.Completer.global_namespace = self.user_global_ns |
|
1984 | 1983 | |
|
1985 | 1984 | #------------------------------------------------------------------------- |
|
1986 | 1985 | # Things related to magics |
|
1987 | 1986 | #------------------------------------------------------------------------- |
|
1988 | 1987 | |
|
1989 | 1988 | def init_magics(self): |
|
1990 | 1989 | from IPython.core import magics as m |
|
1991 | 1990 | self.magics_manager = magic.MagicsManager(shell=self, |
|
1992 | 1991 | parent=self, |
|
1993 | 1992 | user_magics=m.UserMagics(self)) |
|
1994 | 1993 | self.configurables.append(self.magics_manager) |
|
1995 | 1994 | |
|
1996 | 1995 | # Expose as public API from the magics manager |
|
1997 | 1996 | self.register_magics = self.magics_manager.register |
|
1998 | 1997 | |
|
1999 | 1998 | self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics, |
|
2000 | 1999 | m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics, |
|
2001 | 2000 | m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics, |
|
2002 | 2001 | m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics, |
|
2003 | 2002 | ) |
|
2004 | 2003 | |
|
2005 | 2004 | # Register Magic Aliases |
|
2006 | 2005 | mman = self.magics_manager |
|
2007 | 2006 | # FIXME: magic aliases should be defined by the Magics classes |
|
2008 | 2007 | # or in MagicsManager, not here |
|
2009 | 2008 | mman.register_alias('ed', 'edit') |
|
2010 | 2009 | mman.register_alias('hist', 'history') |
|
2011 | 2010 | mman.register_alias('rep', 'recall') |
|
2012 | 2011 | mman.register_alias('SVG', 'svg', 'cell') |
|
2013 | 2012 | mman.register_alias('HTML', 'html', 'cell') |
|
2014 | 2013 | mman.register_alias('file', 'writefile', 'cell') |
|
2015 | 2014 | |
|
2016 | 2015 | # FIXME: Move the color initialization to the DisplayHook, which |
|
2017 | 2016 | # should be split into a prompt manager and displayhook. We probably |
|
2018 | 2017 | # even need a centralize colors management object. |
|
2019 | 2018 | self.magic('colors %s' % self.colors) |
|
2020 | 2019 | |
|
2021 | 2020 | # Defined here so that it's included in the documentation |
|
2022 | 2021 | @functools.wraps(magic.MagicsManager.register_function) |
|
2023 | 2022 | def register_magic_function(self, func, magic_kind='line', magic_name=None): |
|
2024 | 2023 | self.magics_manager.register_function(func, |
|
2025 | 2024 | magic_kind=magic_kind, magic_name=magic_name) |
|
2026 | 2025 | |
|
2027 | 2026 | def run_line_magic(self, magic_name, line): |
|
2028 | 2027 | """Execute the given line magic. |
|
2029 | 2028 | |
|
2030 | 2029 | Parameters |
|
2031 | 2030 | ---------- |
|
2032 | 2031 | magic_name : str |
|
2033 | 2032 | Name of the desired magic function, without '%' prefix. |
|
2034 | 2033 | |
|
2035 | 2034 | line : str |
|
2036 | 2035 | The rest of the input line as a single string. |
|
2037 | 2036 | """ |
|
2038 | 2037 | fn = self.find_line_magic(magic_name) |
|
2039 | 2038 | if fn is None: |
|
2040 | 2039 | cm = self.find_cell_magic(magic_name) |
|
2041 | 2040 | etpl = "Line magic function `%%%s` not found%s." |
|
2042 | 2041 | extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, ' |
|
2043 | 2042 | 'did you mean that instead?)' % magic_name ) |
|
2044 | 2043 | error(etpl % (magic_name, extra)) |
|
2045 | 2044 | else: |
|
2046 | 2045 | # Note: this is the distance in the stack to the user's frame. |
|
2047 | 2046 | # This will need to be updated if the internal calling logic gets |
|
2048 | 2047 | # refactored, or else we'll be expanding the wrong variables. |
|
2049 | 2048 | stack_depth = 2 |
|
2050 | 2049 | magic_arg_s = self.var_expand(line, stack_depth) |
|
2051 | 2050 | # Put magic args in a list so we can call with f(*a) syntax |
|
2052 | 2051 | args = [magic_arg_s] |
|
2053 | 2052 | kwargs = {} |
|
2054 | 2053 | # Grab local namespace if we need it: |
|
2055 | 2054 | if getattr(fn, "needs_local_scope", False): |
|
2056 | 2055 | kwargs['local_ns'] = sys._getframe(stack_depth).f_locals |
|
2057 | 2056 | with self.builtin_trap: |
|
2058 | 2057 | result = fn(*args,**kwargs) |
|
2059 | 2058 | return result |
|
2060 | 2059 | |
|
2061 | 2060 | def run_cell_magic(self, magic_name, line, cell): |
|
2062 | 2061 | """Execute the given cell magic. |
|
2063 | 2062 | |
|
2064 | 2063 | Parameters |
|
2065 | 2064 | ---------- |
|
2066 | 2065 | magic_name : str |
|
2067 | 2066 | Name of the desired magic function, without '%' prefix. |
|
2068 | 2067 | |
|
2069 | 2068 | line : str |
|
2070 | 2069 | The rest of the first input line as a single string. |
|
2071 | 2070 | |
|
2072 | 2071 | cell : str |
|
2073 | 2072 | The body of the cell as a (possibly multiline) string. |
|
2074 | 2073 | """ |
|
2075 | 2074 | fn = self.find_cell_magic(magic_name) |
|
2076 | 2075 | if fn is None: |
|
2077 | 2076 | lm = self.find_line_magic(magic_name) |
|
2078 | 2077 | etpl = "Cell magic `%%{0}` not found{1}." |
|
2079 | 2078 | extra = '' if lm is None else (' (But line magic `%{0}` exists, ' |
|
2080 | 2079 | 'did you mean that instead?)'.format(magic_name)) |
|
2081 | 2080 | error(etpl.format(magic_name, extra)) |
|
2082 | 2081 | elif cell == '': |
|
2083 | 2082 | message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name) |
|
2084 | 2083 | if self.find_line_magic(magic_name) is not None: |
|
2085 | 2084 | message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name) |
|
2086 | 2085 | raise UsageError(message) |
|
2087 | 2086 | else: |
|
2088 | 2087 | # Note: this is the distance in the stack to the user's frame. |
|
2089 | 2088 | # This will need to be updated if the internal calling logic gets |
|
2090 | 2089 | # refactored, or else we'll be expanding the wrong variables. |
|
2091 | 2090 | stack_depth = 2 |
|
2092 | 2091 | magic_arg_s = self.var_expand(line, stack_depth) |
|
2093 | 2092 | with self.builtin_trap: |
|
2094 | 2093 | result = fn(magic_arg_s, cell) |
|
2095 | 2094 | return result |
|
2096 | 2095 | |
|
2097 | 2096 | def find_line_magic(self, magic_name): |
|
2098 | 2097 | """Find and return a line magic by name. |
|
2099 | 2098 | |
|
2100 | 2099 | Returns None if the magic isn't found.""" |
|
2101 | 2100 | return self.magics_manager.magics['line'].get(magic_name) |
|
2102 | 2101 | |
|
2103 | 2102 | def find_cell_magic(self, magic_name): |
|
2104 | 2103 | """Find and return a cell magic by name. |
|
2105 | 2104 | |
|
2106 | 2105 | Returns None if the magic isn't found.""" |
|
2107 | 2106 | return self.magics_manager.magics['cell'].get(magic_name) |
|
2108 | 2107 | |
|
2109 | 2108 | def find_magic(self, magic_name, magic_kind='line'): |
|
2110 | 2109 | """Find and return a magic of the given type by name. |
|
2111 | 2110 | |
|
2112 | 2111 | Returns None if the magic isn't found.""" |
|
2113 | 2112 | return self.magics_manager.magics[magic_kind].get(magic_name) |
|
2114 | 2113 | |
|
2115 | 2114 | def magic(self, arg_s): |
|
2116 | 2115 | """DEPRECATED. Use run_line_magic() instead. |
|
2117 | 2116 | |
|
2118 | 2117 | Call a magic function by name. |
|
2119 | 2118 | |
|
2120 | 2119 | Input: a string containing the name of the magic function to call and |
|
2121 | 2120 | any additional arguments to be passed to the magic. |
|
2122 | 2121 | |
|
2123 | 2122 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
2124 | 2123 | prompt: |
|
2125 | 2124 | |
|
2126 | 2125 | In[1]: %name -opt foo bar |
|
2127 | 2126 | |
|
2128 | 2127 | To call a magic without arguments, simply use magic('name'). |
|
2129 | 2128 | |
|
2130 | 2129 | This provides a proper Python function to call IPython's magics in any |
|
2131 | 2130 | valid Python code you can type at the interpreter, including loops and |
|
2132 | 2131 | compound statements. |
|
2133 | 2132 | """ |
|
2134 | 2133 | # TODO: should we issue a loud deprecation warning here? |
|
2135 | 2134 | magic_name, _, magic_arg_s = arg_s.partition(' ') |
|
2136 | 2135 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
2137 | 2136 | return self.run_line_magic(magic_name, magic_arg_s) |
|
2138 | 2137 | |
|
2139 | 2138 | #------------------------------------------------------------------------- |
|
2140 | 2139 | # Things related to macros |
|
2141 | 2140 | #------------------------------------------------------------------------- |
|
2142 | 2141 | |
|
2143 | 2142 | def define_macro(self, name, themacro): |
|
2144 | 2143 | """Define a new macro |
|
2145 | 2144 | |
|
2146 | 2145 | Parameters |
|
2147 | 2146 | ---------- |
|
2148 | 2147 | name : str |
|
2149 | 2148 | The name of the macro. |
|
2150 | 2149 | themacro : str or Macro |
|
2151 | 2150 | The action to do upon invoking the macro. If a string, a new |
|
2152 | 2151 | Macro object is created by passing the string to it. |
|
2153 | 2152 | """ |
|
2154 | 2153 | |
|
2155 | 2154 | from IPython.core import macro |
|
2156 | 2155 | |
|
2157 |
if isinstance(themacro, str |
|
|
2156 | if isinstance(themacro, str): | |
|
2158 | 2157 | themacro = macro.Macro(themacro) |
|
2159 | 2158 | if not isinstance(themacro, macro.Macro): |
|
2160 | 2159 | raise ValueError('A macro must be a string or a Macro instance.') |
|
2161 | 2160 | self.user_ns[name] = themacro |
|
2162 | 2161 | |
|
2163 | 2162 | #------------------------------------------------------------------------- |
|
2164 | 2163 | # Things related to the running of system commands |
|
2165 | 2164 | #------------------------------------------------------------------------- |
|
2166 | 2165 | |
|
2167 | 2166 | def system_piped(self, cmd): |
|
2168 | 2167 | """Call the given cmd in a subprocess, piping stdout/err |
|
2169 | 2168 | |
|
2170 | 2169 | Parameters |
|
2171 | 2170 | ---------- |
|
2172 | 2171 | cmd : str |
|
2173 | 2172 | Command to execute (can not end in '&', as background processes are |
|
2174 | 2173 | not supported. Should not be a command that expects input |
|
2175 | 2174 | other than simple text. |
|
2176 | 2175 | """ |
|
2177 | 2176 | if cmd.rstrip().endswith('&'): |
|
2178 | 2177 | # this is *far* from a rigorous test |
|
2179 | 2178 | # We do not support backgrounding processes because we either use |
|
2180 | 2179 | # pexpect or pipes to read from. Users can always just call |
|
2181 | 2180 | # os.system() or use ip.system=ip.system_raw |
|
2182 | 2181 | # if they really want a background process. |
|
2183 | 2182 | raise OSError("Background processes not supported.") |
|
2184 | 2183 | |
|
2185 | 2184 | # we explicitly do NOT return the subprocess status code, because |
|
2186 | 2185 | # a non-None value would trigger :func:`sys.displayhook` calls. |
|
2187 | 2186 | # Instead, we store the exit_code in user_ns. |
|
2188 | 2187 | self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1)) |
|
2189 | 2188 | |
|
2190 | 2189 | def system_raw(self, cmd): |
|
2191 | 2190 | """Call the given cmd in a subprocess using os.system on Windows or |
|
2192 | 2191 | subprocess.call using the system shell on other platforms. |
|
2193 | 2192 | |
|
2194 | 2193 | Parameters |
|
2195 | 2194 | ---------- |
|
2196 | 2195 | cmd : str |
|
2197 | 2196 | Command to execute. |
|
2198 | 2197 | """ |
|
2199 | 2198 | cmd = self.var_expand(cmd, depth=1) |
|
2200 | 2199 | # protect os.system from UNC paths on Windows, which it can't handle: |
|
2201 | 2200 | if sys.platform == 'win32': |
|
2202 | 2201 | from IPython.utils._process_win32 import AvoidUNCPath |
|
2203 | 2202 | with AvoidUNCPath() as path: |
|
2204 | 2203 | if path is not None: |
|
2205 | 2204 | cmd = '"pushd %s &&"%s' % (path, cmd) |
|
2206 | cmd = py3compat.unicode_to_str(cmd) | |
|
2207 | 2205 | try: |
|
2208 | 2206 | ec = os.system(cmd) |
|
2209 | 2207 | except KeyboardInterrupt: |
|
2210 | 2208 | print('\n' + self.get_exception_only(), file=sys.stderr) |
|
2211 | 2209 | ec = -2 |
|
2212 | 2210 | else: |
|
2213 | cmd = py3compat.unicode_to_str(cmd) | |
|
2214 | 2211 | # For posix the result of the subprocess.call() below is an exit |
|
2215 | 2212 | # code, which by convention is zero for success, positive for |
|
2216 | 2213 | # program failure. Exit codes above 128 are reserved for signals, |
|
2217 | 2214 | # and the formula for converting a signal to an exit code is usually |
|
2218 | 2215 | # signal_number+128. To more easily differentiate between exit |
|
2219 | 2216 | # codes and signals, ipython uses negative numbers. For instance |
|
2220 | 2217 | # since control-c is signal 2 but exit code 130, ipython's |
|
2221 | 2218 | # _exit_code variable will read -2. Note that some shells like |
|
2222 | 2219 | # csh and fish don't follow sh/bash conventions for exit codes. |
|
2223 | 2220 | executable = os.environ.get('SHELL', None) |
|
2224 | 2221 | try: |
|
2225 | 2222 | # Use env shell instead of default /bin/sh |
|
2226 | 2223 | ec = subprocess.call(cmd, shell=True, executable=executable) |
|
2227 | 2224 | except KeyboardInterrupt: |
|
2228 | 2225 | # intercept control-C; a long traceback is not useful here |
|
2229 | 2226 | print('\n' + self.get_exception_only(), file=sys.stderr) |
|
2230 | 2227 | ec = 130 |
|
2231 | 2228 | if ec > 128: |
|
2232 | 2229 | ec = -(ec - 128) |
|
2233 | 2230 | |
|
2234 | 2231 | # We explicitly do NOT return the subprocess status code, because |
|
2235 | 2232 | # a non-None value would trigger :func:`sys.displayhook` calls. |
|
2236 | 2233 | # Instead, we store the exit_code in user_ns. Note the semantics |
|
2237 | 2234 | # of _exit_code: for control-c, _exit_code == -signal.SIGNIT, |
|
2238 | 2235 | # but raising SystemExit(_exit_code) will give status 254! |
|
2239 | 2236 | self.user_ns['_exit_code'] = ec |
|
2240 | 2237 | |
|
2241 | 2238 | # use piped system by default, because it is better behaved |
|
2242 | 2239 | system = system_piped |
|
2243 | 2240 | |
|
2244 | 2241 | def getoutput(self, cmd, split=True, depth=0): |
|
2245 | 2242 | """Get output (possibly including stderr) from a subprocess. |
|
2246 | 2243 | |
|
2247 | 2244 | Parameters |
|
2248 | 2245 | ---------- |
|
2249 | 2246 | cmd : str |
|
2250 | 2247 | Command to execute (can not end in '&', as background processes are |
|
2251 | 2248 | not supported. |
|
2252 | 2249 | split : bool, optional |
|
2253 | 2250 | If True, split the output into an IPython SList. Otherwise, an |
|
2254 | 2251 | IPython LSString is returned. These are objects similar to normal |
|
2255 | 2252 | lists and strings, with a few convenience attributes for easier |
|
2256 | 2253 | manipulation of line-based output. You can use '?' on them for |
|
2257 | 2254 | details. |
|
2258 | 2255 | depth : int, optional |
|
2259 | 2256 | How many frames above the caller are the local variables which should |
|
2260 | 2257 | be expanded in the command string? The default (0) assumes that the |
|
2261 | 2258 | expansion variables are in the stack frame calling this function. |
|
2262 | 2259 | """ |
|
2263 | 2260 | if cmd.rstrip().endswith('&'): |
|
2264 | 2261 | # this is *far* from a rigorous test |
|
2265 | 2262 | raise OSError("Background processes not supported.") |
|
2266 | 2263 | out = getoutput(self.var_expand(cmd, depth=depth+1)) |
|
2267 | 2264 | if split: |
|
2268 | 2265 | out = SList(out.splitlines()) |
|
2269 | 2266 | else: |
|
2270 | 2267 | out = LSString(out) |
|
2271 | 2268 | return out |
|
2272 | 2269 | |
|
2273 | 2270 | #------------------------------------------------------------------------- |
|
2274 | 2271 | # Things related to aliases |
|
2275 | 2272 | #------------------------------------------------------------------------- |
|
2276 | 2273 | |
|
2277 | 2274 | def init_alias(self): |
|
2278 | 2275 | self.alias_manager = AliasManager(shell=self, parent=self) |
|
2279 | 2276 | self.configurables.append(self.alias_manager) |
|
2280 | 2277 | |
|
2281 | 2278 | #------------------------------------------------------------------------- |
|
2282 | 2279 | # Things related to extensions |
|
2283 | 2280 | #------------------------------------------------------------------------- |
|
2284 | 2281 | |
|
2285 | 2282 | def init_extension_manager(self): |
|
2286 | 2283 | self.extension_manager = ExtensionManager(shell=self, parent=self) |
|
2287 | 2284 | self.configurables.append(self.extension_manager) |
|
2288 | 2285 | |
|
2289 | 2286 | #------------------------------------------------------------------------- |
|
2290 | 2287 | # Things related to payloads |
|
2291 | 2288 | #------------------------------------------------------------------------- |
|
2292 | 2289 | |
|
2293 | 2290 | def init_payload(self): |
|
2294 | 2291 | self.payload_manager = PayloadManager(parent=self) |
|
2295 | 2292 | self.configurables.append(self.payload_manager) |
|
2296 | 2293 | |
|
2297 | 2294 | #------------------------------------------------------------------------- |
|
2298 | 2295 | # Things related to the prefilter |
|
2299 | 2296 | #------------------------------------------------------------------------- |
|
2300 | 2297 | |
|
2301 | 2298 | def init_prefilter(self): |
|
2302 | 2299 | self.prefilter_manager = PrefilterManager(shell=self, parent=self) |
|
2303 | 2300 | self.configurables.append(self.prefilter_manager) |
|
2304 | 2301 | # Ultimately this will be refactored in the new interpreter code, but |
|
2305 | 2302 | # for now, we should expose the main prefilter method (there's legacy |
|
2306 | 2303 | # code out there that may rely on this). |
|
2307 | 2304 | self.prefilter = self.prefilter_manager.prefilter_lines |
|
2308 | 2305 | |
|
2309 | 2306 | def auto_rewrite_input(self, cmd): |
|
2310 | 2307 | """Print to the screen the rewritten form of the user's command. |
|
2311 | 2308 | |
|
2312 | 2309 | This shows visual feedback by rewriting input lines that cause |
|
2313 | 2310 | automatic calling to kick in, like:: |
|
2314 | 2311 | |
|
2315 | 2312 | /f x |
|
2316 | 2313 | |
|
2317 | 2314 | into:: |
|
2318 | 2315 | |
|
2319 | 2316 | ------> f(x) |
|
2320 | 2317 | |
|
2321 | 2318 | after the user's input prompt. This helps the user understand that the |
|
2322 | 2319 | input line was transformed automatically by IPython. |
|
2323 | 2320 | """ |
|
2324 | 2321 | if not self.show_rewritten_input: |
|
2325 | 2322 | return |
|
2326 | 2323 | |
|
2327 | 2324 | # This is overridden in TerminalInteractiveShell to use fancy prompts |
|
2328 | 2325 | print("------> " + cmd) |
|
2329 | 2326 | |
|
2330 | 2327 | #------------------------------------------------------------------------- |
|
2331 | 2328 | # Things related to extracting values/expressions from kernel and user_ns |
|
2332 | 2329 | #------------------------------------------------------------------------- |
|
2333 | 2330 | |
|
2334 | 2331 | def _user_obj_error(self): |
|
2335 | 2332 | """return simple exception dict |
|
2336 | 2333 | |
|
2337 | 2334 | for use in user_expressions |
|
2338 | 2335 | """ |
|
2339 | 2336 | |
|
2340 | 2337 | etype, evalue, tb = self._get_exc_info() |
|
2341 | 2338 | stb = self.InteractiveTB.get_exception_only(etype, evalue) |
|
2342 | 2339 | |
|
2343 | 2340 | exc_info = { |
|
2344 | 2341 | u'status' : 'error', |
|
2345 | 2342 | u'traceback' : stb, |
|
2346 |
u'ename' : |
|
|
2343 | u'ename' : etype.__name__, | |
|
2347 | 2344 | u'evalue' : py3compat.safe_unicode(evalue), |
|
2348 | 2345 | } |
|
2349 | 2346 | |
|
2350 | 2347 | return exc_info |
|
2351 | 2348 | |
|
2352 | 2349 | def _format_user_obj(self, obj): |
|
2353 | 2350 | """format a user object to display dict |
|
2354 | 2351 | |
|
2355 | 2352 | for use in user_expressions |
|
2356 | 2353 | """ |
|
2357 | 2354 | |
|
2358 | 2355 | data, md = self.display_formatter.format(obj) |
|
2359 | 2356 | value = { |
|
2360 | 2357 | 'status' : 'ok', |
|
2361 | 2358 | 'data' : data, |
|
2362 | 2359 | 'metadata' : md, |
|
2363 | 2360 | } |
|
2364 | 2361 | return value |
|
2365 | 2362 | |
|
2366 | 2363 | def user_expressions(self, expressions): |
|
2367 | 2364 | """Evaluate a dict of expressions in the user's namespace. |
|
2368 | 2365 | |
|
2369 | 2366 | Parameters |
|
2370 | 2367 | ---------- |
|
2371 | 2368 | expressions : dict |
|
2372 | 2369 | A dict with string keys and string values. The expression values |
|
2373 | 2370 | should be valid Python expressions, each of which will be evaluated |
|
2374 | 2371 | in the user namespace. |
|
2375 | 2372 | |
|
2376 | 2373 | Returns |
|
2377 | 2374 | ------- |
|
2378 | 2375 | A dict, keyed like the input expressions dict, with the rich mime-typed |
|
2379 | 2376 | display_data of each value. |
|
2380 | 2377 | """ |
|
2381 | 2378 | out = {} |
|
2382 | 2379 | user_ns = self.user_ns |
|
2383 | 2380 | global_ns = self.user_global_ns |
|
2384 | 2381 | |
|
2385 |
for key, expr in |
|
|
2382 | for key, expr in expressions.items(): | |
|
2386 | 2383 | try: |
|
2387 | 2384 | value = self._format_user_obj(eval(expr, global_ns, user_ns)) |
|
2388 | 2385 | except: |
|
2389 | 2386 | value = self._user_obj_error() |
|
2390 | 2387 | out[key] = value |
|
2391 | 2388 | return out |
|
2392 | 2389 | |
|
2393 | 2390 | #------------------------------------------------------------------------- |
|
2394 | 2391 | # Things related to the running of code |
|
2395 | 2392 | #------------------------------------------------------------------------- |
|
2396 | 2393 | |
|
2397 | 2394 | def ex(self, cmd): |
|
2398 | 2395 | """Execute a normal python statement in user namespace.""" |
|
2399 | 2396 | with self.builtin_trap: |
|
2400 | 2397 | exec(cmd, self.user_global_ns, self.user_ns) |
|
2401 | 2398 | |
|
2402 | 2399 | def ev(self, expr): |
|
2403 | 2400 | """Evaluate python expression expr in user namespace. |
|
2404 | 2401 | |
|
2405 | 2402 | Returns the result of evaluation |
|
2406 | 2403 | """ |
|
2407 | 2404 | with self.builtin_trap: |
|
2408 | 2405 | return eval(expr, self.user_global_ns, self.user_ns) |
|
2409 | 2406 | |
|
2410 | 2407 | def safe_execfile(self, fname, *where, **kw): |
|
2411 | 2408 | """A safe version of the builtin execfile(). |
|
2412 | 2409 | |
|
2413 | 2410 | This version will never throw an exception, but instead print |
|
2414 | 2411 | helpful error messages to the screen. This only works on pure |
|
2415 | 2412 | Python files with the .py extension. |
|
2416 | 2413 | |
|
2417 | 2414 | Parameters |
|
2418 | 2415 | ---------- |
|
2419 | 2416 | fname : string |
|
2420 | 2417 | The name of the file to be executed. |
|
2421 | 2418 | where : tuple |
|
2422 | 2419 | One or two namespaces, passed to execfile() as (globals,locals). |
|
2423 | 2420 | If only one is given, it is passed as both. |
|
2424 | 2421 | exit_ignore : bool (False) |
|
2425 | 2422 | If True, then silence SystemExit for non-zero status (it is always |
|
2426 | 2423 | silenced for zero status, as it is so common). |
|
2427 | 2424 | raise_exceptions : bool (False) |
|
2428 | 2425 | If True raise exceptions everywhere. Meant for testing. |
|
2429 | 2426 | shell_futures : bool (False) |
|
2430 | 2427 | If True, the code will share future statements with the interactive |
|
2431 | 2428 | shell. It will both be affected by previous __future__ imports, and |
|
2432 | 2429 | any __future__ imports in the code will affect the shell. If False, |
|
2433 | 2430 | __future__ imports are not shared in either direction. |
|
2434 | 2431 | |
|
2435 | 2432 | """ |
|
2436 | 2433 | kw.setdefault('exit_ignore', False) |
|
2437 | 2434 | kw.setdefault('raise_exceptions', False) |
|
2438 | 2435 | kw.setdefault('shell_futures', False) |
|
2439 | 2436 | |
|
2440 | 2437 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2441 | 2438 | |
|
2442 | 2439 | # Make sure we can open the file |
|
2443 | 2440 | try: |
|
2444 | 2441 | with open(fname): |
|
2445 | 2442 | pass |
|
2446 | 2443 | except: |
|
2447 | 2444 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2448 | 2445 | return |
|
2449 | 2446 | |
|
2450 | 2447 | # Find things also in current directory. This is needed to mimic the |
|
2451 | 2448 | # behavior of running a script from the system command line, where |
|
2452 | 2449 | # Python inserts the script's directory into sys.path |
|
2453 | 2450 | dname = os.path.dirname(fname) |
|
2454 | 2451 | |
|
2455 | 2452 | with prepended_to_syspath(dname), self.builtin_trap: |
|
2456 | 2453 | try: |
|
2457 | 2454 | glob, loc = (where + (None, ))[:2] |
|
2458 | 2455 | py3compat.execfile( |
|
2459 | 2456 | fname, glob, loc, |
|
2460 | 2457 | self.compile if kw['shell_futures'] else None) |
|
2461 | 2458 | except SystemExit as status: |
|
2462 | 2459 | # If the call was made with 0 or None exit status (sys.exit(0) |
|
2463 | 2460 | # or sys.exit() ), don't bother showing a traceback, as both of |
|
2464 | 2461 | # these are considered normal by the OS: |
|
2465 | 2462 | # > python -c'import sys;sys.exit(0)'; echo $? |
|
2466 | 2463 | # 0 |
|
2467 | 2464 | # > python -c'import sys;sys.exit()'; echo $? |
|
2468 | 2465 | # 0 |
|
2469 | 2466 | # For other exit status, we show the exception unless |
|
2470 | 2467 | # explicitly silenced, but only in short form. |
|
2471 | 2468 | if status.code: |
|
2472 | 2469 | if kw['raise_exceptions']: |
|
2473 | 2470 | raise |
|
2474 | 2471 | if not kw['exit_ignore']: |
|
2475 | 2472 | self.showtraceback(exception_only=True) |
|
2476 | 2473 | except: |
|
2477 | 2474 | if kw['raise_exceptions']: |
|
2478 | 2475 | raise |
|
2479 | 2476 | # tb offset is 2 because we wrap execfile |
|
2480 | 2477 | self.showtraceback(tb_offset=2) |
|
2481 | 2478 | |
|
2482 | 2479 | def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False): |
|
2483 | 2480 | """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax. |
|
2484 | 2481 | |
|
2485 | 2482 | Parameters |
|
2486 | 2483 | ---------- |
|
2487 | 2484 | fname : str |
|
2488 | 2485 | The name of the file to execute. The filename must have a |
|
2489 | 2486 | .ipy or .ipynb extension. |
|
2490 | 2487 | shell_futures : bool (False) |
|
2491 | 2488 | If True, the code will share future statements with the interactive |
|
2492 | 2489 | shell. It will both be affected by previous __future__ imports, and |
|
2493 | 2490 | any __future__ imports in the code will affect the shell. If False, |
|
2494 | 2491 | __future__ imports are not shared in either direction. |
|
2495 | 2492 | raise_exceptions : bool (False) |
|
2496 | 2493 | If True raise exceptions everywhere. Meant for testing. |
|
2497 | 2494 | """ |
|
2498 | 2495 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2499 | 2496 | |
|
2500 | 2497 | # Make sure we can open the file |
|
2501 | 2498 | try: |
|
2502 | 2499 | with open(fname): |
|
2503 | 2500 | pass |
|
2504 | 2501 | except: |
|
2505 | 2502 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2506 | 2503 | return |
|
2507 | 2504 | |
|
2508 | 2505 | # Find things also in current directory. This is needed to mimic the |
|
2509 | 2506 | # behavior of running a script from the system command line, where |
|
2510 | 2507 | # Python inserts the script's directory into sys.path |
|
2511 | 2508 | dname = os.path.dirname(fname) |
|
2512 | 2509 | |
|
2513 | 2510 | def get_cells(): |
|
2514 | 2511 | """generator for sequence of code blocks to run""" |
|
2515 | 2512 | if fname.endswith('.ipynb'): |
|
2516 | 2513 | from nbformat import read |
|
2517 | 2514 | with io_open(fname) as f: |
|
2518 | 2515 | nb = read(f, as_version=4) |
|
2519 | 2516 | if not nb.cells: |
|
2520 | 2517 | return |
|
2521 | 2518 | for cell in nb.cells: |
|
2522 | 2519 | if cell.cell_type == 'code': |
|
2523 | 2520 | yield cell.source |
|
2524 | 2521 | else: |
|
2525 | 2522 | with open(fname) as f: |
|
2526 | 2523 | yield f.read() |
|
2527 | 2524 | |
|
2528 | 2525 | with prepended_to_syspath(dname): |
|
2529 | 2526 | try: |
|
2530 | 2527 | for cell in get_cells(): |
|
2531 | 2528 | result = self.run_cell(cell, silent=True, shell_futures=shell_futures) |
|
2532 | 2529 | if raise_exceptions: |
|
2533 | 2530 | result.raise_error() |
|
2534 | 2531 | elif not result.success: |
|
2535 | 2532 | break |
|
2536 | 2533 | except: |
|
2537 | 2534 | if raise_exceptions: |
|
2538 | 2535 | raise |
|
2539 | 2536 | self.showtraceback() |
|
2540 | 2537 | warn('Unknown failure executing file: <%s>' % fname) |
|
2541 | 2538 | |
|
2542 | 2539 | def safe_run_module(self, mod_name, where): |
|
2543 | 2540 | """A safe version of runpy.run_module(). |
|
2544 | 2541 | |
|
2545 | 2542 | This version will never throw an exception, but instead print |
|
2546 | 2543 | helpful error messages to the screen. |
|
2547 | 2544 | |
|
2548 | 2545 | `SystemExit` exceptions with status code 0 or None are ignored. |
|
2549 | 2546 | |
|
2550 | 2547 | Parameters |
|
2551 | 2548 | ---------- |
|
2552 | 2549 | mod_name : string |
|
2553 | 2550 | The name of the module to be executed. |
|
2554 | 2551 | where : dict |
|
2555 | 2552 | The globals namespace. |
|
2556 | 2553 | """ |
|
2557 | 2554 | try: |
|
2558 | 2555 | try: |
|
2559 | 2556 | where.update( |
|
2560 | 2557 | runpy.run_module(str(mod_name), run_name="__main__", |
|
2561 | 2558 | alter_sys=True) |
|
2562 | 2559 | ) |
|
2563 | 2560 | except SystemExit as status: |
|
2564 | 2561 | if status.code: |
|
2565 | 2562 | raise |
|
2566 | 2563 | except: |
|
2567 | 2564 | self.showtraceback() |
|
2568 | 2565 | warn('Unknown failure executing module: <%s>' % mod_name) |
|
2569 | 2566 | |
|
2570 | 2567 | def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True): |
|
2571 | 2568 | """Run a complete IPython cell. |
|
2572 | 2569 | |
|
2573 | 2570 | Parameters |
|
2574 | 2571 | ---------- |
|
2575 | 2572 | raw_cell : str |
|
2576 | 2573 | The code (including IPython code such as %magic functions) to run. |
|
2577 | 2574 | store_history : bool |
|
2578 | 2575 | If True, the raw and translated cell will be stored in IPython's |
|
2579 | 2576 | history. For user code calling back into IPython's machinery, this |
|
2580 | 2577 | should be set to False. |
|
2581 | 2578 | silent : bool |
|
2582 | 2579 | If True, avoid side-effects, such as implicit displayhooks and |
|
2583 | 2580 | and logging. silent=True forces store_history=False. |
|
2584 | 2581 | shell_futures : bool |
|
2585 | 2582 | If True, the code will share future statements with the interactive |
|
2586 | 2583 | shell. It will both be affected by previous __future__ imports, and |
|
2587 | 2584 | any __future__ imports in the code will affect the shell. If False, |
|
2588 | 2585 | __future__ imports are not shared in either direction. |
|
2589 | 2586 | |
|
2590 | 2587 | Returns |
|
2591 | 2588 | ------- |
|
2592 | 2589 | result : :class:`ExecutionResult` |
|
2593 | 2590 | """ |
|
2594 | 2591 | result = ExecutionResult() |
|
2595 | 2592 | |
|
2596 | 2593 | if (not raw_cell) or raw_cell.isspace(): |
|
2597 | 2594 | self.last_execution_succeeded = True |
|
2598 | 2595 | return result |
|
2599 | 2596 | |
|
2600 | 2597 | if silent: |
|
2601 | 2598 | store_history = False |
|
2602 | 2599 | |
|
2603 | 2600 | if store_history: |
|
2604 | 2601 | result.execution_count = self.execution_count |
|
2605 | 2602 | |
|
2606 | 2603 | def error_before_exec(value): |
|
2607 | 2604 | result.error_before_exec = value |
|
2608 | 2605 | self.last_execution_succeeded = False |
|
2609 | 2606 | return result |
|
2610 | 2607 | |
|
2611 | 2608 | self.events.trigger('pre_execute') |
|
2612 | 2609 | if not silent: |
|
2613 | 2610 | self.events.trigger('pre_run_cell') |
|
2614 | 2611 | |
|
2615 | 2612 | # If any of our input transformation (input_transformer_manager or |
|
2616 | 2613 | # prefilter_manager) raises an exception, we store it in this variable |
|
2617 | 2614 | # so that we can display the error after logging the input and storing |
|
2618 | 2615 | # it in the history. |
|
2619 | 2616 | preprocessing_exc_tuple = None |
|
2620 | 2617 | try: |
|
2621 | 2618 | # Static input transformations |
|
2622 | 2619 | cell = self.input_transformer_manager.transform_cell(raw_cell) |
|
2623 | 2620 | except SyntaxError: |
|
2624 | 2621 | preprocessing_exc_tuple = sys.exc_info() |
|
2625 | 2622 | cell = raw_cell # cell has to exist so it can be stored/logged |
|
2626 | 2623 | else: |
|
2627 | 2624 | if len(cell.splitlines()) == 1: |
|
2628 | 2625 | # Dynamic transformations - only applied for single line commands |
|
2629 | 2626 | with self.builtin_trap: |
|
2630 | 2627 | try: |
|
2631 | 2628 | # use prefilter_lines to handle trailing newlines |
|
2632 | 2629 | # restore trailing newline for ast.parse |
|
2633 | 2630 | cell = self.prefilter_manager.prefilter_lines(cell) + '\n' |
|
2634 | 2631 | except Exception: |
|
2635 | 2632 | # don't allow prefilter errors to crash IPython |
|
2636 | 2633 | preprocessing_exc_tuple = sys.exc_info() |
|
2637 | 2634 | |
|
2638 | 2635 | # Store raw and processed history |
|
2639 | 2636 | if store_history: |
|
2640 | 2637 | self.history_manager.store_inputs(self.execution_count, |
|
2641 | 2638 | cell, raw_cell) |
|
2642 | 2639 | if not silent: |
|
2643 | 2640 | self.logger.log(cell, raw_cell) |
|
2644 | 2641 | |
|
2645 | 2642 | # Display the exception if input processing failed. |
|
2646 | 2643 | if preprocessing_exc_tuple is not None: |
|
2647 | 2644 | self.showtraceback(preprocessing_exc_tuple) |
|
2648 | 2645 | if store_history: |
|
2649 | 2646 | self.execution_count += 1 |
|
2650 | 2647 | return error_before_exec(preprocessing_exc_tuple[2]) |
|
2651 | 2648 | |
|
2652 | 2649 | # Our own compiler remembers the __future__ environment. If we want to |
|
2653 | 2650 | # run code with a separate __future__ environment, use the default |
|
2654 | 2651 | # compiler |
|
2655 | 2652 | compiler = self.compile if shell_futures else CachingCompiler() |
|
2656 | 2653 | |
|
2657 | 2654 | with self.builtin_trap: |
|
2658 | 2655 | cell_name = self.compile.cache(cell, self.execution_count) |
|
2659 | 2656 | |
|
2660 | 2657 | with self.display_trap: |
|
2661 | 2658 | # Compile to bytecode |
|
2662 | 2659 | try: |
|
2663 | 2660 | code_ast = compiler.ast_parse(cell, filename=cell_name) |
|
2664 | 2661 | except self.custom_exceptions as e: |
|
2665 | 2662 | etype, value, tb = sys.exc_info() |
|
2666 | 2663 | self.CustomTB(etype, value, tb) |
|
2667 | 2664 | return error_before_exec(e) |
|
2668 | 2665 | except IndentationError as e: |
|
2669 | 2666 | self.showindentationerror() |
|
2670 | 2667 | if store_history: |
|
2671 | 2668 | self.execution_count += 1 |
|
2672 | 2669 | return error_before_exec(e) |
|
2673 | 2670 | except (OverflowError, SyntaxError, ValueError, TypeError, |
|
2674 | 2671 | MemoryError) as e: |
|
2675 | 2672 | self.showsyntaxerror() |
|
2676 | 2673 | if store_history: |
|
2677 | 2674 | self.execution_count += 1 |
|
2678 | 2675 | return error_before_exec(e) |
|
2679 | 2676 | |
|
2680 | 2677 | # Apply AST transformations |
|
2681 | 2678 | try: |
|
2682 | 2679 | code_ast = self.transform_ast(code_ast) |
|
2683 | 2680 | except InputRejected as e: |
|
2684 | 2681 | self.showtraceback() |
|
2685 | 2682 | if store_history: |
|
2686 | 2683 | self.execution_count += 1 |
|
2687 | 2684 | return error_before_exec(e) |
|
2688 | 2685 | |
|
2689 | 2686 | # Give the displayhook a reference to our ExecutionResult so it |
|
2690 | 2687 | # can fill in the output value. |
|
2691 | 2688 | self.displayhook.exec_result = result |
|
2692 | 2689 | |
|
2693 | 2690 | # Execute the user code |
|
2694 | 2691 | interactivity = "none" if silent else self.ast_node_interactivity |
|
2695 | 2692 | has_raised = self.run_ast_nodes(code_ast.body, cell_name, |
|
2696 | 2693 | interactivity=interactivity, compiler=compiler, result=result) |
|
2697 | 2694 | |
|
2698 | 2695 | self.last_execution_succeeded = not has_raised |
|
2699 | 2696 | |
|
2700 | 2697 | # Reset this so later displayed values do not modify the |
|
2701 | 2698 | # ExecutionResult |
|
2702 | 2699 | self.displayhook.exec_result = None |
|
2703 | 2700 | |
|
2704 | 2701 | self.events.trigger('post_execute') |
|
2705 | 2702 | if not silent: |
|
2706 | 2703 | self.events.trigger('post_run_cell') |
|
2707 | 2704 | |
|
2708 | 2705 | if store_history: |
|
2709 | 2706 | # Write output to the database. Does nothing unless |
|
2710 | 2707 | # history output logging is enabled. |
|
2711 | 2708 | self.history_manager.store_output(self.execution_count) |
|
2712 | 2709 | # Each cell is a *single* input, regardless of how many lines it has |
|
2713 | 2710 | self.execution_count += 1 |
|
2714 | 2711 | |
|
2715 | 2712 | return result |
|
2716 | 2713 | |
|
2717 | 2714 | def transform_ast(self, node): |
|
2718 | 2715 | """Apply the AST transformations from self.ast_transformers |
|
2719 | 2716 | |
|
2720 | 2717 | Parameters |
|
2721 | 2718 | ---------- |
|
2722 | 2719 | node : ast.Node |
|
2723 | 2720 | The root node to be transformed. Typically called with the ast.Module |
|
2724 | 2721 | produced by parsing user input. |
|
2725 | 2722 | |
|
2726 | 2723 | Returns |
|
2727 | 2724 | ------- |
|
2728 | 2725 | An ast.Node corresponding to the node it was called with. Note that it |
|
2729 | 2726 | may also modify the passed object, so don't rely on references to the |
|
2730 | 2727 | original AST. |
|
2731 | 2728 | """ |
|
2732 | 2729 | for transformer in self.ast_transformers: |
|
2733 | 2730 | try: |
|
2734 | 2731 | node = transformer.visit(node) |
|
2735 | 2732 | except InputRejected: |
|
2736 | 2733 | # User-supplied AST transformers can reject an input by raising |
|
2737 | 2734 | # an InputRejected. Short-circuit in this case so that we |
|
2738 | 2735 | # don't unregister the transform. |
|
2739 | 2736 | raise |
|
2740 | 2737 | except Exception: |
|
2741 | 2738 | warn("AST transformer %r threw an error. It will be unregistered." % transformer) |
|
2742 | 2739 | self.ast_transformers.remove(transformer) |
|
2743 | 2740 | |
|
2744 | 2741 | if self.ast_transformers: |
|
2745 | 2742 | ast.fix_missing_locations(node) |
|
2746 | 2743 | return node |
|
2747 | 2744 | |
|
2748 | 2745 | |
|
2749 | 2746 | def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr', |
|
2750 | 2747 | compiler=compile, result=None): |
|
2751 | 2748 | """Run a sequence of AST nodes. The execution mode depends on the |
|
2752 | 2749 | interactivity parameter. |
|
2753 | 2750 | |
|
2754 | 2751 | Parameters |
|
2755 | 2752 | ---------- |
|
2756 | 2753 | nodelist : list |
|
2757 | 2754 | A sequence of AST nodes to run. |
|
2758 | 2755 | cell_name : str |
|
2759 | 2756 | Will be passed to the compiler as the filename of the cell. Typically |
|
2760 | 2757 | the value returned by ip.compile.cache(cell). |
|
2761 | 2758 | interactivity : str |
|
2762 | 2759 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be |
|
2763 | 2760 | run interactively (displaying output from expressions). 'last_expr' |
|
2764 | 2761 | will run the last node interactively only if it is an expression (i.e. |
|
2765 | 2762 | expressions in loops or other blocks are not displayed. Other values |
|
2766 | 2763 | for this parameter will raise a ValueError. |
|
2767 | 2764 | compiler : callable |
|
2768 | 2765 | A function with the same interface as the built-in compile(), to turn |
|
2769 | 2766 | the AST nodes into code objects. Default is the built-in compile(). |
|
2770 | 2767 | result : ExecutionResult, optional |
|
2771 | 2768 | An object to store exceptions that occur during execution. |
|
2772 | 2769 | |
|
2773 | 2770 | Returns |
|
2774 | 2771 | ------- |
|
2775 | 2772 | True if an exception occurred while running code, False if it finished |
|
2776 | 2773 | running. |
|
2777 | 2774 | """ |
|
2778 | 2775 | if not nodelist: |
|
2779 | 2776 | return |
|
2780 | 2777 | |
|
2781 | 2778 | if interactivity == 'last_expr': |
|
2782 | 2779 | if isinstance(nodelist[-1], ast.Expr): |
|
2783 | 2780 | interactivity = "last" |
|
2784 | 2781 | else: |
|
2785 | 2782 | interactivity = "none" |
|
2786 | 2783 | |
|
2787 | 2784 | if interactivity == 'none': |
|
2788 | 2785 | to_run_exec, to_run_interactive = nodelist, [] |
|
2789 | 2786 | elif interactivity == 'last': |
|
2790 | 2787 | to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:] |
|
2791 | 2788 | elif interactivity == 'all': |
|
2792 | 2789 | to_run_exec, to_run_interactive = [], nodelist |
|
2793 | 2790 | else: |
|
2794 | 2791 | raise ValueError("Interactivity was %r" % interactivity) |
|
2795 | 2792 | |
|
2796 | 2793 | try: |
|
2797 | 2794 | for i, node in enumerate(to_run_exec): |
|
2798 | 2795 | mod = ast.Module([node]) |
|
2799 | 2796 | code = compiler(mod, cell_name, "exec") |
|
2800 | 2797 | if self.run_code(code, result): |
|
2801 | 2798 | return True |
|
2802 | 2799 | |
|
2803 | 2800 | for i, node in enumerate(to_run_interactive): |
|
2804 | 2801 | mod = ast.Interactive([node]) |
|
2805 | 2802 | code = compiler(mod, cell_name, "single") |
|
2806 | 2803 | if self.run_code(code, result): |
|
2807 | 2804 | return True |
|
2808 | 2805 | |
|
2809 | 2806 | # Flush softspace |
|
2810 | 2807 | if softspace(sys.stdout, 0): |
|
2811 | 2808 | print() |
|
2812 | 2809 | |
|
2813 | 2810 | except: |
|
2814 | 2811 | # It's possible to have exceptions raised here, typically by |
|
2815 | 2812 | # compilation of odd code (such as a naked 'return' outside a |
|
2816 | 2813 | # function) that did parse but isn't valid. Typically the exception |
|
2817 | 2814 | # is a SyntaxError, but it's safest just to catch anything and show |
|
2818 | 2815 | # the user a traceback. |
|
2819 | 2816 | |
|
2820 | 2817 | # We do only one try/except outside the loop to minimize the impact |
|
2821 | 2818 | # on runtime, and also because if any node in the node list is |
|
2822 | 2819 | # broken, we should stop execution completely. |
|
2823 | 2820 | if result: |
|
2824 | 2821 | result.error_before_exec = sys.exc_info()[1] |
|
2825 | 2822 | self.showtraceback() |
|
2826 | 2823 | return True |
|
2827 | 2824 | |
|
2828 | 2825 | return False |
|
2829 | 2826 | |
|
2830 | 2827 | def run_code(self, code_obj, result=None): |
|
2831 | 2828 | """Execute a code object. |
|
2832 | 2829 | |
|
2833 | 2830 | When an exception occurs, self.showtraceback() is called to display a |
|
2834 | 2831 | traceback. |
|
2835 | 2832 | |
|
2836 | 2833 | Parameters |
|
2837 | 2834 | ---------- |
|
2838 | 2835 | code_obj : code object |
|
2839 | 2836 | A compiled code object, to be executed |
|
2840 | 2837 | result : ExecutionResult, optional |
|
2841 | 2838 | An object to store exceptions that occur during execution. |
|
2842 | 2839 | |
|
2843 | 2840 | Returns |
|
2844 | 2841 | ------- |
|
2845 | 2842 | False : successful execution. |
|
2846 | 2843 | True : an error occurred. |
|
2847 | 2844 | """ |
|
2848 | 2845 | # Set our own excepthook in case the user code tries to call it |
|
2849 | 2846 | # directly, so that the IPython crash handler doesn't get triggered |
|
2850 | 2847 | old_excepthook, sys.excepthook = sys.excepthook, self.excepthook |
|
2851 | 2848 | |
|
2852 | 2849 | # we save the original sys.excepthook in the instance, in case config |
|
2853 | 2850 | # code (such as magics) needs access to it. |
|
2854 | 2851 | self.sys_excepthook = old_excepthook |
|
2855 | 2852 | outflag = 1 # happens in more places, so it's easier as default |
|
2856 | 2853 | try: |
|
2857 | 2854 | try: |
|
2858 | 2855 | self.hooks.pre_run_code_hook() |
|
2859 | 2856 | #rprint('Running code', repr(code_obj)) # dbg |
|
2860 | 2857 | exec(code_obj, self.user_global_ns, self.user_ns) |
|
2861 | 2858 | finally: |
|
2862 | 2859 | # Reset our crash handler in place |
|
2863 | 2860 | sys.excepthook = old_excepthook |
|
2864 | 2861 | except SystemExit as e: |
|
2865 | 2862 | if result is not None: |
|
2866 | 2863 | result.error_in_exec = e |
|
2867 | 2864 | self.showtraceback(exception_only=True) |
|
2868 | 2865 | warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1) |
|
2869 | 2866 | except self.custom_exceptions: |
|
2870 | 2867 | etype, value, tb = sys.exc_info() |
|
2871 | 2868 | if result is not None: |
|
2872 | 2869 | result.error_in_exec = value |
|
2873 | 2870 | self.CustomTB(etype, value, tb) |
|
2874 | 2871 | except: |
|
2875 | 2872 | if result is not None: |
|
2876 | 2873 | result.error_in_exec = sys.exc_info()[1] |
|
2877 | 2874 | self.showtraceback() |
|
2878 | 2875 | else: |
|
2879 | 2876 | outflag = 0 |
|
2880 | 2877 | return outflag |
|
2881 | 2878 | |
|
2882 | 2879 | # For backwards compatibility |
|
2883 | 2880 | runcode = run_code |
|
2884 | 2881 | |
|
2885 | 2882 | #------------------------------------------------------------------------- |
|
2886 | 2883 | # Things related to GUI support and pylab |
|
2887 | 2884 | #------------------------------------------------------------------------- |
|
2888 | 2885 | |
|
2889 | 2886 | active_eventloop = None |
|
2890 | 2887 | |
|
2891 | 2888 | def enable_gui(self, gui=None): |
|
2892 | 2889 | raise NotImplementedError('Implement enable_gui in a subclass') |
|
2893 | 2890 | |
|
2894 | 2891 | def enable_matplotlib(self, gui=None): |
|
2895 | 2892 | """Enable interactive matplotlib and inline figure support. |
|
2896 | 2893 | |
|
2897 | 2894 | This takes the following steps: |
|
2898 | 2895 | |
|
2899 | 2896 | 1. select the appropriate eventloop and matplotlib backend |
|
2900 | 2897 | 2. set up matplotlib for interactive use with that backend |
|
2901 | 2898 | 3. configure formatters for inline figure display |
|
2902 | 2899 | 4. enable the selected gui eventloop |
|
2903 | 2900 | |
|
2904 | 2901 | Parameters |
|
2905 | 2902 | ---------- |
|
2906 | 2903 | gui : optional, string |
|
2907 | 2904 | If given, dictates the choice of matplotlib GUI backend to use |
|
2908 | 2905 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', |
|
2909 | 2906 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by |
|
2910 | 2907 | matplotlib (as dictated by the matplotlib build-time options plus the |
|
2911 | 2908 | user's matplotlibrc configuration file). Note that not all backends |
|
2912 | 2909 | make sense in all contexts, for example a terminal ipython can't |
|
2913 | 2910 | display figures inline. |
|
2914 | 2911 | """ |
|
2915 | 2912 | from IPython.core import pylabtools as pt |
|
2916 | 2913 | gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select) |
|
2917 | 2914 | |
|
2918 | 2915 | if gui != 'inline': |
|
2919 | 2916 | # If we have our first gui selection, store it |
|
2920 | 2917 | if self.pylab_gui_select is None: |
|
2921 | 2918 | self.pylab_gui_select = gui |
|
2922 | 2919 | # Otherwise if they are different |
|
2923 | 2920 | elif gui != self.pylab_gui_select: |
|
2924 | 2921 | print ('Warning: Cannot change to a different GUI toolkit: %s.' |
|
2925 | 2922 | ' Using %s instead.' % (gui, self.pylab_gui_select)) |
|
2926 | 2923 | gui, backend = pt.find_gui_and_backend(self.pylab_gui_select) |
|
2927 | 2924 | |
|
2928 | 2925 | pt.activate_matplotlib(backend) |
|
2929 | 2926 | pt.configure_inline_support(self, backend) |
|
2930 | 2927 | |
|
2931 | 2928 | # Now we must activate the gui pylab wants to use, and fix %run to take |
|
2932 | 2929 | # plot updates into account |
|
2933 | 2930 | self.enable_gui(gui) |
|
2934 | 2931 | self.magics_manager.registry['ExecutionMagics'].default_runner = \ |
|
2935 | 2932 | pt.mpl_runner(self.safe_execfile) |
|
2936 | 2933 | |
|
2937 | 2934 | return gui, backend |
|
2938 | 2935 | |
|
2939 | 2936 | def enable_pylab(self, gui=None, import_all=True, welcome_message=False): |
|
2940 | 2937 | """Activate pylab support at runtime. |
|
2941 | 2938 | |
|
2942 | 2939 | This turns on support for matplotlib, preloads into the interactive |
|
2943 | 2940 | namespace all of numpy and pylab, and configures IPython to correctly |
|
2944 | 2941 | interact with the GUI event loop. The GUI backend to be used can be |
|
2945 | 2942 | optionally selected with the optional ``gui`` argument. |
|
2946 | 2943 | |
|
2947 | 2944 | This method only adds preloading the namespace to InteractiveShell.enable_matplotlib. |
|
2948 | 2945 | |
|
2949 | 2946 | Parameters |
|
2950 | 2947 | ---------- |
|
2951 | 2948 | gui : optional, string |
|
2952 | 2949 | If given, dictates the choice of matplotlib GUI backend to use |
|
2953 | 2950 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', |
|
2954 | 2951 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by |
|
2955 | 2952 | matplotlib (as dictated by the matplotlib build-time options plus the |
|
2956 | 2953 | user's matplotlibrc configuration file). Note that not all backends |
|
2957 | 2954 | make sense in all contexts, for example a terminal ipython can't |
|
2958 | 2955 | display figures inline. |
|
2959 | 2956 | import_all : optional, bool, default: True |
|
2960 | 2957 | Whether to do `from numpy import *` and `from pylab import *` |
|
2961 | 2958 | in addition to module imports. |
|
2962 | 2959 | welcome_message : deprecated |
|
2963 | 2960 | This argument is ignored, no welcome message will be displayed. |
|
2964 | 2961 | """ |
|
2965 | 2962 | from IPython.core.pylabtools import import_pylab |
|
2966 | 2963 | |
|
2967 | 2964 | gui, backend = self.enable_matplotlib(gui) |
|
2968 | 2965 | |
|
2969 | 2966 | # We want to prevent the loading of pylab to pollute the user's |
|
2970 | 2967 | # namespace as shown by the %who* magics, so we execute the activation |
|
2971 | 2968 | # code in an empty namespace, and we update *both* user_ns and |
|
2972 | 2969 | # user_ns_hidden with this information. |
|
2973 | 2970 | ns = {} |
|
2974 | 2971 | import_pylab(ns, import_all) |
|
2975 | 2972 | # warn about clobbered names |
|
2976 | 2973 | ignored = {"__builtins__"} |
|
2977 | 2974 | both = set(ns).intersection(self.user_ns).difference(ignored) |
|
2978 | 2975 | clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ] |
|
2979 | 2976 | self.user_ns.update(ns) |
|
2980 | 2977 | self.user_ns_hidden.update(ns) |
|
2981 | 2978 | return gui, backend, clobbered |
|
2982 | 2979 | |
|
2983 | 2980 | #------------------------------------------------------------------------- |
|
2984 | 2981 | # Utilities |
|
2985 | 2982 | #------------------------------------------------------------------------- |
|
2986 | 2983 | |
|
2987 | 2984 | def var_expand(self, cmd, depth=0, formatter=DollarFormatter()): |
|
2988 | 2985 | """Expand python variables in a string. |
|
2989 | 2986 | |
|
2990 | 2987 | The depth argument indicates how many frames above the caller should |
|
2991 | 2988 | be walked to look for the local namespace where to expand variables. |
|
2992 | 2989 | |
|
2993 | 2990 | The global namespace for expansion is always the user's interactive |
|
2994 | 2991 | namespace. |
|
2995 | 2992 | """ |
|
2996 | 2993 | ns = self.user_ns.copy() |
|
2997 | 2994 | try: |
|
2998 | 2995 | frame = sys._getframe(depth+1) |
|
2999 | 2996 | except ValueError: |
|
3000 | 2997 | # This is thrown if there aren't that many frames on the stack, |
|
3001 | 2998 | # e.g. if a script called run_line_magic() directly. |
|
3002 | 2999 | pass |
|
3003 | 3000 | else: |
|
3004 | 3001 | ns.update(frame.f_locals) |
|
3005 | 3002 | |
|
3006 | 3003 | try: |
|
3007 | 3004 | # We have to use .vformat() here, because 'self' is a valid and common |
|
3008 | 3005 | # name, and expanding **ns for .format() would make it collide with |
|
3009 | 3006 | # the 'self' argument of the method. |
|
3010 | 3007 | cmd = formatter.vformat(cmd, args=[], kwargs=ns) |
|
3011 | 3008 | except Exception: |
|
3012 | 3009 | # if formatter couldn't format, just let it go untransformed |
|
3013 | 3010 | pass |
|
3014 | 3011 | return cmd |
|
3015 | 3012 | |
|
3016 | 3013 | def mktempfile(self, data=None, prefix='ipython_edit_'): |
|
3017 | 3014 | """Make a new tempfile and return its filename. |
|
3018 | 3015 | |
|
3019 | 3016 | This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp), |
|
3020 | 3017 | but it registers the created filename internally so ipython cleans it up |
|
3021 | 3018 | at exit time. |
|
3022 | 3019 | |
|
3023 | 3020 | Optional inputs: |
|
3024 | 3021 | |
|
3025 | 3022 | - data(None): if data is given, it gets written out to the temp file |
|
3026 | 3023 | immediately, and the file is closed again.""" |
|
3027 | 3024 | |
|
3028 | 3025 | dirname = tempfile.mkdtemp(prefix=prefix) |
|
3029 | 3026 | self.tempdirs.append(dirname) |
|
3030 | 3027 | |
|
3031 | 3028 | handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname) |
|
3032 | 3029 | os.close(handle) # On Windows, there can only be one open handle on a file |
|
3033 | 3030 | self.tempfiles.append(filename) |
|
3034 | 3031 | |
|
3035 | 3032 | if data: |
|
3036 | 3033 | tmp_file = open(filename,'w') |
|
3037 | 3034 | tmp_file.write(data) |
|
3038 | 3035 | tmp_file.close() |
|
3039 | 3036 | return filename |
|
3040 | 3037 | |
|
3041 | 3038 | @undoc |
|
3042 | 3039 | def write(self,data): |
|
3043 | 3040 | """DEPRECATED: Write a string to the default output""" |
|
3044 | 3041 | warn('InteractiveShell.write() is deprecated, use sys.stdout instead', |
|
3045 | 3042 | DeprecationWarning, stacklevel=2) |
|
3046 | 3043 | sys.stdout.write(data) |
|
3047 | 3044 | |
|
3048 | 3045 | @undoc |
|
3049 | 3046 | def write_err(self,data): |
|
3050 | 3047 | """DEPRECATED: Write a string to the default error output""" |
|
3051 | 3048 | warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead', |
|
3052 | 3049 | DeprecationWarning, stacklevel=2) |
|
3053 | 3050 | sys.stderr.write(data) |
|
3054 | 3051 | |
|
3055 | 3052 | def ask_yes_no(self, prompt, default=None, interrupt=None): |
|
3056 | 3053 | if self.quiet: |
|
3057 | 3054 | return True |
|
3058 | 3055 | return ask_yes_no(prompt,default,interrupt) |
|
3059 | 3056 | |
|
3060 | 3057 | def show_usage(self): |
|
3061 | 3058 | """Show a usage message""" |
|
3062 | 3059 | page.page(IPython.core.usage.interactive_usage) |
|
3063 | 3060 | |
|
3064 | 3061 | def extract_input_lines(self, range_str, raw=False): |
|
3065 | 3062 | """Return as a string a set of input history slices. |
|
3066 | 3063 | |
|
3067 | 3064 | Parameters |
|
3068 | 3065 | ---------- |
|
3069 | 3066 | range_str : string |
|
3070 | 3067 | The set of slices is given as a string, like "~5/6-~4/2 4:8 9", |
|
3071 | 3068 | since this function is for use by magic functions which get their |
|
3072 | 3069 | arguments as strings. The number before the / is the session |
|
3073 | 3070 | number: ~n goes n back from the current session. |
|
3074 | 3071 | |
|
3075 | 3072 | raw : bool, optional |
|
3076 | 3073 | By default, the processed input is used. If this is true, the raw |
|
3077 | 3074 | input history is used instead. |
|
3078 | 3075 | |
|
3079 | 3076 | Notes |
|
3080 | 3077 | ----- |
|
3081 | 3078 | |
|
3082 | 3079 | Slices can be described with two notations: |
|
3083 | 3080 | |
|
3084 | 3081 | * ``N:M`` -> standard python form, means including items N...(M-1). |
|
3085 | 3082 | * ``N-M`` -> include items N..M (closed endpoint). |
|
3086 | 3083 | """ |
|
3087 | 3084 | lines = self.history_manager.get_range_by_str(range_str, raw=raw) |
|
3088 | 3085 | return "\n".join(x for _, _, x in lines) |
|
3089 | 3086 | |
|
3090 | 3087 | def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False): |
|
3091 | 3088 | """Get a code string from history, file, url, or a string or macro. |
|
3092 | 3089 | |
|
3093 | 3090 | This is mainly used by magic functions. |
|
3094 | 3091 | |
|
3095 | 3092 | Parameters |
|
3096 | 3093 | ---------- |
|
3097 | 3094 | |
|
3098 | 3095 | target : str |
|
3099 | 3096 | |
|
3100 | 3097 | A string specifying code to retrieve. This will be tried respectively |
|
3101 | 3098 | as: ranges of input history (see %history for syntax), url, |
|
3102 | 3099 | corresponding .py file, filename, or an expression evaluating to a |
|
3103 | 3100 | string or Macro in the user namespace. |
|
3104 | 3101 | |
|
3105 | 3102 | raw : bool |
|
3106 | 3103 | If true (default), retrieve raw history. Has no effect on the other |
|
3107 | 3104 | retrieval mechanisms. |
|
3108 | 3105 | |
|
3109 | 3106 | py_only : bool (default False) |
|
3110 | 3107 | Only try to fetch python code, do not try alternative methods to decode file |
|
3111 | 3108 | if unicode fails. |
|
3112 | 3109 | |
|
3113 | 3110 | Returns |
|
3114 | 3111 | ------- |
|
3115 | 3112 | A string of code. |
|
3116 | 3113 | |
|
3117 | 3114 | ValueError is raised if nothing is found, and TypeError if it evaluates |
|
3118 | 3115 | to an object of another type. In each case, .args[0] is a printable |
|
3119 | 3116 | message. |
|
3120 | 3117 | """ |
|
3121 | 3118 | code = self.extract_input_lines(target, raw=raw) # Grab history |
|
3122 | 3119 | if code: |
|
3123 | 3120 | return code |
|
3124 | 3121 | try: |
|
3125 | 3122 | if target.startswith(('http://', 'https://')): |
|
3126 | 3123 | return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie) |
|
3127 | 3124 | except UnicodeDecodeError: |
|
3128 | 3125 | if not py_only : |
|
3129 | 3126 | # Deferred import |
|
3130 | 3127 | try: |
|
3131 | 3128 | from urllib.request import urlopen # Py3 |
|
3132 | 3129 | except ImportError: |
|
3133 | 3130 | from urllib import urlopen |
|
3134 | 3131 | response = urlopen(target) |
|
3135 | 3132 | return response.read().decode('latin1') |
|
3136 | 3133 | raise ValueError(("'%s' seem to be unreadable.") % target) |
|
3137 | 3134 | |
|
3138 | 3135 | potential_target = [target] |
|
3139 | 3136 | try : |
|
3140 | 3137 | potential_target.insert(0,get_py_filename(target)) |
|
3141 | 3138 | except IOError: |
|
3142 | 3139 | pass |
|
3143 | 3140 | |
|
3144 | 3141 | for tgt in potential_target : |
|
3145 | 3142 | if os.path.isfile(tgt): # Read file |
|
3146 | 3143 | try : |
|
3147 | 3144 | return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie) |
|
3148 | 3145 | except UnicodeDecodeError : |
|
3149 | 3146 | if not py_only : |
|
3150 | 3147 | with io_open(tgt,'r', encoding='latin1') as f : |
|
3151 | 3148 | return f.read() |
|
3152 | 3149 | raise ValueError(("'%s' seem to be unreadable.") % target) |
|
3153 | 3150 | elif os.path.isdir(os.path.expanduser(tgt)): |
|
3154 | 3151 | raise ValueError("'%s' is a directory, not a regular file." % target) |
|
3155 | 3152 | |
|
3156 | 3153 | if search_ns: |
|
3157 | 3154 | # Inspect namespace to load object source |
|
3158 | 3155 | object_info = self.object_inspect(target, detail_level=1) |
|
3159 | 3156 | if object_info['found'] and object_info['source']: |
|
3160 | 3157 | return object_info['source'] |
|
3161 | 3158 | |
|
3162 | 3159 | try: # User namespace |
|
3163 | 3160 | codeobj = eval(target, self.user_ns) |
|
3164 | 3161 | except Exception: |
|
3165 | 3162 | raise ValueError(("'%s' was not found in history, as a file, url, " |
|
3166 | 3163 | "nor in the user namespace.") % target) |
|
3167 | 3164 | |
|
3168 |
if isinstance(codeobj, str |
|
|
3165 | if isinstance(codeobj, str): | |
|
3169 | 3166 | return codeobj |
|
3170 | 3167 | elif isinstance(codeobj, Macro): |
|
3171 | 3168 | return codeobj.value |
|
3172 | 3169 | |
|
3173 | 3170 | raise TypeError("%s is neither a string nor a macro." % target, |
|
3174 | 3171 | codeobj) |
|
3175 | 3172 | |
|
3176 | 3173 | #------------------------------------------------------------------------- |
|
3177 | 3174 | # Things related to IPython exiting |
|
3178 | 3175 | #------------------------------------------------------------------------- |
|
3179 | 3176 | def atexit_operations(self): |
|
3180 | 3177 | """This will be executed at the time of exit. |
|
3181 | 3178 | |
|
3182 | 3179 | Cleanup operations and saving of persistent data that is done |
|
3183 | 3180 | unconditionally by IPython should be performed here. |
|
3184 | 3181 | |
|
3185 | 3182 | For things that may depend on startup flags or platform specifics (such |
|
3186 | 3183 | as having readline or not), register a separate atexit function in the |
|
3187 | 3184 | code that has the appropriate information, rather than trying to |
|
3188 | 3185 | clutter |
|
3189 | 3186 | """ |
|
3190 | 3187 | # Close the history session (this stores the end time and line count) |
|
3191 | 3188 | # this must be *before* the tempfile cleanup, in case of temporary |
|
3192 | 3189 | # history db |
|
3193 | 3190 | self.history_manager.end_session() |
|
3194 | 3191 | |
|
3195 | 3192 | # Cleanup all tempfiles and folders left around |
|
3196 | 3193 | for tfile in self.tempfiles: |
|
3197 | 3194 | try: |
|
3198 | 3195 | os.unlink(tfile) |
|
3199 | 3196 | except OSError: |
|
3200 | 3197 | pass |
|
3201 | 3198 | |
|
3202 | 3199 | for tdir in self.tempdirs: |
|
3203 | 3200 | try: |
|
3204 | 3201 | os.rmdir(tdir) |
|
3205 | 3202 | except OSError: |
|
3206 | 3203 | pass |
|
3207 | 3204 | |
|
3208 | 3205 | # Clear all user namespaces to release all references cleanly. |
|
3209 | 3206 | self.reset(new_session=False) |
|
3210 | 3207 | |
|
3211 | 3208 | # Run user hooks |
|
3212 | 3209 | self.hooks.shutdown_hook() |
|
3213 | 3210 | |
|
3214 | 3211 | def cleanup(self): |
|
3215 | 3212 | self.restore_sys_module_state() |
|
3216 | 3213 | |
|
3217 | 3214 | |
|
3218 | 3215 | # Overridden in terminal subclass to change prompts |
|
3219 | 3216 | def switch_doctest_mode(self, mode): |
|
3220 | 3217 | pass |
|
3221 | 3218 | |
|
3222 | 3219 | |
|
3223 | 3220 | class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)): |
|
3224 | 3221 | """An abstract base class for InteractiveShell.""" |
|
3225 | 3222 | |
|
3226 | 3223 | InteractiveShellABC.register(InteractiveShell) |
@@ -1,220 +1,218 b'' | |||
|
1 | 1 | """Logger class for IPython's logging facilities. |
|
2 | 2 | """ |
|
3 | 3 | |
|
4 | 4 | #***************************************************************************** |
|
5 | 5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
6 | 6 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> |
|
7 | 7 | # |
|
8 | 8 | # Distributed under the terms of the BSD License. The full license is in |
|
9 | 9 | # the file COPYING, distributed as part of this software. |
|
10 | 10 | #***************************************************************************** |
|
11 | 11 | |
|
12 | 12 | #**************************************************************************** |
|
13 | 13 | # Modules and globals |
|
14 | 14 | |
|
15 | 15 | # Python standard modules |
|
16 | 16 | import glob |
|
17 | 17 | import io |
|
18 | 18 | import os |
|
19 | 19 | import time |
|
20 | 20 | |
|
21 | from IPython.utils.py3compat import str_to_unicode | |
|
22 | 21 | |
|
23 | 22 | #**************************************************************************** |
|
24 | 23 | # FIXME: This class isn't a mixin anymore, but it still needs attributes from |
|
25 | 24 | # ipython and does input cache management. Finish cleanup later... |
|
26 | 25 | |
|
27 | 26 | class Logger(object): |
|
28 | 27 | """A Logfile class with different policies for file creation""" |
|
29 | 28 | |
|
30 | 29 | def __init__(self, home_dir, logfname='Logger.log', loghead=u'', |
|
31 | 30 | logmode='over'): |
|
32 | 31 | |
|
33 | 32 | # this is the full ipython instance, we need some attributes from it |
|
34 | 33 | # which won't exist until later. What a mess, clean up later... |
|
35 | 34 | self.home_dir = home_dir |
|
36 | 35 | |
|
37 | 36 | self.logfname = logfname |
|
38 | 37 | self.loghead = loghead |
|
39 | 38 | self.logmode = logmode |
|
40 | 39 | self.logfile = None |
|
41 | 40 | |
|
42 | 41 | # Whether to log raw or processed input |
|
43 | 42 | self.log_raw_input = False |
|
44 | 43 | |
|
45 | 44 | # whether to also log output |
|
46 | 45 | self.log_output = False |
|
47 | 46 | |
|
48 | 47 | # whether to put timestamps before each log entry |
|
49 | 48 | self.timestamp = False |
|
50 | 49 | |
|
51 | 50 | # activity control flags |
|
52 | 51 | self.log_active = False |
|
53 | 52 | |
|
54 | 53 | # logmode is a validated property |
|
55 | 54 | def _set_mode(self,mode): |
|
56 | 55 | if mode not in ['append','backup','global','over','rotate']: |
|
57 | 56 | raise ValueError('invalid log mode %s given' % mode) |
|
58 | 57 | self._logmode = mode |
|
59 | 58 | |
|
60 | 59 | def _get_mode(self): |
|
61 | 60 | return self._logmode |
|
62 | 61 | |
|
63 | 62 | logmode = property(_get_mode,_set_mode) |
|
64 | 63 | |
|
65 | 64 | def logstart(self, logfname=None, loghead=None, logmode=None, |
|
66 | 65 | log_output=False, timestamp=False, log_raw_input=False): |
|
67 | 66 | """Generate a new log-file with a default header. |
|
68 | 67 | |
|
69 | 68 | Raises RuntimeError if the log has already been started""" |
|
70 | 69 | |
|
71 | 70 | if self.logfile is not None: |
|
72 | 71 | raise RuntimeError('Log file is already active: %s' % |
|
73 | 72 | self.logfname) |
|
74 | 73 | |
|
75 | 74 | # The parameters can override constructor defaults |
|
76 | 75 | if logfname is not None: self.logfname = logfname |
|
77 | 76 | if loghead is not None: self.loghead = loghead |
|
78 | 77 | if logmode is not None: self.logmode = logmode |
|
79 | 78 | |
|
80 | 79 | # Parameters not part of the constructor |
|
81 | 80 | self.timestamp = timestamp |
|
82 | 81 | self.log_output = log_output |
|
83 | 82 | self.log_raw_input = log_raw_input |
|
84 | 83 | |
|
85 | 84 | # init depending on the log mode requested |
|
86 | 85 | isfile = os.path.isfile |
|
87 | 86 | logmode = self.logmode |
|
88 | 87 | |
|
89 | 88 | if logmode == 'append': |
|
90 | 89 | self.logfile = io.open(self.logfname, 'a', encoding='utf-8') |
|
91 | 90 | |
|
92 | 91 | elif logmode == 'backup': |
|
93 | 92 | if isfile(self.logfname): |
|
94 | 93 | backup_logname = self.logfname+'~' |
|
95 | 94 | # Manually remove any old backup, since os.rename may fail |
|
96 | 95 | # under Windows. |
|
97 | 96 | if isfile(backup_logname): |
|
98 | 97 | os.remove(backup_logname) |
|
99 | 98 | os.rename(self.logfname,backup_logname) |
|
100 | 99 | self.logfile = io.open(self.logfname, 'w', encoding='utf-8') |
|
101 | 100 | |
|
102 | 101 | elif logmode == 'global': |
|
103 | 102 | self.logfname = os.path.join(self.home_dir,self.logfname) |
|
104 | 103 | self.logfile = io.open(self.logfname, 'a', encoding='utf-8') |
|
105 | 104 | |
|
106 | 105 | elif logmode == 'over': |
|
107 | 106 | if isfile(self.logfname): |
|
108 | 107 | os.remove(self.logfname) |
|
109 | 108 | self.logfile = io.open(self.logfname,'w', encoding='utf-8') |
|
110 | 109 | |
|
111 | 110 | elif logmode == 'rotate': |
|
112 | 111 | if isfile(self.logfname): |
|
113 | 112 | if isfile(self.logfname+'.001~'): |
|
114 | 113 | old = glob.glob(self.logfname+'.*~') |
|
115 | 114 | old.sort() |
|
116 | 115 | old.reverse() |
|
117 | 116 | for f in old: |
|
118 | 117 | root, ext = os.path.splitext(f) |
|
119 | 118 | num = int(ext[1:-1])+1 |
|
120 | 119 | os.rename(f, root+'.'+repr(num).zfill(3)+'~') |
|
121 | 120 | os.rename(self.logfname, self.logfname+'.001~') |
|
122 | 121 | self.logfile = io.open(self.logfname, 'w', encoding='utf-8') |
|
123 | 122 | |
|
124 | 123 | if logmode != 'append': |
|
125 | 124 | self.logfile.write(self.loghead) |
|
126 | 125 | |
|
127 | 126 | self.logfile.flush() |
|
128 | 127 | self.log_active = True |
|
129 | 128 | |
|
130 | 129 | def switch_log(self,val): |
|
131 | 130 | """Switch logging on/off. val should be ONLY a boolean.""" |
|
132 | 131 | |
|
133 | 132 | if val not in [False,True,0,1]: |
|
134 | 133 | raise ValueError('Call switch_log ONLY with a boolean argument, ' |
|
135 | 134 | 'not with: %s' % val) |
|
136 | 135 | |
|
137 | 136 | label = {0:'OFF',1:'ON',False:'OFF',True:'ON'} |
|
138 | 137 | |
|
139 | 138 | if self.logfile is None: |
|
140 | 139 | print(""" |
|
141 | 140 | Logging hasn't been started yet (use logstart for that). |
|
142 | 141 | |
|
143 | 142 | %logon/%logoff are for temporarily starting and stopping logging for a logfile |
|
144 | 143 | which already exists. But you must first start the logging process with |
|
145 | 144 | %logstart (optionally giving a logfile name).""") |
|
146 | 145 | |
|
147 | 146 | else: |
|
148 | 147 | if self.log_active == val: |
|
149 | 148 | print('Logging is already',label[val]) |
|
150 | 149 | else: |
|
151 | 150 | print('Switching logging',label[val]) |
|
152 | 151 | self.log_active = not self.log_active |
|
153 | 152 | self.log_active_out = self.log_active |
|
154 | 153 | |
|
155 | 154 | def logstate(self): |
|
156 | 155 | """Print a status message about the logger.""" |
|
157 | 156 | if self.logfile is None: |
|
158 | 157 | print('Logging has not been activated.') |
|
159 | 158 | else: |
|
160 | 159 | state = self.log_active and 'active' or 'temporarily suspended' |
|
161 | 160 | print('Filename :', self.logfname) |
|
162 | 161 | print('Mode :', self.logmode) |
|
163 | 162 | print('Output logging :', self.log_output) |
|
164 | 163 | print('Raw input log :', self.log_raw_input) |
|
165 | 164 | print('Timestamping :', self.timestamp) |
|
166 | 165 | print('State :', state) |
|
167 | 166 | |
|
168 | 167 | def log(self, line_mod, line_ori): |
|
169 | 168 | """Write the sources to a log. |
|
170 | 169 | |
|
171 | 170 | Inputs: |
|
172 | 171 | |
|
173 | 172 | - line_mod: possibly modified input, such as the transformations made |
|
174 | 173 | by input prefilters or input handlers of various kinds. This should |
|
175 | 174 | always be valid Python. |
|
176 | 175 | |
|
177 | 176 | - line_ori: unmodified input line from the user. This is not |
|
178 | 177 | necessarily valid Python. |
|
179 | 178 | """ |
|
180 | 179 | |
|
181 | 180 | # Write the log line, but decide which one according to the |
|
182 | 181 | # log_raw_input flag, set when the log is started. |
|
183 | 182 | if self.log_raw_input: |
|
184 | 183 | self.log_write(line_ori) |
|
185 | 184 | else: |
|
186 | 185 | self.log_write(line_mod) |
|
187 | 186 | |
|
188 | 187 | def log_write(self, data, kind='input'): |
|
189 | 188 | """Write data to the log file, if active""" |
|
190 | 189 | |
|
191 | 190 | #print 'data: %r' % data # dbg |
|
192 | 191 | if self.log_active and data: |
|
193 | 192 | write = self.logfile.write |
|
194 | 193 | if kind=='input': |
|
195 | 194 | if self.timestamp: |
|
196 |
write |
|
|
197 | time.localtime()))) | |
|
195 | write(time.strftime('# %a, %d %b %Y %H:%M:%S\n', time.localtime())) | |
|
198 | 196 | write(data) |
|
199 | 197 | elif kind=='output' and self.log_output: |
|
200 | 198 | odata = u'\n'.join([u'#[Out]# %s' % s |
|
201 | 199 | for s in data.splitlines()]) |
|
202 | 200 | write(u'%s\n' % odata) |
|
203 | 201 | self.logfile.flush() |
|
204 | 202 | |
|
205 | 203 | def logstop(self): |
|
206 | 204 | """Fully stop logging and close log file. |
|
207 | 205 | |
|
208 | 206 | In order to start logging again, a new logstart() call needs to be |
|
209 | 207 | made, possibly (though not necessarily) with a new filename, mode and |
|
210 | 208 | other options.""" |
|
211 | 209 | |
|
212 | 210 | if self.logfile is not None: |
|
213 | 211 | self.logfile.close() |
|
214 | 212 | self.logfile = None |
|
215 | 213 | else: |
|
216 | 214 | print("Logging hadn't been started.") |
|
217 | 215 | self.log_active = False |
|
218 | 216 | |
|
219 | 217 | # For backwards compatibility, in case anyone was using this. |
|
220 | 218 | close_log = logstop |
@@ -1,57 +1,57 b'' | |||
|
1 | 1 | """Support for interactive macros in IPython""" |
|
2 | 2 | |
|
3 | 3 | #***************************************************************************** |
|
4 | 4 | # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu> |
|
5 | 5 | # |
|
6 | 6 | # Distributed under the terms of the BSD License. The full license is in |
|
7 | 7 | # the file COPYING, distributed as part of this software. |
|
8 | 8 | #***************************************************************************** |
|
9 | 9 | |
|
10 | 10 | import re |
|
11 | 11 | |
|
12 | 12 | from IPython.utils import py3compat |
|
13 | 13 | from IPython.utils.encoding import DEFAULT_ENCODING |
|
14 | 14 | |
|
15 | 15 | coding_declaration = re.compile(r"#\s*coding[:=]\s*([-\w.]+)") |
|
16 | 16 | |
|
17 | 17 | class Macro(object): |
|
18 | 18 | """Simple class to store the value of macros as strings. |
|
19 | 19 | |
|
20 | 20 | Macro is just a callable that executes a string of IPython |
|
21 | 21 | input when called. |
|
22 | 22 | """ |
|
23 | 23 | |
|
24 | 24 | def __init__(self,code): |
|
25 | 25 | """store the macro value, as a single string which can be executed""" |
|
26 | 26 | lines = [] |
|
27 | 27 | enc = None |
|
28 | 28 | for line in code.splitlines(): |
|
29 | 29 | coding_match = coding_declaration.match(line) |
|
30 | 30 | if coding_match: |
|
31 | 31 | enc = coding_match.group(1) |
|
32 | 32 | else: |
|
33 | 33 | lines.append(line) |
|
34 | 34 | code = "\n".join(lines) |
|
35 | 35 | if isinstance(code, bytes): |
|
36 | 36 | code = code.decode(enc or DEFAULT_ENCODING) |
|
37 | 37 | self.value = code + '\n' |
|
38 | 38 | |
|
39 | 39 | def __str__(self): |
|
40 |
return |
|
|
40 | return self.value | |
|
41 | 41 | |
|
42 | 42 | def __unicode__(self): |
|
43 | 43 | return self.value |
|
44 | 44 | |
|
45 | 45 | def __repr__(self): |
|
46 | 46 | return 'IPython.macro.Macro(%s)' % repr(self.value) |
|
47 | 47 | |
|
48 | 48 | def __getstate__(self): |
|
49 | 49 | """ needed for safe pickling via %store """ |
|
50 | 50 | return {'value': self.value} |
|
51 | 51 | |
|
52 | 52 | def __add__(self, other): |
|
53 | 53 | if isinstance(other, Macro): |
|
54 | 54 | return Macro(self.value + other.value) |
|
55 |
elif isinstance(other, |
|
|
55 | elif isinstance(other, str): | |
|
56 | 56 | return Macro(self.value + other) |
|
57 | 57 | raise TypeError |
@@ -1,679 +1,678 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """Magic functions for InteractiveShell. |
|
3 | 3 | """ |
|
4 | 4 | |
|
5 | 5 | #----------------------------------------------------------------------------- |
|
6 | 6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
7 | 7 | # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu> |
|
8 | 8 | # Copyright (C) 2008 The IPython Development Team |
|
9 | 9 | |
|
10 | 10 | # Distributed under the terms of the BSD License. The full license is in |
|
11 | 11 | # the file COPYING, distributed as part of this software. |
|
12 | 12 | #----------------------------------------------------------------------------- |
|
13 | 13 | |
|
14 | 14 | import os |
|
15 | 15 | import re |
|
16 | 16 | import sys |
|
17 | 17 | import types |
|
18 | 18 | from getopt import getopt, GetoptError |
|
19 | 19 | |
|
20 | 20 | from traitlets.config.configurable import Configurable |
|
21 | 21 | from IPython.core import oinspect |
|
22 | 22 | from IPython.core.error import UsageError |
|
23 | 23 | from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2 |
|
24 | 24 | from decorator import decorator |
|
25 | 25 | from IPython.utils.ipstruct import Struct |
|
26 | 26 | from IPython.utils.process import arg_split |
|
27 | from IPython.utils.py3compat import string_types, iteritems | |
|
28 | 27 | from IPython.utils.text import dedent |
|
29 | 28 | from traitlets import Bool, Dict, Instance, observe |
|
30 | 29 | from logging import error |
|
31 | 30 | |
|
32 | 31 | #----------------------------------------------------------------------------- |
|
33 | 32 | # Globals |
|
34 | 33 | #----------------------------------------------------------------------------- |
|
35 | 34 | |
|
36 | 35 | # A dict we'll use for each class that has magics, used as temporary storage to |
|
37 | 36 | # pass information between the @line/cell_magic method decorators and the |
|
38 | 37 | # @magics_class class decorator, because the method decorators have no |
|
39 | 38 | # access to the class when they run. See for more details: |
|
40 | 39 | # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class |
|
41 | 40 | |
|
42 | 41 | magics = dict(line={}, cell={}) |
|
43 | 42 | |
|
44 | 43 | magic_kinds = ('line', 'cell') |
|
45 | 44 | magic_spec = ('line', 'cell', 'line_cell') |
|
46 | 45 | magic_escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC2) |
|
47 | 46 | |
|
48 | 47 | #----------------------------------------------------------------------------- |
|
49 | 48 | # Utility classes and functions |
|
50 | 49 | #----------------------------------------------------------------------------- |
|
51 | 50 | |
|
52 | 51 | class Bunch: pass |
|
53 | 52 | |
|
54 | 53 | |
|
55 | 54 | def on_off(tag): |
|
56 | 55 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
57 | 56 | return ['OFF','ON'][tag] |
|
58 | 57 | |
|
59 | 58 | |
|
60 | 59 | def compress_dhist(dh): |
|
61 | 60 | """Compress a directory history into a new one with at most 20 entries. |
|
62 | 61 | |
|
63 | 62 | Return a new list made from the first and last 10 elements of dhist after |
|
64 | 63 | removal of duplicates. |
|
65 | 64 | """ |
|
66 | 65 | head, tail = dh[:-10], dh[-10:] |
|
67 | 66 | |
|
68 | 67 | newhead = [] |
|
69 | 68 | done = set() |
|
70 | 69 | for h in head: |
|
71 | 70 | if h in done: |
|
72 | 71 | continue |
|
73 | 72 | newhead.append(h) |
|
74 | 73 | done.add(h) |
|
75 | 74 | |
|
76 | 75 | return newhead + tail |
|
77 | 76 | |
|
78 | 77 | |
|
79 | 78 | def needs_local_scope(func): |
|
80 | 79 | """Decorator to mark magic functions which need to local scope to run.""" |
|
81 | 80 | func.needs_local_scope = True |
|
82 | 81 | return func |
|
83 | 82 | |
|
84 | 83 | #----------------------------------------------------------------------------- |
|
85 | 84 | # Class and method decorators for registering magics |
|
86 | 85 | #----------------------------------------------------------------------------- |
|
87 | 86 | |
|
88 | 87 | def magics_class(cls): |
|
89 | 88 | """Class decorator for all subclasses of the main Magics class. |
|
90 | 89 | |
|
91 | 90 | Any class that subclasses Magics *must* also apply this decorator, to |
|
92 | 91 | ensure that all the methods that have been decorated as line/cell magics |
|
93 | 92 | get correctly registered in the class instance. This is necessary because |
|
94 | 93 | when method decorators run, the class does not exist yet, so they |
|
95 | 94 | temporarily store their information into a module global. Application of |
|
96 | 95 | this class decorator copies that global data to the class instance and |
|
97 | 96 | clears the global. |
|
98 | 97 | |
|
99 | 98 | Obviously, this mechanism is not thread-safe, which means that the |
|
100 | 99 | *creation* of subclasses of Magic should only be done in a single-thread |
|
101 | 100 | context. Instantiation of the classes has no restrictions. Given that |
|
102 | 101 | these classes are typically created at IPython startup time and before user |
|
103 | 102 | application code becomes active, in practice this should not pose any |
|
104 | 103 | problems. |
|
105 | 104 | """ |
|
106 | 105 | cls.registered = True |
|
107 | 106 | cls.magics = dict(line = magics['line'], |
|
108 | 107 | cell = magics['cell']) |
|
109 | 108 | magics['line'] = {} |
|
110 | 109 | magics['cell'] = {} |
|
111 | 110 | return cls |
|
112 | 111 | |
|
113 | 112 | |
|
114 | 113 | def record_magic(dct, magic_kind, magic_name, func): |
|
115 | 114 | """Utility function to store a function as a magic of a specific kind. |
|
116 | 115 | |
|
117 | 116 | Parameters |
|
118 | 117 | ---------- |
|
119 | 118 | dct : dict |
|
120 | 119 | A dictionary with 'line' and 'cell' subdicts. |
|
121 | 120 | |
|
122 | 121 | magic_kind : str |
|
123 | 122 | Kind of magic to be stored. |
|
124 | 123 | |
|
125 | 124 | magic_name : str |
|
126 | 125 | Key to store the magic as. |
|
127 | 126 | |
|
128 | 127 | func : function |
|
129 | 128 | Callable object to store. |
|
130 | 129 | """ |
|
131 | 130 | if magic_kind == 'line_cell': |
|
132 | 131 | dct['line'][magic_name] = dct['cell'][magic_name] = func |
|
133 | 132 | else: |
|
134 | 133 | dct[magic_kind][magic_name] = func |
|
135 | 134 | |
|
136 | 135 | |
|
137 | 136 | def validate_type(magic_kind): |
|
138 | 137 | """Ensure that the given magic_kind is valid. |
|
139 | 138 | |
|
140 | 139 | Check that the given magic_kind is one of the accepted spec types (stored |
|
141 | 140 | in the global `magic_spec`), raise ValueError otherwise. |
|
142 | 141 | """ |
|
143 | 142 | if magic_kind not in magic_spec: |
|
144 | 143 | raise ValueError('magic_kind must be one of %s, %s given' % |
|
145 | 144 | magic_kinds, magic_kind) |
|
146 | 145 | |
|
147 | 146 | |
|
148 | 147 | # The docstrings for the decorator below will be fairly similar for the two |
|
149 | 148 | # types (method and function), so we generate them here once and reuse the |
|
150 | 149 | # templates below. |
|
151 | 150 | _docstring_template = \ |
|
152 | 151 | """Decorate the given {0} as {1} magic. |
|
153 | 152 | |
|
154 | 153 | The decorator can be used with or without arguments, as follows. |
|
155 | 154 | |
|
156 | 155 | i) without arguments: it will create a {1} magic named as the {0} being |
|
157 | 156 | decorated:: |
|
158 | 157 | |
|
159 | 158 | @deco |
|
160 | 159 | def foo(...) |
|
161 | 160 | |
|
162 | 161 | will create a {1} magic named `foo`. |
|
163 | 162 | |
|
164 | 163 | ii) with one string argument: which will be used as the actual name of the |
|
165 | 164 | resulting magic:: |
|
166 | 165 | |
|
167 | 166 | @deco('bar') |
|
168 | 167 | def foo(...) |
|
169 | 168 | |
|
170 | 169 | will create a {1} magic named `bar`. |
|
171 | 170 | """ |
|
172 | 171 | |
|
173 | 172 | # These two are decorator factories. While they are conceptually very similar, |
|
174 | 173 | # there are enough differences in the details that it's simpler to have them |
|
175 | 174 | # written as completely standalone functions rather than trying to share code |
|
176 | 175 | # and make a single one with convoluted logic. |
|
177 | 176 | |
|
178 | 177 | def _method_magic_marker(magic_kind): |
|
179 | 178 | """Decorator factory for methods in Magics subclasses. |
|
180 | 179 | """ |
|
181 | 180 | |
|
182 | 181 | validate_type(magic_kind) |
|
183 | 182 | |
|
184 | 183 | # This is a closure to capture the magic_kind. We could also use a class, |
|
185 | 184 | # but it's overkill for just that one bit of state. |
|
186 | 185 | def magic_deco(arg): |
|
187 | 186 | call = lambda f, *a, **k: f(*a, **k) |
|
188 | 187 | |
|
189 | 188 | if callable(arg): |
|
190 | 189 | # "Naked" decorator call (just @foo, no args) |
|
191 | 190 | func = arg |
|
192 | 191 | name = func.__name__ |
|
193 | 192 | retval = decorator(call, func) |
|
194 | 193 | record_magic(magics, magic_kind, name, name) |
|
195 |
elif isinstance(arg, str |
|
|
194 | elif isinstance(arg, str): | |
|
196 | 195 | # Decorator called with arguments (@foo('bar')) |
|
197 | 196 | name = arg |
|
198 | 197 | def mark(func, *a, **kw): |
|
199 | 198 | record_magic(magics, magic_kind, name, func.__name__) |
|
200 | 199 | return decorator(call, func) |
|
201 | 200 | retval = mark |
|
202 | 201 | else: |
|
203 | 202 | raise TypeError("Decorator can only be called with " |
|
204 | 203 | "string or function") |
|
205 | 204 | return retval |
|
206 | 205 | |
|
207 | 206 | # Ensure the resulting decorator has a usable docstring |
|
208 | 207 | magic_deco.__doc__ = _docstring_template.format('method', magic_kind) |
|
209 | 208 | return magic_deco |
|
210 | 209 | |
|
211 | 210 | |
|
212 | 211 | def _function_magic_marker(magic_kind): |
|
213 | 212 | """Decorator factory for standalone functions. |
|
214 | 213 | """ |
|
215 | 214 | validate_type(magic_kind) |
|
216 | 215 | |
|
217 | 216 | # This is a closure to capture the magic_kind. We could also use a class, |
|
218 | 217 | # but it's overkill for just that one bit of state. |
|
219 | 218 | def magic_deco(arg): |
|
220 | 219 | call = lambda f, *a, **k: f(*a, **k) |
|
221 | 220 | |
|
222 | 221 | # Find get_ipython() in the caller's namespace |
|
223 | 222 | caller = sys._getframe(1) |
|
224 | 223 | for ns in ['f_locals', 'f_globals', 'f_builtins']: |
|
225 | 224 | get_ipython = getattr(caller, ns).get('get_ipython') |
|
226 | 225 | if get_ipython is not None: |
|
227 | 226 | break |
|
228 | 227 | else: |
|
229 | 228 | raise NameError('Decorator can only run in context where ' |
|
230 | 229 | '`get_ipython` exists') |
|
231 | 230 | |
|
232 | 231 | ip = get_ipython() |
|
233 | 232 | |
|
234 | 233 | if callable(arg): |
|
235 | 234 | # "Naked" decorator call (just @foo, no args) |
|
236 | 235 | func = arg |
|
237 | 236 | name = func.__name__ |
|
238 | 237 | ip.register_magic_function(func, magic_kind, name) |
|
239 | 238 | retval = decorator(call, func) |
|
240 |
elif isinstance(arg, str |
|
|
239 | elif isinstance(arg, str): | |
|
241 | 240 | # Decorator called with arguments (@foo('bar')) |
|
242 | 241 | name = arg |
|
243 | 242 | def mark(func, *a, **kw): |
|
244 | 243 | ip.register_magic_function(func, magic_kind, name) |
|
245 | 244 | return decorator(call, func) |
|
246 | 245 | retval = mark |
|
247 | 246 | else: |
|
248 | 247 | raise TypeError("Decorator can only be called with " |
|
249 | 248 | "string or function") |
|
250 | 249 | return retval |
|
251 | 250 | |
|
252 | 251 | # Ensure the resulting decorator has a usable docstring |
|
253 | 252 | ds = _docstring_template.format('function', magic_kind) |
|
254 | 253 | |
|
255 | 254 | ds += dedent(""" |
|
256 | 255 | Note: this decorator can only be used in a context where IPython is already |
|
257 | 256 | active, so that the `get_ipython()` call succeeds. You can therefore use |
|
258 | 257 | it in your startup files loaded after IPython initializes, but *not* in the |
|
259 | 258 | IPython configuration file itself, which is executed before IPython is |
|
260 | 259 | fully up and running. Any file located in the `startup` subdirectory of |
|
261 | 260 | your configuration profile will be OK in this sense. |
|
262 | 261 | """) |
|
263 | 262 | |
|
264 | 263 | magic_deco.__doc__ = ds |
|
265 | 264 | return magic_deco |
|
266 | 265 | |
|
267 | 266 | |
|
268 | 267 | # Create the actual decorators for public use |
|
269 | 268 | |
|
270 | 269 | # These three are used to decorate methods in class definitions |
|
271 | 270 | line_magic = _method_magic_marker('line') |
|
272 | 271 | cell_magic = _method_magic_marker('cell') |
|
273 | 272 | line_cell_magic = _method_magic_marker('line_cell') |
|
274 | 273 | |
|
275 | 274 | # These three decorate standalone functions and perform the decoration |
|
276 | 275 | # immediately. They can only run where get_ipython() works |
|
277 | 276 | register_line_magic = _function_magic_marker('line') |
|
278 | 277 | register_cell_magic = _function_magic_marker('cell') |
|
279 | 278 | register_line_cell_magic = _function_magic_marker('line_cell') |
|
280 | 279 | |
|
281 | 280 | #----------------------------------------------------------------------------- |
|
282 | 281 | # Core Magic classes |
|
283 | 282 | #----------------------------------------------------------------------------- |
|
284 | 283 | |
|
285 | 284 | class MagicsManager(Configurable): |
|
286 | 285 | """Object that handles all magic-related functionality for IPython. |
|
287 | 286 | """ |
|
288 | 287 | # Non-configurable class attributes |
|
289 | 288 | |
|
290 | 289 | # A two-level dict, first keyed by magic type, then by magic function, and |
|
291 | 290 | # holding the actual callable object as value. This is the dict used for |
|
292 | 291 | # magic function dispatch |
|
293 | 292 | magics = Dict() |
|
294 | 293 | |
|
295 | 294 | # A registry of the original objects that we've been given holding magics. |
|
296 | 295 | registry = Dict() |
|
297 | 296 | |
|
298 | 297 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True) |
|
299 | 298 | |
|
300 | 299 | auto_magic = Bool(True, help= |
|
301 | 300 | "Automatically call line magics without requiring explicit % prefix" |
|
302 | 301 | ).tag(config=True) |
|
303 | 302 | @observe('auto_magic') |
|
304 | 303 | def _auto_magic_changed(self, change): |
|
305 | 304 | self.shell.automagic = change['new'] |
|
306 | 305 | |
|
307 | 306 | _auto_status = [ |
|
308 | 307 | 'Automagic is OFF, % prefix IS needed for line magics.', |
|
309 | 308 | 'Automagic is ON, % prefix IS NOT needed for line magics.'] |
|
310 | 309 | |
|
311 | 310 | user_magics = Instance('IPython.core.magics.UserMagics', allow_none=True) |
|
312 | 311 | |
|
313 | 312 | def __init__(self, shell=None, config=None, user_magics=None, **traits): |
|
314 | 313 | |
|
315 | 314 | super(MagicsManager, self).__init__(shell=shell, config=config, |
|
316 | 315 | user_magics=user_magics, **traits) |
|
317 | 316 | self.magics = dict(line={}, cell={}) |
|
318 | 317 | # Let's add the user_magics to the registry for uniformity, so *all* |
|
319 | 318 | # registered magic containers can be found there. |
|
320 | 319 | self.registry[user_magics.__class__.__name__] = user_magics |
|
321 | 320 | |
|
322 | 321 | def auto_status(self): |
|
323 | 322 | """Return descriptive string with automagic status.""" |
|
324 | 323 | return self._auto_status[self.auto_magic] |
|
325 | 324 | |
|
326 | 325 | def lsmagic(self): |
|
327 | 326 | """Return a dict of currently available magic functions. |
|
328 | 327 | |
|
329 | 328 | The return dict has the keys 'line' and 'cell', corresponding to the |
|
330 | 329 | two types of magics we support. Each value is a list of names. |
|
331 | 330 | """ |
|
332 | 331 | return self.magics |
|
333 | 332 | |
|
334 | 333 | def lsmagic_docs(self, brief=False, missing=''): |
|
335 | 334 | """Return dict of documentation of magic functions. |
|
336 | 335 | |
|
337 | 336 | The return dict has the keys 'line' and 'cell', corresponding to the |
|
338 | 337 | two types of magics we support. Each value is a dict keyed by magic |
|
339 | 338 | name whose value is the function docstring. If a docstring is |
|
340 | 339 | unavailable, the value of `missing` is used instead. |
|
341 | 340 | |
|
342 | 341 | If brief is True, only the first line of each docstring will be returned. |
|
343 | 342 | """ |
|
344 | 343 | docs = {} |
|
345 | 344 | for m_type in self.magics: |
|
346 | 345 | m_docs = {} |
|
347 |
for m_name, m_func in |
|
|
346 | for m_name, m_func in self.magics[m_type].items(): | |
|
348 | 347 | if m_func.__doc__: |
|
349 | 348 | if brief: |
|
350 | 349 | m_docs[m_name] = m_func.__doc__.split('\n', 1)[0] |
|
351 | 350 | else: |
|
352 | 351 | m_docs[m_name] = m_func.__doc__.rstrip() |
|
353 | 352 | else: |
|
354 | 353 | m_docs[m_name] = missing |
|
355 | 354 | docs[m_type] = m_docs |
|
356 | 355 | return docs |
|
357 | 356 | |
|
358 | 357 | def register(self, *magic_objects): |
|
359 | 358 | """Register one or more instances of Magics. |
|
360 | 359 | |
|
361 | 360 | Take one or more classes or instances of classes that subclass the main |
|
362 | 361 | `core.Magic` class, and register them with IPython to use the magic |
|
363 | 362 | functions they provide. The registration process will then ensure that |
|
364 | 363 | any methods that have decorated to provide line and/or cell magics will |
|
365 | 364 | be recognized with the `%x`/`%%x` syntax as a line/cell magic |
|
366 | 365 | respectively. |
|
367 | 366 | |
|
368 | 367 | If classes are given, they will be instantiated with the default |
|
369 | 368 | constructor. If your classes need a custom constructor, you should |
|
370 | 369 | instanitate them first and pass the instance. |
|
371 | 370 | |
|
372 | 371 | The provided arguments can be an arbitrary mix of classes and instances. |
|
373 | 372 | |
|
374 | 373 | Parameters |
|
375 | 374 | ---------- |
|
376 | 375 | magic_objects : one or more classes or instances |
|
377 | 376 | """ |
|
378 | 377 | # Start by validating them to ensure they have all had their magic |
|
379 | 378 | # methods registered at the instance level |
|
380 | 379 | for m in magic_objects: |
|
381 | 380 | if not m.registered: |
|
382 | 381 | raise ValueError("Class of magics %r was constructed without " |
|
383 | 382 | "the @register_magics class decorator") |
|
384 | 383 | if isinstance(m, type): |
|
385 | 384 | # If we're given an uninstantiated class |
|
386 | 385 | m = m(shell=self.shell) |
|
387 | 386 | |
|
388 | 387 | # Now that we have an instance, we can register it and update the |
|
389 | 388 | # table of callables |
|
390 | 389 | self.registry[m.__class__.__name__] = m |
|
391 | 390 | for mtype in magic_kinds: |
|
392 | 391 | self.magics[mtype].update(m.magics[mtype]) |
|
393 | 392 | |
|
394 | 393 | def register_function(self, func, magic_kind='line', magic_name=None): |
|
395 | 394 | """Expose a standalone function as magic function for IPython. |
|
396 | 395 | |
|
397 | 396 | This will create an IPython magic (line, cell or both) from a |
|
398 | 397 | standalone function. The functions should have the following |
|
399 | 398 | signatures: |
|
400 | 399 | |
|
401 | 400 | * For line magics: `def f(line)` |
|
402 | 401 | * For cell magics: `def f(line, cell)` |
|
403 | 402 | * For a function that does both: `def f(line, cell=None)` |
|
404 | 403 | |
|
405 | 404 | In the latter case, the function will be called with `cell==None` when |
|
406 | 405 | invoked as `%f`, and with cell as a string when invoked as `%%f`. |
|
407 | 406 | |
|
408 | 407 | Parameters |
|
409 | 408 | ---------- |
|
410 | 409 | func : callable |
|
411 | 410 | Function to be registered as a magic. |
|
412 | 411 | |
|
413 | 412 | magic_kind : str |
|
414 | 413 | Kind of magic, one of 'line', 'cell' or 'line_cell' |
|
415 | 414 | |
|
416 | 415 | magic_name : optional str |
|
417 | 416 | If given, the name the magic will have in the IPython namespace. By |
|
418 | 417 | default, the name of the function itself is used. |
|
419 | 418 | """ |
|
420 | 419 | |
|
421 | 420 | # Create the new method in the user_magics and register it in the |
|
422 | 421 | # global table |
|
423 | 422 | validate_type(magic_kind) |
|
424 | 423 | magic_name = func.__name__ if magic_name is None else magic_name |
|
425 | 424 | setattr(self.user_magics, magic_name, func) |
|
426 | 425 | record_magic(self.magics, magic_kind, magic_name, func) |
|
427 | 426 | |
|
428 | 427 | def register_alias(self, alias_name, magic_name, magic_kind='line'): |
|
429 | 428 | """Register an alias to a magic function. |
|
430 | 429 | |
|
431 | 430 | The alias is an instance of :class:`MagicAlias`, which holds the |
|
432 | 431 | name and kind of the magic it should call. Binding is done at |
|
433 | 432 | call time, so if the underlying magic function is changed the alias |
|
434 | 433 | will call the new function. |
|
435 | 434 | |
|
436 | 435 | Parameters |
|
437 | 436 | ---------- |
|
438 | 437 | alias_name : str |
|
439 | 438 | The name of the magic to be registered. |
|
440 | 439 | |
|
441 | 440 | magic_name : str |
|
442 | 441 | The name of an existing magic. |
|
443 | 442 | |
|
444 | 443 | magic_kind : str |
|
445 | 444 | Kind of magic, one of 'line' or 'cell' |
|
446 | 445 | """ |
|
447 | 446 | |
|
448 | 447 | # `validate_type` is too permissive, as it allows 'line_cell' |
|
449 | 448 | # which we do not handle. |
|
450 | 449 | if magic_kind not in magic_kinds: |
|
451 | 450 | raise ValueError('magic_kind must be one of %s, %s given' % |
|
452 | 451 | magic_kinds, magic_kind) |
|
453 | 452 | |
|
454 | 453 | alias = MagicAlias(self.shell, magic_name, magic_kind) |
|
455 | 454 | setattr(self.user_magics, alias_name, alias) |
|
456 | 455 | record_magic(self.magics, magic_kind, alias_name, alias) |
|
457 | 456 | |
|
458 | 457 | # Key base class that provides the central functionality for magics. |
|
459 | 458 | |
|
460 | 459 | |
|
461 | 460 | class Magics(Configurable): |
|
462 | 461 | """Base class for implementing magic functions. |
|
463 | 462 | |
|
464 | 463 | Shell functions which can be reached as %function_name. All magic |
|
465 | 464 | functions should accept a string, which they can parse for their own |
|
466 | 465 | needs. This can make some functions easier to type, eg `%cd ../` |
|
467 | 466 | vs. `%cd("../")` |
|
468 | 467 | |
|
469 | 468 | Classes providing magic functions need to subclass this class, and they |
|
470 | 469 | MUST: |
|
471 | 470 | |
|
472 | 471 | - Use the method decorators `@line_magic` and `@cell_magic` to decorate |
|
473 | 472 | individual methods as magic functions, AND |
|
474 | 473 | |
|
475 | 474 | - Use the class decorator `@magics_class` to ensure that the magic |
|
476 | 475 | methods are properly registered at the instance level upon instance |
|
477 | 476 | initialization. |
|
478 | 477 | |
|
479 | 478 | See :mod:`magic_functions` for examples of actual implementation classes. |
|
480 | 479 | """ |
|
481 | 480 | # Dict holding all command-line options for each magic. |
|
482 | 481 | options_table = None |
|
483 | 482 | # Dict for the mapping of magic names to methods, set by class decorator |
|
484 | 483 | magics = None |
|
485 | 484 | # Flag to check that the class decorator was properly applied |
|
486 | 485 | registered = False |
|
487 | 486 | # Instance of IPython shell |
|
488 | 487 | shell = None |
|
489 | 488 | |
|
490 | 489 | def __init__(self, shell=None, **kwargs): |
|
491 | 490 | if not(self.__class__.registered): |
|
492 | 491 | raise ValueError('Magics subclass without registration - ' |
|
493 | 492 | 'did you forget to apply @magics_class?') |
|
494 | 493 | if shell is not None: |
|
495 | 494 | if hasattr(shell, 'configurables'): |
|
496 | 495 | shell.configurables.append(self) |
|
497 | 496 | if hasattr(shell, 'config'): |
|
498 | 497 | kwargs.setdefault('parent', shell) |
|
499 | 498 | |
|
500 | 499 | self.shell = shell |
|
501 | 500 | self.options_table = {} |
|
502 | 501 | # The method decorators are run when the instance doesn't exist yet, so |
|
503 | 502 | # they can only record the names of the methods they are supposed to |
|
504 | 503 | # grab. Only now, that the instance exists, can we create the proper |
|
505 | 504 | # mapping to bound methods. So we read the info off the original names |
|
506 | 505 | # table and replace each method name by the actual bound method. |
|
507 | 506 | # But we mustn't clobber the *class* mapping, in case of multiple instances. |
|
508 | 507 | class_magics = self.magics |
|
509 | 508 | self.magics = {} |
|
510 | 509 | for mtype in magic_kinds: |
|
511 | 510 | tab = self.magics[mtype] = {} |
|
512 | 511 | cls_tab = class_magics[mtype] |
|
513 |
for magic_name, meth_name in |
|
|
514 |
if isinstance(meth_name, str |
|
|
512 | for magic_name, meth_name in cls_tab.items(): | |
|
513 | if isinstance(meth_name, str): | |
|
515 | 514 | # it's a method name, grab it |
|
516 | 515 | tab[magic_name] = getattr(self, meth_name) |
|
517 | 516 | else: |
|
518 | 517 | # it's the real thing |
|
519 | 518 | tab[magic_name] = meth_name |
|
520 | 519 | # Configurable **needs** to be initiated at the end or the config |
|
521 | 520 | # magics get screwed up. |
|
522 | 521 | super(Magics, self).__init__(**kwargs) |
|
523 | 522 | |
|
524 | 523 | def arg_err(self,func): |
|
525 | 524 | """Print docstring if incorrect arguments were passed""" |
|
526 | 525 | print('Error in arguments:') |
|
527 | 526 | print(oinspect.getdoc(func)) |
|
528 | 527 | |
|
529 | 528 | def format_latex(self, strng): |
|
530 | 529 | """Format a string for latex inclusion.""" |
|
531 | 530 | |
|
532 | 531 | # Characters that need to be escaped for latex: |
|
533 | 532 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
534 | 533 | # Magic command names as headers: |
|
535 | 534 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, |
|
536 | 535 | re.MULTILINE) |
|
537 | 536 | # Magic commands |
|
538 | 537 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, |
|
539 | 538 | re.MULTILINE) |
|
540 | 539 | # Paragraph continue |
|
541 | 540 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
542 | 541 | |
|
543 | 542 | # The "\n" symbol |
|
544 | 543 | newline_re = re.compile(r'\\n') |
|
545 | 544 | |
|
546 | 545 | # Now build the string for output: |
|
547 | 546 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
548 | 547 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
549 | 548 | strng) |
|
550 | 549 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
551 | 550 | strng = par_re.sub(r'\\\\',strng) |
|
552 | 551 | strng = escape_re.sub(r'\\\1',strng) |
|
553 | 552 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
554 | 553 | return strng |
|
555 | 554 | |
|
556 | 555 | def parse_options(self, arg_str, opt_str, *long_opts, **kw): |
|
557 | 556 | """Parse options passed to an argument string. |
|
558 | 557 | |
|
559 | 558 | The interface is similar to that of :func:`getopt.getopt`, but it |
|
560 | 559 | returns a :class:`~IPython.utils.struct.Struct` with the options as keys |
|
561 | 560 | and the stripped argument string still as a string. |
|
562 | 561 | |
|
563 | 562 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
564 | 563 | This allows us to easily expand variables, glob files, quote |
|
565 | 564 | arguments, etc. |
|
566 | 565 | |
|
567 | 566 | Parameters |
|
568 | 567 | ---------- |
|
569 | 568 | |
|
570 | 569 | arg_str : str |
|
571 | 570 | The arguments to parse. |
|
572 | 571 | |
|
573 | 572 | opt_str : str |
|
574 | 573 | The options specification. |
|
575 | 574 | |
|
576 | 575 | mode : str, default 'string' |
|
577 | 576 | If given as 'list', the argument string is returned as a list (split |
|
578 | 577 | on whitespace) instead of a string. |
|
579 | 578 | |
|
580 | 579 | list_all : bool, default False |
|
581 | 580 | Put all option values in lists. Normally only options |
|
582 | 581 | appearing more than once are put in a list. |
|
583 | 582 | |
|
584 | 583 | posix : bool, default True |
|
585 | 584 | Whether to split the input line in POSIX mode or not, as per the |
|
586 | 585 | conventions outlined in the :mod:`shlex` module from the standard |
|
587 | 586 | library. |
|
588 | 587 | """ |
|
589 | 588 | |
|
590 | 589 | # inject default options at the beginning of the input line |
|
591 | 590 | caller = sys._getframe(1).f_code.co_name |
|
592 | 591 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
593 | 592 | |
|
594 | 593 | mode = kw.get('mode','string') |
|
595 | 594 | if mode not in ['string','list']: |
|
596 | 595 | raise ValueError('incorrect mode given: %s' % mode) |
|
597 | 596 | # Get options |
|
598 | 597 | list_all = kw.get('list_all',0) |
|
599 | 598 | posix = kw.get('posix', os.name == 'posix') |
|
600 | 599 | strict = kw.get('strict', True) |
|
601 | 600 | |
|
602 | 601 | # Check if we have more than one argument to warrant extra processing: |
|
603 | 602 | odict = {} # Dictionary with options |
|
604 | 603 | args = arg_str.split() |
|
605 | 604 | if len(args) >= 1: |
|
606 | 605 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
607 | 606 | # need to look for options |
|
608 | 607 | argv = arg_split(arg_str, posix, strict) |
|
609 | 608 | # Do regular option processing |
|
610 | 609 | try: |
|
611 | 610 | opts,args = getopt(argv, opt_str, long_opts) |
|
612 | 611 | except GetoptError as e: |
|
613 | 612 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
614 | 613 | " ".join(long_opts))) |
|
615 | 614 | for o,a in opts: |
|
616 | 615 | if o.startswith('--'): |
|
617 | 616 | o = o[2:] |
|
618 | 617 | else: |
|
619 | 618 | o = o[1:] |
|
620 | 619 | try: |
|
621 | 620 | odict[o].append(a) |
|
622 | 621 | except AttributeError: |
|
623 | 622 | odict[o] = [odict[o],a] |
|
624 | 623 | except KeyError: |
|
625 | 624 | if list_all: |
|
626 | 625 | odict[o] = [a] |
|
627 | 626 | else: |
|
628 | 627 | odict[o] = a |
|
629 | 628 | |
|
630 | 629 | # Prepare opts,args for return |
|
631 | 630 | opts = Struct(odict) |
|
632 | 631 | if mode == 'string': |
|
633 | 632 | args = ' '.join(args) |
|
634 | 633 | |
|
635 | 634 | return opts,args |
|
636 | 635 | |
|
637 | 636 | def default_option(self, fn, optstr): |
|
638 | 637 | """Make an entry in the options_table for fn, with value optstr""" |
|
639 | 638 | |
|
640 | 639 | if fn not in self.lsmagic(): |
|
641 | 640 | error("%s is not a magic function" % fn) |
|
642 | 641 | self.options_table[fn] = optstr |
|
643 | 642 | |
|
644 | 643 | |
|
645 | 644 | class MagicAlias(object): |
|
646 | 645 | """An alias to another magic function. |
|
647 | 646 | |
|
648 | 647 | An alias is determined by its magic name and magic kind. Lookup |
|
649 | 648 | is done at call time, so if the underlying magic changes the alias |
|
650 | 649 | will call the new function. |
|
651 | 650 | |
|
652 | 651 | Use the :meth:`MagicsManager.register_alias` method or the |
|
653 | 652 | `%alias_magic` magic function to create and register a new alias. |
|
654 | 653 | """ |
|
655 | 654 | def __init__(self, shell, magic_name, magic_kind): |
|
656 | 655 | self.shell = shell |
|
657 | 656 | self.magic_name = magic_name |
|
658 | 657 | self.magic_kind = magic_kind |
|
659 | 658 | |
|
660 | 659 | self.pretty_target = '%s%s' % (magic_escapes[self.magic_kind], self.magic_name) |
|
661 | 660 | self.__doc__ = "Alias for `%s`." % self.pretty_target |
|
662 | 661 | |
|
663 | 662 | self._in_call = False |
|
664 | 663 | |
|
665 | 664 | def __call__(self, *args, **kwargs): |
|
666 | 665 | """Call the magic alias.""" |
|
667 | 666 | fn = self.shell.find_magic(self.magic_name, self.magic_kind) |
|
668 | 667 | if fn is None: |
|
669 | 668 | raise UsageError("Magic `%s` not found." % self.pretty_target) |
|
670 | 669 | |
|
671 | 670 | # Protect against infinite recursion. |
|
672 | 671 | if self._in_call: |
|
673 | 672 | raise UsageError("Infinite recursion detected; " |
|
674 | 673 | "magic aliases cannot call themselves.") |
|
675 | 674 | self._in_call = True |
|
676 | 675 | try: |
|
677 | 676 | return fn(*args, **kwargs) |
|
678 | 677 | finally: |
|
679 | 678 | self._in_call = False |
@@ -1,581 +1,580 b'' | |||
|
1 | 1 | """Implementation of basic magic functions.""" |
|
2 | 2 | |
|
3 | 3 | |
|
4 | 4 | import argparse |
|
5 | 5 | import io |
|
6 | 6 | import sys |
|
7 | 7 | from pprint import pformat |
|
8 | 8 | |
|
9 | 9 | from IPython.core import magic_arguments, page |
|
10 | 10 | from IPython.core.error import UsageError |
|
11 | 11 | from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes |
|
12 | 12 | from IPython.utils.text import format_screen, dedent, indent |
|
13 | 13 | from IPython.testing.skipdoctest import skip_doctest |
|
14 | 14 | from IPython.utils.ipstruct import Struct |
|
15 | from IPython.utils.py3compat import unicode_type | |
|
16 | 15 | from warnings import warn |
|
17 | 16 | from logging import error |
|
18 | 17 | |
|
19 | 18 | |
|
20 | 19 | class MagicsDisplay(object): |
|
21 | 20 | def __init__(self, magics_manager): |
|
22 | 21 | self.magics_manager = magics_manager |
|
23 | 22 | |
|
24 | 23 | def _lsmagic(self): |
|
25 | 24 | """The main implementation of the %lsmagic""" |
|
26 | 25 | mesc = magic_escapes['line'] |
|
27 | 26 | cesc = magic_escapes['cell'] |
|
28 | 27 | mman = self.magics_manager |
|
29 | 28 | magics = mman.lsmagic() |
|
30 | 29 | out = ['Available line magics:', |
|
31 | 30 | mesc + (' '+mesc).join(sorted(magics['line'])), |
|
32 | 31 | '', |
|
33 | 32 | 'Available cell magics:', |
|
34 | 33 | cesc + (' '+cesc).join(sorted(magics['cell'])), |
|
35 | 34 | '', |
|
36 | 35 | mman.auto_status()] |
|
37 | 36 | return '\n'.join(out) |
|
38 | 37 | |
|
39 | 38 | def _repr_pretty_(self, p, cycle): |
|
40 | 39 | p.text(self._lsmagic()) |
|
41 | 40 | |
|
42 | 41 | def __str__(self): |
|
43 | 42 | return self._lsmagic() |
|
44 | 43 | |
|
45 | 44 | def _jsonable(self): |
|
46 | 45 | """turn magics dict into jsonable dict of the same structure |
|
47 | 46 | |
|
48 | 47 | replaces object instances with their class names as strings |
|
49 | 48 | """ |
|
50 | 49 | magic_dict = {} |
|
51 | 50 | mman = self.magics_manager |
|
52 | 51 | magics = mman.lsmagic() |
|
53 | 52 | for key, subdict in magics.items(): |
|
54 | 53 | d = {} |
|
55 | 54 | magic_dict[key] = d |
|
56 | 55 | for name, obj in subdict.items(): |
|
57 | 56 | try: |
|
58 | 57 | classname = obj.__self__.__class__.__name__ |
|
59 | 58 | except AttributeError: |
|
60 | 59 | classname = 'Other' |
|
61 | 60 | |
|
62 | 61 | d[name] = classname |
|
63 | 62 | return magic_dict |
|
64 | 63 | |
|
65 | 64 | def _repr_json_(self): |
|
66 | 65 | return self._jsonable() |
|
67 | 66 | |
|
68 | 67 | |
|
69 | 68 | @magics_class |
|
70 | 69 | class BasicMagics(Magics): |
|
71 | 70 | """Magics that provide central IPython functionality. |
|
72 | 71 | |
|
73 | 72 | These are various magics that don't fit into specific categories but that |
|
74 | 73 | are all part of the base 'IPython experience'.""" |
|
75 | 74 | |
|
76 | 75 | @magic_arguments.magic_arguments() |
|
77 | 76 | @magic_arguments.argument( |
|
78 | 77 | '-l', '--line', action='store_true', |
|
79 | 78 | help="""Create a line magic alias.""" |
|
80 | 79 | ) |
|
81 | 80 | @magic_arguments.argument( |
|
82 | 81 | '-c', '--cell', action='store_true', |
|
83 | 82 | help="""Create a cell magic alias.""" |
|
84 | 83 | ) |
|
85 | 84 | @magic_arguments.argument( |
|
86 | 85 | 'name', |
|
87 | 86 | help="""Name of the magic to be created.""" |
|
88 | 87 | ) |
|
89 | 88 | @magic_arguments.argument( |
|
90 | 89 | 'target', |
|
91 | 90 | help="""Name of the existing line or cell magic.""" |
|
92 | 91 | ) |
|
93 | 92 | @line_magic |
|
94 | 93 | def alias_magic(self, line=''): |
|
95 | 94 | """Create an alias for an existing line or cell magic. |
|
96 | 95 | |
|
97 | 96 | Examples |
|
98 | 97 | -------- |
|
99 | 98 | :: |
|
100 | 99 | |
|
101 | 100 | In [1]: %alias_magic t timeit |
|
102 | 101 | Created `%t` as an alias for `%timeit`. |
|
103 | 102 | Created `%%t` as an alias for `%%timeit`. |
|
104 | 103 | |
|
105 | 104 | In [2]: %t -n1 pass |
|
106 | 105 | 1 loops, best of 3: 954 ns per loop |
|
107 | 106 | |
|
108 | 107 | In [3]: %%t -n1 |
|
109 | 108 | ...: pass |
|
110 | 109 | ...: |
|
111 | 110 | 1 loops, best of 3: 954 ns per loop |
|
112 | 111 | |
|
113 | 112 | In [4]: %alias_magic --cell whereami pwd |
|
114 | 113 | UsageError: Cell magic function `%%pwd` not found. |
|
115 | 114 | In [5]: %alias_magic --line whereami pwd |
|
116 | 115 | Created `%whereami` as an alias for `%pwd`. |
|
117 | 116 | |
|
118 | 117 | In [6]: %whereami |
|
119 | 118 | Out[6]: u'/home/testuser' |
|
120 | 119 | """ |
|
121 | 120 | args = magic_arguments.parse_argstring(self.alias_magic, line) |
|
122 | 121 | shell = self.shell |
|
123 | 122 | mman = self.shell.magics_manager |
|
124 | 123 | escs = ''.join(magic_escapes.values()) |
|
125 | 124 | |
|
126 | 125 | target = args.target.lstrip(escs) |
|
127 | 126 | name = args.name.lstrip(escs) |
|
128 | 127 | |
|
129 | 128 | # Find the requested magics. |
|
130 | 129 | m_line = shell.find_magic(target, 'line') |
|
131 | 130 | m_cell = shell.find_magic(target, 'cell') |
|
132 | 131 | if args.line and m_line is None: |
|
133 | 132 | raise UsageError('Line magic function `%s%s` not found.' % |
|
134 | 133 | (magic_escapes['line'], target)) |
|
135 | 134 | if args.cell and m_cell is None: |
|
136 | 135 | raise UsageError('Cell magic function `%s%s` not found.' % |
|
137 | 136 | (magic_escapes['cell'], target)) |
|
138 | 137 | |
|
139 | 138 | # If --line and --cell are not specified, default to the ones |
|
140 | 139 | # that are available. |
|
141 | 140 | if not args.line and not args.cell: |
|
142 | 141 | if not m_line and not m_cell: |
|
143 | 142 | raise UsageError( |
|
144 | 143 | 'No line or cell magic with name `%s` found.' % target |
|
145 | 144 | ) |
|
146 | 145 | args.line = bool(m_line) |
|
147 | 146 | args.cell = bool(m_cell) |
|
148 | 147 | |
|
149 | 148 | if args.line: |
|
150 | 149 | mman.register_alias(name, target, 'line') |
|
151 | 150 | print('Created `%s%s` as an alias for `%s%s`.' % ( |
|
152 | 151 | magic_escapes['line'], name, |
|
153 | 152 | magic_escapes['line'], target)) |
|
154 | 153 | |
|
155 | 154 | if args.cell: |
|
156 | 155 | mman.register_alias(name, target, 'cell') |
|
157 | 156 | print('Created `%s%s` as an alias for `%s%s`.' % ( |
|
158 | 157 | magic_escapes['cell'], name, |
|
159 | 158 | magic_escapes['cell'], target)) |
|
160 | 159 | |
|
161 | 160 | @line_magic |
|
162 | 161 | def lsmagic(self, parameter_s=''): |
|
163 | 162 | """List currently available magic functions.""" |
|
164 | 163 | return MagicsDisplay(self.shell.magics_manager) |
|
165 | 164 | |
|
166 | 165 | def _magic_docs(self, brief=False, rest=False): |
|
167 | 166 | """Return docstrings from magic functions.""" |
|
168 | 167 | mman = self.shell.magics_manager |
|
169 | 168 | docs = mman.lsmagic_docs(brief, missing='No documentation') |
|
170 | 169 | |
|
171 | 170 | if rest: |
|
172 | 171 | format_string = '**%s%s**::\n\n%s\n\n' |
|
173 | 172 | else: |
|
174 | 173 | format_string = '%s%s:\n%s\n' |
|
175 | 174 | |
|
176 | 175 | return ''.join( |
|
177 | 176 | [format_string % (magic_escapes['line'], fname, |
|
178 | 177 | indent(dedent(fndoc))) |
|
179 | 178 | for fname, fndoc in sorted(docs['line'].items())] |
|
180 | 179 | + |
|
181 | 180 | [format_string % (magic_escapes['cell'], fname, |
|
182 | 181 | indent(dedent(fndoc))) |
|
183 | 182 | for fname, fndoc in sorted(docs['cell'].items())] |
|
184 | 183 | ) |
|
185 | 184 | |
|
186 | 185 | @line_magic |
|
187 | 186 | def magic(self, parameter_s=''): |
|
188 | 187 | """Print information about the magic function system. |
|
189 | 188 | |
|
190 | 189 | Supported formats: -latex, -brief, -rest |
|
191 | 190 | """ |
|
192 | 191 | |
|
193 | 192 | mode = '' |
|
194 | 193 | try: |
|
195 | 194 | mode = parameter_s.split()[0][1:] |
|
196 | 195 | except IndexError: |
|
197 | 196 | pass |
|
198 | 197 | |
|
199 | 198 | brief = (mode == 'brief') |
|
200 | 199 | rest = (mode == 'rest') |
|
201 | 200 | magic_docs = self._magic_docs(brief, rest) |
|
202 | 201 | |
|
203 | 202 | if mode == 'latex': |
|
204 | 203 | print(self.format_latex(magic_docs)) |
|
205 | 204 | return |
|
206 | 205 | else: |
|
207 | 206 | magic_docs = format_screen(magic_docs) |
|
208 | 207 | |
|
209 | 208 | out = [""" |
|
210 | 209 | IPython's 'magic' functions |
|
211 | 210 | =========================== |
|
212 | 211 | |
|
213 | 212 | The magic function system provides a series of functions which allow you to |
|
214 | 213 | control the behavior of IPython itself, plus a lot of system-type |
|
215 | 214 | features. There are two kinds of magics, line-oriented and cell-oriented. |
|
216 | 215 | |
|
217 | 216 | Line magics are prefixed with the % character and work much like OS |
|
218 | 217 | command-line calls: they get as an argument the rest of the line, where |
|
219 | 218 | arguments are passed without parentheses or quotes. For example, this will |
|
220 | 219 | time the given statement:: |
|
221 | 220 | |
|
222 | 221 | %timeit range(1000) |
|
223 | 222 | |
|
224 | 223 | Cell magics are prefixed with a double %%, and they are functions that get as |
|
225 | 224 | an argument not only the rest of the line, but also the lines below it in a |
|
226 | 225 | separate argument. These magics are called with two arguments: the rest of the |
|
227 | 226 | call line and the body of the cell, consisting of the lines below the first. |
|
228 | 227 | For example:: |
|
229 | 228 | |
|
230 | 229 | %%timeit x = numpy.random.randn((100, 100)) |
|
231 | 230 | numpy.linalg.svd(x) |
|
232 | 231 | |
|
233 | 232 | will time the execution of the numpy svd routine, running the assignment of x |
|
234 | 233 | as part of the setup phase, which is not timed. |
|
235 | 234 | |
|
236 | 235 | In a line-oriented client (the terminal or Qt console IPython), starting a new |
|
237 | 236 | input with %% will automatically enter cell mode, and IPython will continue |
|
238 | 237 | reading input until a blank line is given. In the notebook, simply type the |
|
239 | 238 | whole cell as one entity, but keep in mind that the %% escape can only be at |
|
240 | 239 | the very start of the cell. |
|
241 | 240 | |
|
242 | 241 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
243 | 242 | %automagic function), you don't need to type in the % explicitly for line |
|
244 | 243 | magics; cell magics always require an explicit '%%' escape. By default, |
|
245 | 244 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
246 | 245 | |
|
247 | 246 | Example: typing '%cd mydir' (without the quotes) changes your working directory |
|
248 | 247 | to 'mydir', if it exists. |
|
249 | 248 | |
|
250 | 249 | For a list of the available magic functions, use %lsmagic. For a description |
|
251 | 250 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
252 | 251 | |
|
253 | 252 | Currently the magic system has the following functions:""", |
|
254 | 253 | magic_docs, |
|
255 | 254 | "Summary of magic functions (from %slsmagic):" % magic_escapes['line'], |
|
256 | 255 | str(self.lsmagic()), |
|
257 | 256 | ] |
|
258 | 257 | page.page('\n'.join(out)) |
|
259 | 258 | |
|
260 | 259 | |
|
261 | 260 | @line_magic |
|
262 | 261 | def page(self, parameter_s=''): |
|
263 | 262 | """Pretty print the object and display it through a pager. |
|
264 | 263 | |
|
265 | 264 | %page [options] OBJECT |
|
266 | 265 | |
|
267 | 266 | If no object is given, use _ (last output). |
|
268 | 267 | |
|
269 | 268 | Options: |
|
270 | 269 | |
|
271 | 270 | -r: page str(object), don't pretty-print it.""" |
|
272 | 271 | |
|
273 | 272 | # After a function contributed by Olivier Aubert, slightly modified. |
|
274 | 273 | |
|
275 | 274 | # Process options/args |
|
276 | 275 | opts, args = self.parse_options(parameter_s, 'r') |
|
277 | 276 | raw = 'r' in opts |
|
278 | 277 | |
|
279 | 278 | oname = args and args or '_' |
|
280 | 279 | info = self.shell._ofind(oname) |
|
281 | 280 | if info['found']: |
|
282 | 281 | txt = (raw and str or pformat)( info['obj'] ) |
|
283 | 282 | page.page(txt) |
|
284 | 283 | else: |
|
285 | 284 | print('Object `%s` not found' % oname) |
|
286 | 285 | |
|
287 | 286 | @line_magic |
|
288 | 287 | def profile(self, parameter_s=''): |
|
289 | 288 | """Print your currently active IPython profile. |
|
290 | 289 | |
|
291 | 290 | See Also |
|
292 | 291 | -------- |
|
293 | 292 | prun : run code using the Python profiler |
|
294 | 293 | (:meth:`~IPython.core.magics.execution.ExecutionMagics.prun`) |
|
295 | 294 | """ |
|
296 | 295 | warn("%profile is now deprecated. Please use get_ipython().profile instead.") |
|
297 | 296 | from IPython.core.application import BaseIPythonApplication |
|
298 | 297 | if BaseIPythonApplication.initialized(): |
|
299 | 298 | print(BaseIPythonApplication.instance().profile) |
|
300 | 299 | else: |
|
301 | 300 | error("profile is an application-level value, but you don't appear to be in an IPython application") |
|
302 | 301 | |
|
303 | 302 | @line_magic |
|
304 | 303 | def pprint(self, parameter_s=''): |
|
305 | 304 | """Toggle pretty printing on/off.""" |
|
306 | 305 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
307 | 306 | ptformatter.pprint = bool(1 - ptformatter.pprint) |
|
308 | 307 | print('Pretty printing has been turned', |
|
309 | 308 | ['OFF','ON'][ptformatter.pprint]) |
|
310 | 309 | |
|
311 | 310 | @line_magic |
|
312 | 311 | def colors(self, parameter_s=''): |
|
313 | 312 | """Switch color scheme for prompts, info system and exception handlers. |
|
314 | 313 | |
|
315 | 314 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
316 | 315 | |
|
317 | 316 | Color scheme names are not case-sensitive. |
|
318 | 317 | |
|
319 | 318 | Examples |
|
320 | 319 | -------- |
|
321 | 320 | To get a plain black and white terminal:: |
|
322 | 321 | |
|
323 | 322 | %colors nocolor |
|
324 | 323 | """ |
|
325 | 324 | def color_switch_err(name): |
|
326 | 325 | warn('Error changing %s color schemes.\n%s' % |
|
327 | 326 | (name, sys.exc_info()[1]), stacklevel=2) |
|
328 | 327 | |
|
329 | 328 | |
|
330 | 329 | new_scheme = parameter_s.strip() |
|
331 | 330 | if not new_scheme: |
|
332 | 331 | raise UsageError( |
|
333 | 332 | "%colors: you must specify a color scheme. See '%colors?'") |
|
334 | 333 | # local shortcut |
|
335 | 334 | shell = self.shell |
|
336 | 335 | |
|
337 | 336 | # Set shell colour scheme |
|
338 | 337 | try: |
|
339 | 338 | shell.colors = new_scheme |
|
340 | 339 | shell.refresh_style() |
|
341 | 340 | except: |
|
342 | 341 | color_switch_err('shell') |
|
343 | 342 | |
|
344 | 343 | # Set exception colors |
|
345 | 344 | try: |
|
346 | 345 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
347 | 346 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
348 | 347 | except: |
|
349 | 348 | color_switch_err('exception') |
|
350 | 349 | |
|
351 | 350 | # Set info (for 'object?') colors |
|
352 | 351 | if shell.color_info: |
|
353 | 352 | try: |
|
354 | 353 | shell.inspector.set_active_scheme(new_scheme) |
|
355 | 354 | except: |
|
356 | 355 | color_switch_err('object inspector') |
|
357 | 356 | else: |
|
358 | 357 | shell.inspector.set_active_scheme('NoColor') |
|
359 | 358 | |
|
360 | 359 | @line_magic |
|
361 | 360 | def xmode(self, parameter_s=''): |
|
362 | 361 | """Switch modes for the exception handlers. |
|
363 | 362 | |
|
364 | 363 | Valid modes: Plain, Context and Verbose. |
|
365 | 364 | |
|
366 | 365 | If called without arguments, acts as a toggle.""" |
|
367 | 366 | |
|
368 | 367 | def xmode_switch_err(name): |
|
369 | 368 | warn('Error changing %s exception modes.\n%s' % |
|
370 | 369 | (name,sys.exc_info()[1])) |
|
371 | 370 | |
|
372 | 371 | shell = self.shell |
|
373 | 372 | new_mode = parameter_s.strip().capitalize() |
|
374 | 373 | try: |
|
375 | 374 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
376 | 375 | print('Exception reporting mode:',shell.InteractiveTB.mode) |
|
377 | 376 | except: |
|
378 | 377 | xmode_switch_err('user') |
|
379 | 378 | |
|
380 | 379 | @line_magic |
|
381 | 380 | def quickref(self,arg): |
|
382 | 381 | """ Show a quick reference sheet """ |
|
383 | 382 | from IPython.core.usage import quick_reference |
|
384 | 383 | qr = quick_reference + self._magic_docs(brief=True) |
|
385 | 384 | page.page(qr) |
|
386 | 385 | |
|
387 | 386 | @line_magic |
|
388 | 387 | def doctest_mode(self, parameter_s=''): |
|
389 | 388 | """Toggle doctest mode on and off. |
|
390 | 389 | |
|
391 | 390 | This mode is intended to make IPython behave as much as possible like a |
|
392 | 391 | plain Python shell, from the perspective of how its prompts, exceptions |
|
393 | 392 | and output look. This makes it easy to copy and paste parts of a |
|
394 | 393 | session into doctests. It does so by: |
|
395 | 394 | |
|
396 | 395 | - Changing the prompts to the classic ``>>>`` ones. |
|
397 | 396 | - Changing the exception reporting mode to 'Plain'. |
|
398 | 397 | - Disabling pretty-printing of output. |
|
399 | 398 | |
|
400 | 399 | Note that IPython also supports the pasting of code snippets that have |
|
401 | 400 | leading '>>>' and '...' prompts in them. This means that you can paste |
|
402 | 401 | doctests from files or docstrings (even if they have leading |
|
403 | 402 | whitespace), and the code will execute correctly. You can then use |
|
404 | 403 | '%history -t' to see the translated history; this will give you the |
|
405 | 404 | input after removal of all the leading prompts and whitespace, which |
|
406 | 405 | can be pasted back into an editor. |
|
407 | 406 | |
|
408 | 407 | With these features, you can switch into this mode easily whenever you |
|
409 | 408 | need to do testing and changes to doctests, without having to leave |
|
410 | 409 | your existing IPython session. |
|
411 | 410 | """ |
|
412 | 411 | |
|
413 | 412 | # Shorthands |
|
414 | 413 | shell = self.shell |
|
415 | 414 | meta = shell.meta |
|
416 | 415 | disp_formatter = self.shell.display_formatter |
|
417 | 416 | ptformatter = disp_formatter.formatters['text/plain'] |
|
418 | 417 | # dstore is a data store kept in the instance metadata bag to track any |
|
419 | 418 | # changes we make, so we can undo them later. |
|
420 | 419 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
421 | 420 | save_dstore = dstore.setdefault |
|
422 | 421 | |
|
423 | 422 | # save a few values we'll need to recover later |
|
424 | 423 | mode = save_dstore('mode',False) |
|
425 | 424 | save_dstore('rc_pprint',ptformatter.pprint) |
|
426 | 425 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
427 | 426 | save_dstore('rc_separate_out',shell.separate_out) |
|
428 | 427 | save_dstore('rc_separate_out2',shell.separate_out2) |
|
429 | 428 | save_dstore('rc_separate_in',shell.separate_in) |
|
430 | 429 | save_dstore('rc_active_types',disp_formatter.active_types) |
|
431 | 430 | |
|
432 | 431 | if not mode: |
|
433 | 432 | # turn on |
|
434 | 433 | |
|
435 | 434 | # Prompt separators like plain python |
|
436 | 435 | shell.separate_in = '' |
|
437 | 436 | shell.separate_out = '' |
|
438 | 437 | shell.separate_out2 = '' |
|
439 | 438 | |
|
440 | 439 | |
|
441 | 440 | ptformatter.pprint = False |
|
442 | 441 | disp_formatter.active_types = ['text/plain'] |
|
443 | 442 | |
|
444 | 443 | shell.magic('xmode Plain') |
|
445 | 444 | else: |
|
446 | 445 | # turn off |
|
447 | 446 | shell.separate_in = dstore.rc_separate_in |
|
448 | 447 | |
|
449 | 448 | shell.separate_out = dstore.rc_separate_out |
|
450 | 449 | shell.separate_out2 = dstore.rc_separate_out2 |
|
451 | 450 | |
|
452 | 451 | ptformatter.pprint = dstore.rc_pprint |
|
453 | 452 | disp_formatter.active_types = dstore.rc_active_types |
|
454 | 453 | |
|
455 | 454 | shell.magic('xmode ' + dstore.xmode) |
|
456 | 455 | |
|
457 | 456 | # mode here is the state before we switch; switch_doctest_mode takes |
|
458 | 457 | # the mode we're switching to. |
|
459 | 458 | shell.switch_doctest_mode(not mode) |
|
460 | 459 | |
|
461 | 460 | # Store new mode and inform |
|
462 | 461 | dstore.mode = bool(not mode) |
|
463 | 462 | mode_label = ['OFF','ON'][dstore.mode] |
|
464 | 463 | print('Doctest mode is:', mode_label) |
|
465 | 464 | |
|
466 | 465 | @line_magic |
|
467 | 466 | def gui(self, parameter_s=''): |
|
468 | 467 | """Enable or disable IPython GUI event loop integration. |
|
469 | 468 | |
|
470 | 469 | %gui [GUINAME] |
|
471 | 470 | |
|
472 | 471 | This magic replaces IPython's threaded shells that were activated |
|
473 | 472 | using the (pylab/wthread/etc.) command line flags. GUI toolkits |
|
474 | 473 | can now be enabled at runtime and keyboard |
|
475 | 474 | interrupts should work without any problems. The following toolkits |
|
476 | 475 | are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX):: |
|
477 | 476 | |
|
478 | 477 | %gui wx # enable wxPython event loop integration |
|
479 | 478 | %gui qt4|qt # enable PyQt4 event loop integration |
|
480 | 479 | %gui qt5 # enable PyQt5 event loop integration |
|
481 | 480 | %gui gtk # enable PyGTK event loop integration |
|
482 | 481 | %gui gtk3 # enable Gtk3 event loop integration |
|
483 | 482 | %gui tk # enable Tk event loop integration |
|
484 | 483 | %gui osx # enable Cocoa event loop integration |
|
485 | 484 | # (requires %matplotlib 1.1) |
|
486 | 485 | %gui # disable all event loop integration |
|
487 | 486 | |
|
488 | 487 | WARNING: after any of these has been called you can simply create |
|
489 | 488 | an application object, but DO NOT start the event loop yourself, as |
|
490 | 489 | we have already handled that. |
|
491 | 490 | """ |
|
492 | 491 | opts, arg = self.parse_options(parameter_s, '') |
|
493 | 492 | if arg=='': arg = None |
|
494 | 493 | try: |
|
495 | 494 | return self.shell.enable_gui(arg) |
|
496 | 495 | except Exception as e: |
|
497 | 496 | # print simple error message, rather than traceback if we can't |
|
498 | 497 | # hook up the GUI |
|
499 | 498 | error(str(e)) |
|
500 | 499 | |
|
501 | 500 | @skip_doctest |
|
502 | 501 | @line_magic |
|
503 | 502 | def precision(self, s=''): |
|
504 | 503 | """Set floating point precision for pretty printing. |
|
505 | 504 | |
|
506 | 505 | Can set either integer precision or a format string. |
|
507 | 506 | |
|
508 | 507 | If numpy has been imported and precision is an int, |
|
509 | 508 | numpy display precision will also be set, via ``numpy.set_printoptions``. |
|
510 | 509 | |
|
511 | 510 | If no argument is given, defaults will be restored. |
|
512 | 511 | |
|
513 | 512 | Examples |
|
514 | 513 | -------- |
|
515 | 514 | :: |
|
516 | 515 | |
|
517 | 516 | In [1]: from math import pi |
|
518 | 517 | |
|
519 | 518 | In [2]: %precision 3 |
|
520 | 519 | Out[2]: u'%.3f' |
|
521 | 520 | |
|
522 | 521 | In [3]: pi |
|
523 | 522 | Out[3]: 3.142 |
|
524 | 523 | |
|
525 | 524 | In [4]: %precision %i |
|
526 | 525 | Out[4]: u'%i' |
|
527 | 526 | |
|
528 | 527 | In [5]: pi |
|
529 | 528 | Out[5]: 3 |
|
530 | 529 | |
|
531 | 530 | In [6]: %precision %e |
|
532 | 531 | Out[6]: u'%e' |
|
533 | 532 | |
|
534 | 533 | In [7]: pi**10 |
|
535 | 534 | Out[7]: 9.364805e+04 |
|
536 | 535 | |
|
537 | 536 | In [8]: %precision |
|
538 | 537 | Out[8]: u'%r' |
|
539 | 538 | |
|
540 | 539 | In [9]: pi**10 |
|
541 | 540 | Out[9]: 93648.047476082982 |
|
542 | 541 | """ |
|
543 | 542 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
544 | 543 | ptformatter.float_precision = s |
|
545 | 544 | return ptformatter.float_format |
|
546 | 545 | |
|
547 | 546 | @magic_arguments.magic_arguments() |
|
548 | 547 | @magic_arguments.argument( |
|
549 | 548 | '-e', '--export', action='store_true', default=False, |
|
550 | 549 | help=argparse.SUPPRESS |
|
551 | 550 | ) |
|
552 | 551 | @magic_arguments.argument( |
|
553 |
'filename', type= |
|
|
552 | 'filename', type=str, | |
|
554 | 553 | help='Notebook name or filename' |
|
555 | 554 | ) |
|
556 | 555 | @line_magic |
|
557 | 556 | def notebook(self, s): |
|
558 | 557 | """Export and convert IPython notebooks. |
|
559 | 558 | |
|
560 | 559 | This function can export the current IPython history to a notebook file. |
|
561 | 560 | For example, to export the history to "foo.ipynb" do "%notebook foo.ipynb". |
|
562 | 561 | |
|
563 | 562 | The -e or --export flag is deprecated in IPython 5.2, and will be |
|
564 | 563 | removed in the future. |
|
565 | 564 | """ |
|
566 | 565 | args = magic_arguments.parse_argstring(self.notebook, s) |
|
567 | 566 | |
|
568 | 567 | from nbformat import write, v4 |
|
569 | 568 | |
|
570 | 569 | cells = [] |
|
571 | 570 | hist = list(self.shell.history_manager.get_range()) |
|
572 | 571 | if(len(hist)<=1): |
|
573 | 572 | raise ValueError('History is empty, cannot export') |
|
574 | 573 | for session, execution_count, source in hist[:-1]: |
|
575 | 574 | cells.append(v4.new_code_cell( |
|
576 | 575 | execution_count=execution_count, |
|
577 | 576 | source=source |
|
578 | 577 | )) |
|
579 | 578 | nb = v4.new_notebook(cells=cells) |
|
580 | 579 | with io.open(args.filename, 'w', encoding='utf-8') as f: |
|
581 | 580 | write(nb, f, version=4) |
@@ -1,744 +1,743 b'' | |||
|
1 | 1 | """Implementation of code management magic functions. |
|
2 | 2 | """ |
|
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 inspect |
|
17 | 17 | import io |
|
18 | 18 | import os |
|
19 | 19 | import re |
|
20 | 20 | import sys |
|
21 | 21 | import ast |
|
22 | 22 | from itertools import chain |
|
23 | 23 | |
|
24 | 24 | # Our own packages |
|
25 | 25 | from IPython.core.error import TryNext, StdinNotImplementedError, UsageError |
|
26 | 26 | from IPython.core.macro import Macro |
|
27 | 27 | from IPython.core.magic import Magics, magics_class, line_magic |
|
28 | 28 | from IPython.core.oinspect import find_file, find_source_lines |
|
29 | 29 | from IPython.testing.skipdoctest import skip_doctest |
|
30 | 30 | from IPython.utils import py3compat |
|
31 | from IPython.utils.py3compat import string_types | |
|
32 | 31 | from IPython.utils.contexts import preserve_keys |
|
33 | 32 | from IPython.utils.path import get_py_filename |
|
34 | 33 | from warnings import warn |
|
35 | 34 | from logging import error |
|
36 | 35 | from IPython.utils.text import get_text_list |
|
37 | 36 | |
|
38 | 37 | #----------------------------------------------------------------------------- |
|
39 | 38 | # Magic implementation classes |
|
40 | 39 | #----------------------------------------------------------------------------- |
|
41 | 40 | |
|
42 | 41 | # Used for exception handling in magic_edit |
|
43 | 42 | class MacroToEdit(ValueError): pass |
|
44 | 43 | |
|
45 | 44 | ipython_input_pat = re.compile(r"<ipython\-input\-(\d+)-[a-z\d]+>$") |
|
46 | 45 | |
|
47 | 46 | # To match, e.g. 8-10 1:5 :10 3- |
|
48 | 47 | range_re = re.compile(r""" |
|
49 | 48 | (?P<start>\d+)? |
|
50 | 49 | ((?P<sep>[\-:]) |
|
51 | 50 | (?P<end>\d+)?)? |
|
52 | 51 | $""", re.VERBOSE) |
|
53 | 52 | |
|
54 | 53 | |
|
55 | 54 | def extract_code_ranges(ranges_str): |
|
56 | 55 | """Turn a string of range for %%load into 2-tuples of (start, stop) |
|
57 | 56 | ready to use as a slice of the content splitted by lines. |
|
58 | 57 | |
|
59 | 58 | Examples |
|
60 | 59 | -------- |
|
61 | 60 | list(extract_input_ranges("5-10 2")) |
|
62 | 61 | [(4, 10), (1, 2)] |
|
63 | 62 | """ |
|
64 | 63 | for range_str in ranges_str.split(): |
|
65 | 64 | rmatch = range_re.match(range_str) |
|
66 | 65 | if not rmatch: |
|
67 | 66 | continue |
|
68 | 67 | sep = rmatch.group("sep") |
|
69 | 68 | start = rmatch.group("start") |
|
70 | 69 | end = rmatch.group("end") |
|
71 | 70 | |
|
72 | 71 | if sep == '-': |
|
73 | 72 | start = int(start) - 1 if start else None |
|
74 | 73 | end = int(end) if end else None |
|
75 | 74 | elif sep == ':': |
|
76 | 75 | start = int(start) - 1 if start else None |
|
77 | 76 | end = int(end) - 1 if end else None |
|
78 | 77 | else: |
|
79 | 78 | end = int(start) |
|
80 | 79 | start = int(start) - 1 |
|
81 | 80 | yield (start, end) |
|
82 | 81 | |
|
83 | 82 | |
|
84 | 83 | @skip_doctest |
|
85 | 84 | def extract_symbols(code, symbols): |
|
86 | 85 | """ |
|
87 | 86 | Return a tuple (blocks, not_found) |
|
88 | 87 | where ``blocks`` is a list of code fragments |
|
89 | 88 | for each symbol parsed from code, and ``not_found`` are |
|
90 | 89 | symbols not found in the code. |
|
91 | 90 | |
|
92 | 91 | For example:: |
|
93 | 92 | |
|
94 | 93 | >>> code = '''a = 10 |
|
95 | 94 | |
|
96 | 95 | def b(): return 42 |
|
97 | 96 | |
|
98 | 97 | class A: pass''' |
|
99 | 98 | |
|
100 | 99 | >>> extract_symbols(code, 'A,b,z') |
|
101 | 100 | (["class A: pass", "def b(): return 42"], ['z']) |
|
102 | 101 | """ |
|
103 | 102 | symbols = symbols.split(',') |
|
104 | 103 | |
|
105 | 104 | # this will raise SyntaxError if code isn't valid Python |
|
106 | 105 | py_code = ast.parse(code) |
|
107 | 106 | |
|
108 | 107 | marks = [(getattr(s, 'name', None), s.lineno) for s in py_code.body] |
|
109 | 108 | code = code.split('\n') |
|
110 | 109 | |
|
111 | 110 | symbols_lines = {} |
|
112 | 111 | |
|
113 | 112 | # we already know the start_lineno of each symbol (marks). |
|
114 | 113 | # To find each end_lineno, we traverse in reverse order until each |
|
115 | 114 | # non-blank line |
|
116 | 115 | end = len(code) |
|
117 | 116 | for name, start in reversed(marks): |
|
118 | 117 | while not code[end - 1].strip(): |
|
119 | 118 | end -= 1 |
|
120 | 119 | if name: |
|
121 | 120 | symbols_lines[name] = (start - 1, end) |
|
122 | 121 | end = start - 1 |
|
123 | 122 | |
|
124 | 123 | # Now symbols_lines is a map |
|
125 | 124 | # {'symbol_name': (start_lineno, end_lineno), ...} |
|
126 | 125 | |
|
127 | 126 | # fill a list with chunks of codes for each requested symbol |
|
128 | 127 | blocks = [] |
|
129 | 128 | not_found = [] |
|
130 | 129 | for symbol in symbols: |
|
131 | 130 | if symbol in symbols_lines: |
|
132 | 131 | start, end = symbols_lines[symbol] |
|
133 | 132 | blocks.append('\n'.join(code[start:end]) + '\n') |
|
134 | 133 | else: |
|
135 | 134 | not_found.append(symbol) |
|
136 | 135 | |
|
137 | 136 | return blocks, not_found |
|
138 | 137 | |
|
139 | 138 | def strip_initial_indent(lines): |
|
140 | 139 | """For %load, strip indent from lines until finding an unindented line. |
|
141 | 140 | |
|
142 | 141 | https://github.com/ipython/ipython/issues/9775 |
|
143 | 142 | """ |
|
144 | 143 | indent_re = re.compile(r'\s+') |
|
145 | 144 | |
|
146 | 145 | it = iter(lines) |
|
147 | 146 | first_line = next(it) |
|
148 | 147 | indent_match = indent_re.match(first_line) |
|
149 | 148 | |
|
150 | 149 | if indent_match: |
|
151 | 150 | # First line was indented |
|
152 | 151 | indent = indent_match.group() |
|
153 | 152 | yield first_line[len(indent):] |
|
154 | 153 | |
|
155 | 154 | for line in it: |
|
156 | 155 | if line.startswith(indent): |
|
157 | 156 | yield line[len(indent):] |
|
158 | 157 | else: |
|
159 | 158 | # Less indented than the first line - stop dedenting |
|
160 | 159 | yield line |
|
161 | 160 | break |
|
162 | 161 | else: |
|
163 | 162 | yield first_line |
|
164 | 163 | |
|
165 | 164 | # Pass the remaining lines through without dedenting |
|
166 | 165 | for line in it: |
|
167 | 166 | yield line |
|
168 | 167 | |
|
169 | 168 | |
|
170 | 169 | class InteractivelyDefined(Exception): |
|
171 | 170 | """Exception for interactively defined variable in magic_edit""" |
|
172 | 171 | def __init__(self, index): |
|
173 | 172 | self.index = index |
|
174 | 173 | |
|
175 | 174 | |
|
176 | 175 | @magics_class |
|
177 | 176 | class CodeMagics(Magics): |
|
178 | 177 | """Magics related to code management (loading, saving, editing, ...).""" |
|
179 | 178 | |
|
180 | 179 | def __init__(self, *args, **kwargs): |
|
181 | 180 | self._knowntemps = set() |
|
182 | 181 | super(CodeMagics, self).__init__(*args, **kwargs) |
|
183 | 182 | |
|
184 | 183 | @line_magic |
|
185 | 184 | def save(self, parameter_s=''): |
|
186 | 185 | """Save a set of lines or a macro to a given filename. |
|
187 | 186 | |
|
188 | 187 | Usage:\\ |
|
189 | 188 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
190 | 189 | |
|
191 | 190 | Options: |
|
192 | 191 | |
|
193 | 192 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
194 | 193 | so that magics are loaded in their transformed version to valid |
|
195 | 194 | Python. If this option is given, the raw input as typed as the |
|
196 | 195 | command line is used instead. |
|
197 | 196 | |
|
198 | 197 | -f: force overwrite. If file exists, %save will prompt for overwrite |
|
199 | 198 | unless -f is given. |
|
200 | 199 | |
|
201 | 200 | -a: append to the file instead of overwriting it. |
|
202 | 201 | |
|
203 | 202 | This function uses the same syntax as %history for input ranges, |
|
204 | 203 | then saves the lines to the filename you specify. |
|
205 | 204 | |
|
206 | 205 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
207 | 206 | it asks for confirmation before overwriting existing files. |
|
208 | 207 | |
|
209 | 208 | If `-r` option is used, the default extension is `.ipy`. |
|
210 | 209 | """ |
|
211 | 210 | |
|
212 | 211 | opts,args = self.parse_options(parameter_s,'fra',mode='list') |
|
213 | 212 | if not args: |
|
214 | 213 | raise UsageError('Missing filename.') |
|
215 | 214 | raw = 'r' in opts |
|
216 | 215 | force = 'f' in opts |
|
217 | 216 | append = 'a' in opts |
|
218 | 217 | mode = 'a' if append else 'w' |
|
219 | 218 | ext = u'.ipy' if raw else u'.py' |
|
220 | 219 | fname, codefrom = args[0], " ".join(args[1:]) |
|
221 | 220 | if not fname.endswith((u'.py',u'.ipy')): |
|
222 | 221 | fname += ext |
|
223 | 222 | file_exists = os.path.isfile(fname) |
|
224 | 223 | if file_exists and not force and not append: |
|
225 | 224 | try: |
|
226 | 225 | overwrite = self.shell.ask_yes_no('File `%s` exists. Overwrite (y/[N])? ' % fname, default='n') |
|
227 | 226 | except StdinNotImplementedError: |
|
228 | 227 | print("File `%s` exists. Use `%%save -f %s` to force overwrite" % (fname, parameter_s)) |
|
229 | 228 | return |
|
230 | 229 | if not overwrite : |
|
231 | 230 | print('Operation cancelled.') |
|
232 | 231 | return |
|
233 | 232 | try: |
|
234 | 233 | cmds = self.shell.find_user_code(codefrom,raw) |
|
235 | 234 | except (TypeError, ValueError) as e: |
|
236 | 235 | print(e.args[0]) |
|
237 | 236 | return |
|
238 | 237 | out = py3compat.cast_unicode(cmds) |
|
239 | 238 | with io.open(fname, mode, encoding="utf-8") as f: |
|
240 | 239 | if not file_exists or not append: |
|
241 | 240 | f.write(u"# coding: utf-8\n") |
|
242 | 241 | f.write(out) |
|
243 | 242 | # make sure we end on a newline |
|
244 | 243 | if not out.endswith(u'\n'): |
|
245 | 244 | f.write(u'\n') |
|
246 | 245 | print('The following commands were written to file `%s`:' % fname) |
|
247 | 246 | print(cmds) |
|
248 | 247 | |
|
249 | 248 | @line_magic |
|
250 | 249 | def pastebin(self, parameter_s=''): |
|
251 | 250 | """Upload code to Github's Gist paste bin, returning the URL. |
|
252 | 251 | |
|
253 | 252 | Usage:\\ |
|
254 | 253 | %pastebin [-d "Custom description"] 1-7 |
|
255 | 254 | |
|
256 | 255 | The argument can be an input history range, a filename, or the name of a |
|
257 | 256 | string or macro. |
|
258 | 257 | |
|
259 | 258 | Options: |
|
260 | 259 | |
|
261 | 260 | -d: Pass a custom description for the gist. The default will say |
|
262 | 261 | "Pasted from IPython". |
|
263 | 262 | """ |
|
264 | 263 | opts, args = self.parse_options(parameter_s, 'd:') |
|
265 | 264 | |
|
266 | 265 | try: |
|
267 | 266 | code = self.shell.find_user_code(args) |
|
268 | 267 | except (ValueError, TypeError) as e: |
|
269 | 268 | print(e.args[0]) |
|
270 | 269 | return |
|
271 | 270 | |
|
272 | 271 | # Deferred import |
|
273 | 272 | try: |
|
274 | 273 | from urllib.request import urlopen # Py 3 |
|
275 | 274 | except ImportError: |
|
276 | 275 | from urllib2 import urlopen |
|
277 | 276 | import json |
|
278 | 277 | post_data = json.dumps({ |
|
279 | 278 | "description": opts.get('d', "Pasted from IPython"), |
|
280 | 279 | "public": True, |
|
281 | 280 | "files": { |
|
282 | 281 | "file1.py": { |
|
283 | 282 | "content": code |
|
284 | 283 | } |
|
285 | 284 | } |
|
286 | 285 | }).encode('utf-8') |
|
287 | 286 | |
|
288 | 287 | response = urlopen("https://api.github.com/gists", post_data) |
|
289 | 288 | response_data = json.loads(response.read().decode('utf-8')) |
|
290 | 289 | return response_data['html_url'] |
|
291 | 290 | |
|
292 | 291 | @line_magic |
|
293 | 292 | def loadpy(self, arg_s): |
|
294 | 293 | """Alias of `%load` |
|
295 | 294 | |
|
296 | 295 | `%loadpy` has gained some flexibility and dropped the requirement of a `.py` |
|
297 | 296 | extension. So it has been renamed simply into %load. You can look at |
|
298 | 297 | `%load`'s docstring for more info. |
|
299 | 298 | """ |
|
300 | 299 | self.load(arg_s) |
|
301 | 300 | |
|
302 | 301 | @line_magic |
|
303 | 302 | def load(self, arg_s): |
|
304 | 303 | """Load code into the current frontend. |
|
305 | 304 | |
|
306 | 305 | Usage:\\ |
|
307 | 306 | %load [options] source |
|
308 | 307 | |
|
309 | 308 | where source can be a filename, URL, input history range, macro, or |
|
310 | 309 | element in the user namespace |
|
311 | 310 | |
|
312 | 311 | Options: |
|
313 | 312 | |
|
314 | 313 | -r <lines>: Specify lines or ranges of lines to load from the source. |
|
315 | 314 | Ranges could be specified as x-y (x..y) or in python-style x:y |
|
316 | 315 | (x..(y-1)). Both limits x and y can be left blank (meaning the |
|
317 | 316 | beginning and end of the file, respectively). |
|
318 | 317 | |
|
319 | 318 | -s <symbols>: Specify function or classes to load from python source. |
|
320 | 319 | |
|
321 | 320 | -y : Don't ask confirmation for loading source above 200 000 characters. |
|
322 | 321 | |
|
323 | 322 | -n : Include the user's namespace when searching for source code. |
|
324 | 323 | |
|
325 | 324 | This magic command can either take a local filename, a URL, an history |
|
326 | 325 | range (see %history) or a macro as argument, it will prompt for |
|
327 | 326 | confirmation before loading source with more than 200 000 characters, unless |
|
328 | 327 | -y flag is passed or if the frontend does not support raw_input:: |
|
329 | 328 | |
|
330 | 329 | %load myscript.py |
|
331 | 330 | %load 7-27 |
|
332 | 331 | %load myMacro |
|
333 | 332 | %load http://www.example.com/myscript.py |
|
334 | 333 | %load -r 5-10 myscript.py |
|
335 | 334 | %load -r 10-20,30,40: foo.py |
|
336 | 335 | %load -s MyClass,wonder_function myscript.py |
|
337 | 336 | %load -n MyClass |
|
338 | 337 | %load -n my_module.wonder_function |
|
339 | 338 | """ |
|
340 | 339 | opts,args = self.parse_options(arg_s,'yns:r:') |
|
341 | 340 | |
|
342 | 341 | if not args: |
|
343 | 342 | raise UsageError('Missing filename, URL, input history range, ' |
|
344 | 343 | 'macro, or element in the user namespace.') |
|
345 | 344 | |
|
346 | 345 | search_ns = 'n' in opts |
|
347 | 346 | |
|
348 | 347 | contents = self.shell.find_user_code(args, search_ns=search_ns) |
|
349 | 348 | |
|
350 | 349 | if 's' in opts: |
|
351 | 350 | try: |
|
352 | 351 | blocks, not_found = extract_symbols(contents, opts['s']) |
|
353 | 352 | except SyntaxError: |
|
354 | 353 | # non python code |
|
355 | 354 | error("Unable to parse the input as valid Python code") |
|
356 | 355 | return |
|
357 | 356 | |
|
358 | 357 | if len(not_found) == 1: |
|
359 | 358 | warn('The symbol `%s` was not found' % not_found[0]) |
|
360 | 359 | elif len(not_found) > 1: |
|
361 | 360 | warn('The symbols %s were not found' % get_text_list(not_found, |
|
362 | 361 | wrap_item_with='`') |
|
363 | 362 | ) |
|
364 | 363 | |
|
365 | 364 | contents = '\n'.join(blocks) |
|
366 | 365 | |
|
367 | 366 | if 'r' in opts: |
|
368 | 367 | ranges = opts['r'].replace(',', ' ') |
|
369 | 368 | lines = contents.split('\n') |
|
370 | 369 | slices = extract_code_ranges(ranges) |
|
371 | 370 | contents = [lines[slice(*slc)] for slc in slices] |
|
372 | 371 | contents = '\n'.join(strip_initial_indent(chain.from_iterable(contents))) |
|
373 | 372 | |
|
374 | 373 | l = len(contents) |
|
375 | 374 | |
|
376 | 375 | # 200 000 is ~ 2500 full 80 caracter lines |
|
377 | 376 | # so in average, more than 5000 lines |
|
378 | 377 | if l > 200000 and 'y' not in opts: |
|
379 | 378 | try: |
|
380 | 379 | ans = self.shell.ask_yes_no(("The text you're trying to load seems pretty big"\ |
|
381 | 380 | " (%d characters). Continue (y/[N]) ?" % l), default='n' ) |
|
382 | 381 | except StdinNotImplementedError: |
|
383 | 382 | #asume yes if raw input not implemented |
|
384 | 383 | ans = True |
|
385 | 384 | |
|
386 | 385 | if ans is False : |
|
387 | 386 | print('Operation cancelled.') |
|
388 | 387 | return |
|
389 | 388 | |
|
390 | 389 | contents = "# %load {}\n".format(arg_s) + contents |
|
391 | 390 | |
|
392 | 391 | self.shell.set_next_input(contents, replace=True) |
|
393 | 392 | |
|
394 | 393 | @staticmethod |
|
395 | 394 | def _find_edit_target(shell, args, opts, last_call): |
|
396 | 395 | """Utility method used by magic_edit to find what to edit.""" |
|
397 | 396 | |
|
398 | 397 | def make_filename(arg): |
|
399 | 398 | "Make a filename from the given args" |
|
400 | 399 | try: |
|
401 | 400 | filename = get_py_filename(arg) |
|
402 | 401 | except IOError: |
|
403 | 402 | # If it ends with .py but doesn't already exist, assume we want |
|
404 | 403 | # a new file. |
|
405 | 404 | if arg.endswith('.py'): |
|
406 | 405 | filename = arg |
|
407 | 406 | else: |
|
408 | 407 | filename = None |
|
409 | 408 | return filename |
|
410 | 409 | |
|
411 | 410 | # Set a few locals from the options for convenience: |
|
412 | 411 | opts_prev = 'p' in opts |
|
413 | 412 | opts_raw = 'r' in opts |
|
414 | 413 | |
|
415 | 414 | # custom exceptions |
|
416 | 415 | class DataIsObject(Exception): pass |
|
417 | 416 | |
|
418 | 417 | # Default line number value |
|
419 | 418 | lineno = opts.get('n',None) |
|
420 | 419 | |
|
421 | 420 | if opts_prev: |
|
422 | 421 | args = '_%s' % last_call[0] |
|
423 | 422 | if args not in shell.user_ns: |
|
424 | 423 | args = last_call[1] |
|
425 | 424 | |
|
426 | 425 | # by default this is done with temp files, except when the given |
|
427 | 426 | # arg is a filename |
|
428 | 427 | use_temp = True |
|
429 | 428 | |
|
430 | 429 | data = '' |
|
431 | 430 | |
|
432 | 431 | # First, see if the arguments should be a filename. |
|
433 | 432 | filename = make_filename(args) |
|
434 | 433 | if filename: |
|
435 | 434 | use_temp = False |
|
436 | 435 | elif args: |
|
437 | 436 | # Mode where user specifies ranges of lines, like in %macro. |
|
438 | 437 | data = shell.extract_input_lines(args, opts_raw) |
|
439 | 438 | if not data: |
|
440 | 439 | try: |
|
441 | 440 | # Load the parameter given as a variable. If not a string, |
|
442 | 441 | # process it as an object instead (below) |
|
443 | 442 | |
|
444 | 443 | #print '*** args',args,'type',type(args) # dbg |
|
445 | 444 | data = eval(args, shell.user_ns) |
|
446 |
if not isinstance(data, str |
|
|
445 | if not isinstance(data, str): | |
|
447 | 446 | raise DataIsObject |
|
448 | 447 | |
|
449 | 448 | except (NameError,SyntaxError): |
|
450 | 449 | # given argument is not a variable, try as a filename |
|
451 | 450 | filename = make_filename(args) |
|
452 | 451 | if filename is None: |
|
453 | 452 | warn("Argument given (%s) can't be found as a variable " |
|
454 | 453 | "or as a filename." % args) |
|
455 | 454 | return (None, None, None) |
|
456 | 455 | use_temp = False |
|
457 | 456 | |
|
458 | 457 | except DataIsObject: |
|
459 | 458 | # macros have a special edit function |
|
460 | 459 | if isinstance(data, Macro): |
|
461 | 460 | raise MacroToEdit(data) |
|
462 | 461 | |
|
463 | 462 | # For objects, try to edit the file where they are defined |
|
464 | 463 | filename = find_file(data) |
|
465 | 464 | if filename: |
|
466 | 465 | if 'fakemodule' in filename.lower() and \ |
|
467 | 466 | inspect.isclass(data): |
|
468 | 467 | # class created by %edit? Try to find source |
|
469 | 468 | # by looking for method definitions instead, the |
|
470 | 469 | # __module__ in those classes is FakeModule. |
|
471 | 470 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
472 | 471 | for attr in attrs: |
|
473 | 472 | if not inspect.ismethod(attr): |
|
474 | 473 | continue |
|
475 | 474 | filename = find_file(attr) |
|
476 | 475 | if filename and \ |
|
477 | 476 | 'fakemodule' not in filename.lower(): |
|
478 | 477 | # change the attribute to be the edit |
|
479 | 478 | # target instead |
|
480 | 479 | data = attr |
|
481 | 480 | break |
|
482 | 481 | |
|
483 | 482 | m = ipython_input_pat.match(os.path.basename(filename)) |
|
484 | 483 | if m: |
|
485 | 484 | raise InteractivelyDefined(int(m.groups()[0])) |
|
486 | 485 | |
|
487 | 486 | datafile = 1 |
|
488 | 487 | if filename is None: |
|
489 | 488 | filename = make_filename(args) |
|
490 | 489 | datafile = 1 |
|
491 | 490 | if filename is not None: |
|
492 | 491 | # only warn about this if we get a real name |
|
493 | 492 | warn('Could not find file where `%s` is defined.\n' |
|
494 | 493 | 'Opening a file named `%s`' % (args, filename)) |
|
495 | 494 | # Now, make sure we can actually read the source (if it was |
|
496 | 495 | # in a temp file it's gone by now). |
|
497 | 496 | if datafile: |
|
498 | 497 | if lineno is None: |
|
499 | 498 | lineno = find_source_lines(data) |
|
500 | 499 | if lineno is None: |
|
501 | 500 | filename = make_filename(args) |
|
502 | 501 | if filename is None: |
|
503 | 502 | warn('The file where `%s` was defined ' |
|
504 | 503 | 'cannot be read or found.' % data) |
|
505 | 504 | return (None, None, None) |
|
506 | 505 | use_temp = False |
|
507 | 506 | |
|
508 | 507 | if use_temp: |
|
509 | 508 | filename = shell.mktempfile(data) |
|
510 | 509 | print('IPython will make a temporary file named:',filename) |
|
511 | 510 | |
|
512 | 511 | # use last_call to remember the state of the previous call, but don't |
|
513 | 512 | # let it be clobbered by successive '-p' calls. |
|
514 | 513 | try: |
|
515 | 514 | last_call[0] = shell.displayhook.prompt_count |
|
516 | 515 | if not opts_prev: |
|
517 | 516 | last_call[1] = args |
|
518 | 517 | except: |
|
519 | 518 | pass |
|
520 | 519 | |
|
521 | 520 | |
|
522 | 521 | return filename, lineno, use_temp |
|
523 | 522 | |
|
524 | 523 | def _edit_macro(self,mname,macro): |
|
525 | 524 | """open an editor with the macro data in a file""" |
|
526 | 525 | filename = self.shell.mktempfile(macro.value) |
|
527 | 526 | self.shell.hooks.editor(filename) |
|
528 | 527 | |
|
529 | 528 | # and make a new macro object, to replace the old one |
|
530 | 529 | with open(filename) as mfile: |
|
531 | 530 | mvalue = mfile.read() |
|
532 | 531 | self.shell.user_ns[mname] = Macro(mvalue) |
|
533 | 532 | |
|
534 | 533 | @skip_doctest |
|
535 | 534 | @line_magic |
|
536 | 535 | def edit(self, parameter_s='',last_call=['','']): |
|
537 | 536 | """Bring up an editor and execute the resulting code. |
|
538 | 537 | |
|
539 | 538 | Usage: |
|
540 | 539 | %edit [options] [args] |
|
541 | 540 | |
|
542 | 541 | %edit runs IPython's editor hook. The default version of this hook is |
|
543 | 542 | set to call the editor specified by your $EDITOR environment variable. |
|
544 | 543 | If this isn't found, it will default to vi under Linux/Unix and to |
|
545 | 544 | notepad under Windows. See the end of this docstring for how to change |
|
546 | 545 | the editor hook. |
|
547 | 546 | |
|
548 | 547 | You can also set the value of this editor via the |
|
549 | 548 | ``TerminalInteractiveShell.editor`` option in your configuration file. |
|
550 | 549 | This is useful if you wish to use a different editor from your typical |
|
551 | 550 | default with IPython (and for Windows users who typically don't set |
|
552 | 551 | environment variables). |
|
553 | 552 | |
|
554 | 553 | This command allows you to conveniently edit multi-line code right in |
|
555 | 554 | your IPython session. |
|
556 | 555 | |
|
557 | 556 | If called without arguments, %edit opens up an empty editor with a |
|
558 | 557 | temporary file and will execute the contents of this file when you |
|
559 | 558 | close it (don't forget to save it!). |
|
560 | 559 | |
|
561 | 560 | |
|
562 | 561 | Options: |
|
563 | 562 | |
|
564 | 563 | -n <number>: open the editor at a specified line number. By default, |
|
565 | 564 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
566 | 565 | you can configure this by providing your own modified hook if your |
|
567 | 566 | favorite editor supports line-number specifications with a different |
|
568 | 567 | syntax. |
|
569 | 568 | |
|
570 | 569 | -p: this will call the editor with the same data as the previous time |
|
571 | 570 | it was used, regardless of how long ago (in your current session) it |
|
572 | 571 | was. |
|
573 | 572 | |
|
574 | 573 | -r: use 'raw' input. This option only applies to input taken from the |
|
575 | 574 | user's history. By default, the 'processed' history is used, so that |
|
576 | 575 | magics are loaded in their transformed version to valid Python. If |
|
577 | 576 | this option is given, the raw input as typed as the command line is |
|
578 | 577 | used instead. When you exit the editor, it will be executed by |
|
579 | 578 | IPython's own processor. |
|
580 | 579 | |
|
581 | 580 | -x: do not execute the edited code immediately upon exit. This is |
|
582 | 581 | mainly useful if you are editing programs which need to be called with |
|
583 | 582 | command line arguments, which you can then do using %run. |
|
584 | 583 | |
|
585 | 584 | |
|
586 | 585 | Arguments: |
|
587 | 586 | |
|
588 | 587 | If arguments are given, the following possibilities exist: |
|
589 | 588 | |
|
590 | 589 | - If the argument is a filename, IPython will load that into the |
|
591 | 590 | editor. It will execute its contents with execfile() when you exit, |
|
592 | 591 | loading any code in the file into your interactive namespace. |
|
593 | 592 | |
|
594 | 593 | - The arguments are ranges of input history, e.g. "7 ~1/4-6". |
|
595 | 594 | The syntax is the same as in the %history magic. |
|
596 | 595 | |
|
597 | 596 | - If the argument is a string variable, its contents are loaded |
|
598 | 597 | into the editor. You can thus edit any string which contains |
|
599 | 598 | python code (including the result of previous edits). |
|
600 | 599 | |
|
601 | 600 | - If the argument is the name of an object (other than a string), |
|
602 | 601 | IPython will try to locate the file where it was defined and open the |
|
603 | 602 | editor at the point where it is defined. You can use `%edit function` |
|
604 | 603 | to load an editor exactly at the point where 'function' is defined, |
|
605 | 604 | edit it and have the file be executed automatically. |
|
606 | 605 | |
|
607 | 606 | - If the object is a macro (see %macro for details), this opens up your |
|
608 | 607 | specified editor with a temporary file containing the macro's data. |
|
609 | 608 | Upon exit, the macro is reloaded with the contents of the file. |
|
610 | 609 | |
|
611 | 610 | Note: opening at an exact line is only supported under Unix, and some |
|
612 | 611 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
613 | 612 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
614 | 613 | (X)Emacs, vi, jed, pico and joe all do. |
|
615 | 614 | |
|
616 | 615 | After executing your code, %edit will return as output the code you |
|
617 | 616 | typed in the editor (except when it was an existing file). This way |
|
618 | 617 | you can reload the code in further invocations of %edit as a variable, |
|
619 | 618 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
620 | 619 | the output. |
|
621 | 620 | |
|
622 | 621 | Note that %edit is also available through the alias %ed. |
|
623 | 622 | |
|
624 | 623 | This is an example of creating a simple function inside the editor and |
|
625 | 624 | then modifying it. First, start up the editor:: |
|
626 | 625 | |
|
627 | 626 | In [1]: edit |
|
628 | 627 | Editing... done. Executing edited code... |
|
629 | 628 | Out[1]: 'def foo():\\n print "foo() was defined in an editing |
|
630 | 629 | session"\\n' |
|
631 | 630 | |
|
632 | 631 | We can then call the function foo():: |
|
633 | 632 | |
|
634 | 633 | In [2]: foo() |
|
635 | 634 | foo() was defined in an editing session |
|
636 | 635 | |
|
637 | 636 | Now we edit foo. IPython automatically loads the editor with the |
|
638 | 637 | (temporary) file where foo() was previously defined:: |
|
639 | 638 | |
|
640 | 639 | In [3]: edit foo |
|
641 | 640 | Editing... done. Executing edited code... |
|
642 | 641 | |
|
643 | 642 | And if we call foo() again we get the modified version:: |
|
644 | 643 | |
|
645 | 644 | In [4]: foo() |
|
646 | 645 | foo() has now been changed! |
|
647 | 646 | |
|
648 | 647 | Here is an example of how to edit a code snippet successive |
|
649 | 648 | times. First we call the editor:: |
|
650 | 649 | |
|
651 | 650 | In [5]: edit |
|
652 | 651 | Editing... done. Executing edited code... |
|
653 | 652 | hello |
|
654 | 653 | Out[5]: "print 'hello'\\n" |
|
655 | 654 | |
|
656 | 655 | Now we call it again with the previous output (stored in _):: |
|
657 | 656 | |
|
658 | 657 | In [6]: edit _ |
|
659 | 658 | Editing... done. Executing edited code... |
|
660 | 659 | hello world |
|
661 | 660 | Out[6]: "print 'hello world'\\n" |
|
662 | 661 | |
|
663 | 662 | Now we call it with the output #8 (stored in _8, also as Out[8]):: |
|
664 | 663 | |
|
665 | 664 | In [7]: edit _8 |
|
666 | 665 | Editing... done. Executing edited code... |
|
667 | 666 | hello again |
|
668 | 667 | Out[7]: "print 'hello again'\\n" |
|
669 | 668 | |
|
670 | 669 | |
|
671 | 670 | Changing the default editor hook: |
|
672 | 671 | |
|
673 | 672 | If you wish to write your own editor hook, you can put it in a |
|
674 | 673 | configuration file which you load at startup time. The default hook |
|
675 | 674 | is defined in the IPython.core.hooks module, and you can use that as a |
|
676 | 675 | starting example for further modifications. That file also has |
|
677 | 676 | general instructions on how to set a new hook for use once you've |
|
678 | 677 | defined it.""" |
|
679 | 678 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
680 | 679 | |
|
681 | 680 | try: |
|
682 | 681 | filename, lineno, is_temp = self._find_edit_target(self.shell, |
|
683 | 682 | args, opts, last_call) |
|
684 | 683 | except MacroToEdit as e: |
|
685 | 684 | self._edit_macro(args, e.args[0]) |
|
686 | 685 | return |
|
687 | 686 | except InteractivelyDefined as e: |
|
688 | 687 | print("Editing In[%i]" % e.index) |
|
689 | 688 | args = str(e.index) |
|
690 | 689 | filename, lineno, is_temp = self._find_edit_target(self.shell, |
|
691 | 690 | args, opts, last_call) |
|
692 | 691 | if filename is None: |
|
693 | 692 | # nothing was found, warnings have already been issued, |
|
694 | 693 | # just give up. |
|
695 | 694 | return |
|
696 | 695 | |
|
697 | 696 | if is_temp: |
|
698 | 697 | self._knowntemps.add(filename) |
|
699 | 698 | elif (filename in self._knowntemps): |
|
700 | 699 | is_temp = True |
|
701 | 700 | |
|
702 | 701 | |
|
703 | 702 | # do actual editing here |
|
704 | 703 | print('Editing...', end=' ') |
|
705 | 704 | sys.stdout.flush() |
|
706 | 705 | try: |
|
707 | 706 | # Quote filenames that may have spaces in them |
|
708 | 707 | if ' ' in filename: |
|
709 | 708 | filename = "'%s'" % filename |
|
710 | 709 | self.shell.hooks.editor(filename,lineno) |
|
711 | 710 | except TryNext: |
|
712 | 711 | warn('Could not open editor') |
|
713 | 712 | return |
|
714 | 713 | |
|
715 | 714 | # XXX TODO: should this be generalized for all string vars? |
|
716 | 715 | # For now, this is special-cased to blocks created by cpaste |
|
717 | 716 | if args.strip() == 'pasted_block': |
|
718 | 717 | with open(filename, 'r') as f: |
|
719 | 718 | self.shell.user_ns['pasted_block'] = f.read() |
|
720 | 719 | |
|
721 | 720 | if 'x' in opts: # -x prevents actual execution |
|
722 | 721 | print() |
|
723 | 722 | else: |
|
724 | 723 | print('done. Executing edited code...') |
|
725 | 724 | with preserve_keys(self.shell.user_ns, '__file__'): |
|
726 | 725 | if not is_temp: |
|
727 | 726 | self.shell.user_ns['__file__'] = filename |
|
728 | 727 | if 'r' in opts: # Untranslated IPython code |
|
729 | 728 | with open(filename, 'r') as f: |
|
730 | 729 | source = f.read() |
|
731 | 730 | self.shell.run_cell(source, store_history=False) |
|
732 | 731 | else: |
|
733 | 732 | self.shell.safe_execfile(filename, self.shell.user_ns, |
|
734 | 733 | self.shell.user_ns) |
|
735 | 734 | |
|
736 | 735 | if is_temp: |
|
737 | 736 | try: |
|
738 | 737 | return open(filename).read() |
|
739 | 738 | except IOError as msg: |
|
740 | 739 | if msg.filename == filename: |
|
741 | 740 | warn('File not found. Did you forget to save?') |
|
742 | 741 | return |
|
743 | 742 | else: |
|
744 | 743 | self.shell.showtraceback() |
@@ -1,1381 +1,1380 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Implementation of execution-related magic functions.""" |
|
3 | 3 | |
|
4 | 4 | # Copyright (c) IPython Development Team. |
|
5 | 5 | # Distributed under the terms of the Modified BSD License. |
|
6 | 6 | |
|
7 | 7 | |
|
8 | 8 | import ast |
|
9 | 9 | import bdb |
|
10 | 10 | import gc |
|
11 | 11 | import itertools |
|
12 | 12 | import os |
|
13 | 13 | import sys |
|
14 | 14 | import time |
|
15 | 15 | import timeit |
|
16 | 16 | import math |
|
17 | 17 | from pdb import Restart |
|
18 | 18 | |
|
19 | 19 | # cProfile was added in Python2.5 |
|
20 | 20 | try: |
|
21 | 21 | import cProfile as profile |
|
22 | 22 | import pstats |
|
23 | 23 | except ImportError: |
|
24 | 24 | # profile isn't bundled by default in Debian for license reasons |
|
25 | 25 | try: |
|
26 | 26 | import profile, pstats |
|
27 | 27 | except ImportError: |
|
28 | 28 | profile = pstats = None |
|
29 | 29 | |
|
30 | 30 | from IPython.core import oinspect |
|
31 | 31 | from IPython.core import magic_arguments |
|
32 | 32 | from IPython.core import page |
|
33 | 33 | from IPython.core.error import UsageError |
|
34 | 34 | from IPython.core.macro import Macro |
|
35 | 35 | from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic, |
|
36 | 36 | line_cell_magic, on_off, needs_local_scope) |
|
37 | 37 | from IPython.testing.skipdoctest import skip_doctest |
|
38 | 38 | from IPython.utils import py3compat |
|
39 |
from IPython.utils.py3compat import builtin_mod, |
|
|
39 | from IPython.utils.py3compat import builtin_mod, PY3 | |
|
40 | 40 | from IPython.utils.contexts import preserve_keys |
|
41 | 41 | from IPython.utils.capture import capture_output |
|
42 | 42 | from IPython.utils.ipstruct import Struct |
|
43 | 43 | from IPython.utils.module_paths import find_mod |
|
44 | 44 | from IPython.utils.path import get_py_filename, shellglob |
|
45 | 45 | from IPython.utils.timing import clock, clock2 |
|
46 | 46 | from warnings import warn |
|
47 | 47 | from logging import error |
|
48 | 48 | |
|
49 | 49 | if PY3: |
|
50 | 50 | from io import StringIO |
|
51 | 51 | else: |
|
52 | 52 | from StringIO import StringIO |
|
53 | 53 | |
|
54 | 54 | #----------------------------------------------------------------------------- |
|
55 | 55 | # Magic implementation classes |
|
56 | 56 | #----------------------------------------------------------------------------- |
|
57 | 57 | |
|
58 | 58 | |
|
59 | 59 | class TimeitResult(object): |
|
60 | 60 | """ |
|
61 | 61 | Object returned by the timeit magic with info about the run. |
|
62 | 62 | |
|
63 | 63 | Contains the following attributes : |
|
64 | 64 | |
|
65 | 65 | loops: (int) number of loops done per measurement |
|
66 | 66 | repeat: (int) number of times the measurement has been repeated |
|
67 | 67 | best: (float) best execution time / number |
|
68 | 68 | all_runs: (list of float) execution time of each run (in s) |
|
69 | 69 | compile_time: (float) time of statement compilation (s) |
|
70 | 70 | |
|
71 | 71 | """ |
|
72 | 72 | def __init__(self, loops, repeat, best, worst, all_runs, compile_time, precision): |
|
73 | 73 | self.loops = loops |
|
74 | 74 | self.repeat = repeat |
|
75 | 75 | self.best = best |
|
76 | 76 | self.worst = worst |
|
77 | 77 | self.all_runs = all_runs |
|
78 | 78 | self.compile_time = compile_time |
|
79 | 79 | self._precision = precision |
|
80 | 80 | self.timings = [ dt / self.loops for dt in all_runs] |
|
81 | 81 | |
|
82 | 82 | @property |
|
83 | 83 | def average(self): |
|
84 | 84 | return math.fsum(self.timings) / len(self.timings) |
|
85 | 85 | |
|
86 | 86 | @property |
|
87 | 87 | def stdev(self): |
|
88 | 88 | mean = self.average |
|
89 | 89 | return (math.fsum([(x - mean) ** 2 for x in self.timings]) / len(self.timings)) ** 0.5 |
|
90 | 90 | |
|
91 | 91 | def __str__(self): |
|
92 | 92 | return (u"%s loop%s, average of %d: %s +- %s per loop (using standard deviation)" |
|
93 | 93 | % (self.loops,"" if self.loops == 1 else "s", self.repeat, |
|
94 | 94 | _format_time(self.average, self._precision), |
|
95 | 95 | _format_time(self.stdev, self._precision))) |
|
96 | 96 | |
|
97 | 97 | def _repr_pretty_(self, p , cycle): |
|
98 | 98 | unic = self.__str__() |
|
99 | 99 | p.text(u'<TimeitResult : '+unic+u'>') |
|
100 | 100 | |
|
101 | 101 | |
|
102 | 102 | |
|
103 | 103 | class TimeitTemplateFiller(ast.NodeTransformer): |
|
104 | 104 | """Fill in the AST template for timing execution. |
|
105 | 105 | |
|
106 | 106 | This is quite closely tied to the template definition, which is in |
|
107 | 107 | :meth:`ExecutionMagics.timeit`. |
|
108 | 108 | """ |
|
109 | 109 | def __init__(self, ast_setup, ast_stmt): |
|
110 | 110 | self.ast_setup = ast_setup |
|
111 | 111 | self.ast_stmt = ast_stmt |
|
112 | 112 | |
|
113 | 113 | def visit_FunctionDef(self, node): |
|
114 | 114 | "Fill in the setup statement" |
|
115 | 115 | self.generic_visit(node) |
|
116 | 116 | if node.name == "inner": |
|
117 | 117 | node.body[:1] = self.ast_setup.body |
|
118 | 118 | |
|
119 | 119 | return node |
|
120 | 120 | |
|
121 | 121 | def visit_For(self, node): |
|
122 | 122 | "Fill in the statement to be timed" |
|
123 | 123 | if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt': |
|
124 | 124 | node.body = self.ast_stmt.body |
|
125 | 125 | return node |
|
126 | 126 | |
|
127 | 127 | |
|
128 | 128 | class Timer(timeit.Timer): |
|
129 | 129 | """Timer class that explicitly uses self.inner |
|
130 | 130 | |
|
131 | 131 | which is an undocumented implementation detail of CPython, |
|
132 | 132 | not shared by PyPy. |
|
133 | 133 | """ |
|
134 | 134 | # Timer.timeit copied from CPython 3.4.2 |
|
135 | 135 | def timeit(self, number=timeit.default_number): |
|
136 | 136 | """Time 'number' executions of the main statement. |
|
137 | 137 | |
|
138 | 138 | To be precise, this executes the setup statement once, and |
|
139 | 139 | then returns the time it takes to execute the main statement |
|
140 | 140 | a number of times, as a float measured in seconds. The |
|
141 | 141 | argument is the number of times through the loop, defaulting |
|
142 | 142 | to one million. The main statement, the setup statement and |
|
143 | 143 | the timer function to be used are passed to the constructor. |
|
144 | 144 | """ |
|
145 | 145 | it = itertools.repeat(None, number) |
|
146 | 146 | gcold = gc.isenabled() |
|
147 | 147 | gc.disable() |
|
148 | 148 | try: |
|
149 | 149 | timing = self.inner(it, self.timer) |
|
150 | 150 | finally: |
|
151 | 151 | if gcold: |
|
152 | 152 | gc.enable() |
|
153 | 153 | return timing |
|
154 | 154 | |
|
155 | 155 | |
|
156 | 156 | @magics_class |
|
157 | 157 | class ExecutionMagics(Magics): |
|
158 | 158 | """Magics related to code execution, debugging, profiling, etc. |
|
159 | 159 | |
|
160 | 160 | """ |
|
161 | 161 | |
|
162 | 162 | def __init__(self, shell): |
|
163 | 163 | super(ExecutionMagics, self).__init__(shell) |
|
164 | 164 | if profile is None: |
|
165 | 165 | self.prun = self.profile_missing_notice |
|
166 | 166 | # Default execution function used to actually run user code. |
|
167 | 167 | self.default_runner = None |
|
168 | 168 | |
|
169 | 169 | def profile_missing_notice(self, *args, **kwargs): |
|
170 | 170 | error("""\ |
|
171 | 171 | The profile module could not be found. It has been removed from the standard |
|
172 | 172 | python packages because of its non-free license. To use profiling, install the |
|
173 | 173 | python-profiler package from non-free.""") |
|
174 | 174 | |
|
175 | 175 | @skip_doctest |
|
176 | 176 | @line_cell_magic |
|
177 | 177 | def prun(self, parameter_s='', cell=None): |
|
178 | 178 | |
|
179 | 179 | """Run a statement through the python code profiler. |
|
180 | 180 | |
|
181 | 181 | Usage, in line mode: |
|
182 | 182 | %prun [options] statement |
|
183 | 183 | |
|
184 | 184 | Usage, in cell mode: |
|
185 | 185 | %%prun [options] [statement] |
|
186 | 186 | code... |
|
187 | 187 | code... |
|
188 | 188 | |
|
189 | 189 | In cell mode, the additional code lines are appended to the (possibly |
|
190 | 190 | empty) statement in the first line. Cell mode allows you to easily |
|
191 | 191 | profile multiline blocks without having to put them in a separate |
|
192 | 192 | function. |
|
193 | 193 | |
|
194 | 194 | The given statement (which doesn't require quote marks) is run via the |
|
195 | 195 | python profiler in a manner similar to the profile.run() function. |
|
196 | 196 | Namespaces are internally managed to work correctly; profile.run |
|
197 | 197 | cannot be used in IPython because it makes certain assumptions about |
|
198 | 198 | namespaces which do not hold under IPython. |
|
199 | 199 | |
|
200 | 200 | Options: |
|
201 | 201 | |
|
202 | 202 | -l <limit> |
|
203 | 203 | you can place restrictions on what or how much of the |
|
204 | 204 | profile gets printed. The limit value can be: |
|
205 | 205 | |
|
206 | 206 | * A string: only information for function names containing this string |
|
207 | 207 | is printed. |
|
208 | 208 | |
|
209 | 209 | * An integer: only these many lines are printed. |
|
210 | 210 | |
|
211 | 211 | * A float (between 0 and 1): this fraction of the report is printed |
|
212 | 212 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
213 | 213 | |
|
214 | 214 | You can combine several limits with repeated use of the option. For |
|
215 | 215 | example, ``-l __init__ -l 5`` will print only the topmost 5 lines of |
|
216 | 216 | information about class constructors. |
|
217 | 217 | |
|
218 | 218 | -r |
|
219 | 219 | return the pstats.Stats object generated by the profiling. This |
|
220 | 220 | object has all the information about the profile in it, and you can |
|
221 | 221 | later use it for further analysis or in other functions. |
|
222 | 222 | |
|
223 | 223 | -s <key> |
|
224 | 224 | sort profile by given key. You can provide more than one key |
|
225 | 225 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
226 | 226 | default sorting key is 'time'. |
|
227 | 227 | |
|
228 | 228 | The following is copied verbatim from the profile documentation |
|
229 | 229 | referenced below: |
|
230 | 230 | |
|
231 | 231 | When more than one key is provided, additional keys are used as |
|
232 | 232 | secondary criteria when the there is equality in all keys selected |
|
233 | 233 | before them. |
|
234 | 234 | |
|
235 | 235 | Abbreviations can be used for any key names, as long as the |
|
236 | 236 | abbreviation is unambiguous. The following are the keys currently |
|
237 | 237 | defined: |
|
238 | 238 | |
|
239 | 239 | ============ ===================== |
|
240 | 240 | Valid Arg Meaning |
|
241 | 241 | ============ ===================== |
|
242 | 242 | "calls" call count |
|
243 | 243 | "cumulative" cumulative time |
|
244 | 244 | "file" file name |
|
245 | 245 | "module" file name |
|
246 | 246 | "pcalls" primitive call count |
|
247 | 247 | "line" line number |
|
248 | 248 | "name" function name |
|
249 | 249 | "nfl" name/file/line |
|
250 | 250 | "stdname" standard name |
|
251 | 251 | "time" internal time |
|
252 | 252 | ============ ===================== |
|
253 | 253 | |
|
254 | 254 | Note that all sorts on statistics are in descending order (placing |
|
255 | 255 | most time consuming items first), where as name, file, and line number |
|
256 | 256 | searches are in ascending order (i.e., alphabetical). The subtle |
|
257 | 257 | distinction between "nfl" and "stdname" is that the standard name is a |
|
258 | 258 | sort of the name as printed, which means that the embedded line |
|
259 | 259 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
260 | 260 | would (if the file names were the same) appear in the string order |
|
261 | 261 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
262 | 262 | line numbers. In fact, sort_stats("nfl") is the same as |
|
263 | 263 | sort_stats("name", "file", "line"). |
|
264 | 264 | |
|
265 | 265 | -T <filename> |
|
266 | 266 | save profile results as shown on screen to a text |
|
267 | 267 | file. The profile is still shown on screen. |
|
268 | 268 | |
|
269 | 269 | -D <filename> |
|
270 | 270 | save (via dump_stats) profile statistics to given |
|
271 | 271 | filename. This data is in a format understood by the pstats module, and |
|
272 | 272 | is generated by a call to the dump_stats() method of profile |
|
273 | 273 | objects. The profile is still shown on screen. |
|
274 | 274 | |
|
275 | 275 | -q |
|
276 | 276 | suppress output to the pager. Best used with -T and/or -D above. |
|
277 | 277 | |
|
278 | 278 | If you want to run complete programs under the profiler's control, use |
|
279 | 279 | ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts |
|
280 | 280 | contains profiler specific options as described here. |
|
281 | 281 | |
|
282 | 282 | You can read the complete documentation for the profile module with:: |
|
283 | 283 | |
|
284 | 284 | In [1]: import profile; profile.help() |
|
285 | 285 | """ |
|
286 | 286 | opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q', |
|
287 | 287 | list_all=True, posix=False) |
|
288 | 288 | if cell is not None: |
|
289 | 289 | arg_str += '\n' + cell |
|
290 | 290 | arg_str = self.shell.input_splitter.transform_cell(arg_str) |
|
291 | 291 | return self._run_with_profiler(arg_str, opts, self.shell.user_ns) |
|
292 | 292 | |
|
293 | 293 | def _run_with_profiler(self, code, opts, namespace): |
|
294 | 294 | """ |
|
295 | 295 | Run `code` with profiler. Used by ``%prun`` and ``%run -p``. |
|
296 | 296 | |
|
297 | 297 | Parameters |
|
298 | 298 | ---------- |
|
299 | 299 | code : str |
|
300 | 300 | Code to be executed. |
|
301 | 301 | opts : Struct |
|
302 | 302 | Options parsed by `self.parse_options`. |
|
303 | 303 | namespace : dict |
|
304 | 304 | A dictionary for Python namespace (e.g., `self.shell.user_ns`). |
|
305 | 305 | |
|
306 | 306 | """ |
|
307 | 307 | |
|
308 | 308 | # Fill default values for unspecified options: |
|
309 | 309 | opts.merge(Struct(D=[''], l=[], s=['time'], T=[''])) |
|
310 | 310 | |
|
311 | 311 | prof = profile.Profile() |
|
312 | 312 | try: |
|
313 | 313 | prof = prof.runctx(code, namespace, namespace) |
|
314 | 314 | sys_exit = '' |
|
315 | 315 | except SystemExit: |
|
316 | 316 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
317 | 317 | |
|
318 | 318 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
319 | 319 | |
|
320 | 320 | lims = opts.l |
|
321 | 321 | if lims: |
|
322 | 322 | lims = [] # rebuild lims with ints/floats/strings |
|
323 | 323 | for lim in opts.l: |
|
324 | 324 | try: |
|
325 | 325 | lims.append(int(lim)) |
|
326 | 326 | except ValueError: |
|
327 | 327 | try: |
|
328 | 328 | lims.append(float(lim)) |
|
329 | 329 | except ValueError: |
|
330 | 330 | lims.append(lim) |
|
331 | 331 | |
|
332 | 332 | # Trap output. |
|
333 | 333 | stdout_trap = StringIO() |
|
334 | 334 | stats_stream = stats.stream |
|
335 | 335 | try: |
|
336 | 336 | stats.stream = stdout_trap |
|
337 | 337 | stats.print_stats(*lims) |
|
338 | 338 | finally: |
|
339 | 339 | stats.stream = stats_stream |
|
340 | 340 | |
|
341 | 341 | output = stdout_trap.getvalue() |
|
342 | 342 | output = output.rstrip() |
|
343 | 343 | |
|
344 | 344 | if 'q' not in opts: |
|
345 | 345 | page.page(output) |
|
346 | 346 | print(sys_exit, end=' ') |
|
347 | 347 | |
|
348 | 348 | dump_file = opts.D[0] |
|
349 | 349 | text_file = opts.T[0] |
|
350 | 350 | if dump_file: |
|
351 | 351 | prof.dump_stats(dump_file) |
|
352 | 352 | print('\n*** Profile stats marshalled to file',\ |
|
353 | 353 | repr(dump_file)+'.',sys_exit) |
|
354 | 354 | if text_file: |
|
355 | 355 | pfile = open(text_file,'w') |
|
356 | 356 | pfile.write(output) |
|
357 | 357 | pfile.close() |
|
358 | 358 | print('\n*** Profile printout saved to text file',\ |
|
359 | 359 | repr(text_file)+'.',sys_exit) |
|
360 | 360 | |
|
361 | 361 | if 'r' in opts: |
|
362 | 362 | return stats |
|
363 | 363 | else: |
|
364 | 364 | return None |
|
365 | 365 | |
|
366 | 366 | @line_magic |
|
367 | 367 | def pdb(self, parameter_s=''): |
|
368 | 368 | """Control the automatic calling of the pdb interactive debugger. |
|
369 | 369 | |
|
370 | 370 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
371 | 371 | argument it works as a toggle. |
|
372 | 372 | |
|
373 | 373 | When an exception is triggered, IPython can optionally call the |
|
374 | 374 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
375 | 375 | this feature on and off. |
|
376 | 376 | |
|
377 | 377 | The initial state of this feature is set in your configuration |
|
378 | 378 | file (the option is ``InteractiveShell.pdb``). |
|
379 | 379 | |
|
380 | 380 | If you want to just activate the debugger AFTER an exception has fired, |
|
381 | 381 | without having to type '%pdb on' and rerunning your code, you can use |
|
382 | 382 | the %debug magic.""" |
|
383 | 383 | |
|
384 | 384 | par = parameter_s.strip().lower() |
|
385 | 385 | |
|
386 | 386 | if par: |
|
387 | 387 | try: |
|
388 | 388 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
389 | 389 | except KeyError: |
|
390 | 390 | print ('Incorrect argument. Use on/1, off/0, ' |
|
391 | 391 | 'or nothing for a toggle.') |
|
392 | 392 | return |
|
393 | 393 | else: |
|
394 | 394 | # toggle |
|
395 | 395 | new_pdb = not self.shell.call_pdb |
|
396 | 396 | |
|
397 | 397 | # set on the shell |
|
398 | 398 | self.shell.call_pdb = new_pdb |
|
399 | 399 | print('Automatic pdb calling has been turned',on_off(new_pdb)) |
|
400 | 400 | |
|
401 | 401 | @skip_doctest |
|
402 | 402 | @magic_arguments.magic_arguments() |
|
403 | 403 | @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE', |
|
404 | 404 | help=""" |
|
405 | 405 | Set break point at LINE in FILE. |
|
406 | 406 | """ |
|
407 | 407 | ) |
|
408 | 408 | @magic_arguments.argument('statement', nargs='*', |
|
409 | 409 | help=""" |
|
410 | 410 | Code to run in debugger. |
|
411 | 411 | You can omit this in cell magic mode. |
|
412 | 412 | """ |
|
413 | 413 | ) |
|
414 | 414 | @line_cell_magic |
|
415 | 415 | def debug(self, line='', cell=None): |
|
416 | 416 | """Activate the interactive debugger. |
|
417 | 417 | |
|
418 | 418 | This magic command support two ways of activating debugger. |
|
419 | 419 | One is to activate debugger before executing code. This way, you |
|
420 | 420 | can set a break point, to step through the code from the point. |
|
421 | 421 | You can use this mode by giving statements to execute and optionally |
|
422 | 422 | a breakpoint. |
|
423 | 423 | |
|
424 | 424 | The other one is to activate debugger in post-mortem mode. You can |
|
425 | 425 | activate this mode simply running %debug without any argument. |
|
426 | 426 | If an exception has just occurred, this lets you inspect its stack |
|
427 | 427 | frames interactively. Note that this will always work only on the last |
|
428 | 428 | traceback that occurred, so you must call this quickly after an |
|
429 | 429 | exception that you wish to inspect has fired, because if another one |
|
430 | 430 | occurs, it clobbers the previous one. |
|
431 | 431 | |
|
432 | 432 | If you want IPython to automatically do this on every exception, see |
|
433 | 433 | the %pdb magic for more details. |
|
434 | 434 | """ |
|
435 | 435 | args = magic_arguments.parse_argstring(self.debug, line) |
|
436 | 436 | |
|
437 | 437 | if not (args.breakpoint or args.statement or cell): |
|
438 | 438 | self._debug_post_mortem() |
|
439 | 439 | else: |
|
440 | 440 | code = "\n".join(args.statement) |
|
441 | 441 | if cell: |
|
442 | 442 | code += "\n" + cell |
|
443 | 443 | self._debug_exec(code, args.breakpoint) |
|
444 | 444 | |
|
445 | 445 | def _debug_post_mortem(self): |
|
446 | 446 | self.shell.debugger(force=True) |
|
447 | 447 | |
|
448 | 448 | def _debug_exec(self, code, breakpoint): |
|
449 | 449 | if breakpoint: |
|
450 | 450 | (filename, bp_line) = breakpoint.rsplit(':', 1) |
|
451 | 451 | bp_line = int(bp_line) |
|
452 | 452 | else: |
|
453 | 453 | (filename, bp_line) = (None, None) |
|
454 | 454 | self._run_with_debugger(code, self.shell.user_ns, filename, bp_line) |
|
455 | 455 | |
|
456 | 456 | @line_magic |
|
457 | 457 | def tb(self, s): |
|
458 | 458 | """Print the last traceback with the currently active exception mode. |
|
459 | 459 | |
|
460 | 460 | See %xmode for changing exception reporting modes.""" |
|
461 | 461 | self.shell.showtraceback() |
|
462 | 462 | |
|
463 | 463 | @skip_doctest |
|
464 | 464 | @line_magic |
|
465 | 465 | def run(self, parameter_s='', runner=None, |
|
466 | 466 | file_finder=get_py_filename): |
|
467 | 467 | """Run the named file inside IPython as a program. |
|
468 | 468 | |
|
469 | 469 | Usage:: |
|
470 | 470 | |
|
471 | 471 | %run [-n -i -e -G] |
|
472 | 472 | [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )] |
|
473 | 473 | ( -m mod | file ) [args] |
|
474 | 474 | |
|
475 | 475 | Parameters after the filename are passed as command-line arguments to |
|
476 | 476 | the program (put in sys.argv). Then, control returns to IPython's |
|
477 | 477 | prompt. |
|
478 | 478 | |
|
479 | 479 | This is similar to running at a system prompt ``python file args``, |
|
480 | 480 | but with the advantage of giving you IPython's tracebacks, and of |
|
481 | 481 | loading all variables into your interactive namespace for further use |
|
482 | 482 | (unless -p is used, see below). |
|
483 | 483 | |
|
484 | 484 | The file is executed in a namespace initially consisting only of |
|
485 | 485 | ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus |
|
486 | 486 | sees its environment as if it were being run as a stand-alone program |
|
487 | 487 | (except for sharing global objects such as previously imported |
|
488 | 488 | modules). But after execution, the IPython interactive namespace gets |
|
489 | 489 | updated with all variables defined in the program (except for __name__ |
|
490 | 490 | and sys.argv). This allows for very convenient loading of code for |
|
491 | 491 | interactive work, while giving each program a 'clean sheet' to run in. |
|
492 | 492 | |
|
493 | 493 | Arguments are expanded using shell-like glob match. Patterns |
|
494 | 494 | '*', '?', '[seq]' and '[!seq]' can be used. Additionally, |
|
495 | 495 | tilde '~' will be expanded into user's home directory. Unlike |
|
496 | 496 | real shells, quotation does not suppress expansions. Use |
|
497 | 497 | *two* back slashes (e.g. ``\\\\*``) to suppress expansions. |
|
498 | 498 | To completely disable these expansions, you can use -G flag. |
|
499 | 499 | |
|
500 | 500 | Options: |
|
501 | 501 | |
|
502 | 502 | -n |
|
503 | 503 | __name__ is NOT set to '__main__', but to the running file's name |
|
504 | 504 | without extension (as python does under import). This allows running |
|
505 | 505 | scripts and reloading the definitions in them without calling code |
|
506 | 506 | protected by an ``if __name__ == "__main__"`` clause. |
|
507 | 507 | |
|
508 | 508 | -i |
|
509 | 509 | run the file in IPython's namespace instead of an empty one. This |
|
510 | 510 | is useful if you are experimenting with code written in a text editor |
|
511 | 511 | which depends on variables defined interactively. |
|
512 | 512 | |
|
513 | 513 | -e |
|
514 | 514 | ignore sys.exit() calls or SystemExit exceptions in the script |
|
515 | 515 | being run. This is particularly useful if IPython is being used to |
|
516 | 516 | run unittests, which always exit with a sys.exit() call. In such |
|
517 | 517 | cases you are interested in the output of the test results, not in |
|
518 | 518 | seeing a traceback of the unittest module. |
|
519 | 519 | |
|
520 | 520 | -t |
|
521 | 521 | print timing information at the end of the run. IPython will give |
|
522 | 522 | you an estimated CPU time consumption for your script, which under |
|
523 | 523 | Unix uses the resource module to avoid the wraparound problems of |
|
524 | 524 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
525 | 525 | is also given (for Windows platforms this is reported as 0.0). |
|
526 | 526 | |
|
527 | 527 | If -t is given, an additional ``-N<N>`` option can be given, where <N> |
|
528 | 528 | must be an integer indicating how many times you want the script to |
|
529 | 529 | run. The final timing report will include total and per run results. |
|
530 | 530 | |
|
531 | 531 | For example (testing the script uniq_stable.py):: |
|
532 | 532 | |
|
533 | 533 | In [1]: run -t uniq_stable |
|
534 | 534 | |
|
535 | 535 | IPython CPU timings (estimated): |
|
536 | 536 | User : 0.19597 s. |
|
537 | 537 | System: 0.0 s. |
|
538 | 538 | |
|
539 | 539 | In [2]: run -t -N5 uniq_stable |
|
540 | 540 | |
|
541 | 541 | IPython CPU timings (estimated): |
|
542 | 542 | Total runs performed: 5 |
|
543 | 543 | Times : Total Per run |
|
544 | 544 | User : 0.910862 s, 0.1821724 s. |
|
545 | 545 | System: 0.0 s, 0.0 s. |
|
546 | 546 | |
|
547 | 547 | -d |
|
548 | 548 | run your program under the control of pdb, the Python debugger. |
|
549 | 549 | This allows you to execute your program step by step, watch variables, |
|
550 | 550 | etc. Internally, what IPython does is similar to calling:: |
|
551 | 551 | |
|
552 | 552 | pdb.run('execfile("YOURFILENAME")') |
|
553 | 553 | |
|
554 | 554 | with a breakpoint set on line 1 of your file. You can change the line |
|
555 | 555 | number for this automatic breakpoint to be <N> by using the -bN option |
|
556 | 556 | (where N must be an integer). For example:: |
|
557 | 557 | |
|
558 | 558 | %run -d -b40 myscript |
|
559 | 559 | |
|
560 | 560 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
561 | 561 | the first breakpoint must be set on a line which actually does |
|
562 | 562 | something (not a comment or docstring) for it to stop execution. |
|
563 | 563 | |
|
564 | 564 | Or you can specify a breakpoint in a different file:: |
|
565 | 565 | |
|
566 | 566 | %run -d -b myotherfile.py:20 myscript |
|
567 | 567 | |
|
568 | 568 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
569 | 569 | first enter 'c' (without quotes) to start execution up to the first |
|
570 | 570 | breakpoint. |
|
571 | 571 | |
|
572 | 572 | Entering 'help' gives information about the use of the debugger. You |
|
573 | 573 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
574 | 574 | at a prompt. |
|
575 | 575 | |
|
576 | 576 | -p |
|
577 | 577 | run program under the control of the Python profiler module (which |
|
578 | 578 | prints a detailed report of execution times, function calls, etc). |
|
579 | 579 | |
|
580 | 580 | You can pass other options after -p which affect the behavior of the |
|
581 | 581 | profiler itself. See the docs for %prun for details. |
|
582 | 582 | |
|
583 | 583 | In this mode, the program's variables do NOT propagate back to the |
|
584 | 584 | IPython interactive namespace (because they remain in the namespace |
|
585 | 585 | where the profiler executes them). |
|
586 | 586 | |
|
587 | 587 | Internally this triggers a call to %prun, see its documentation for |
|
588 | 588 | details on the options available specifically for profiling. |
|
589 | 589 | |
|
590 | 590 | There is one special usage for which the text above doesn't apply: |
|
591 | 591 | if the filename ends with .ipy[nb], the file is run as ipython script, |
|
592 | 592 | just as if the commands were written on IPython prompt. |
|
593 | 593 | |
|
594 | 594 | -m |
|
595 | 595 | specify module name to load instead of script path. Similar to |
|
596 | 596 | the -m option for the python interpreter. Use this option last if you |
|
597 | 597 | want to combine with other %run options. Unlike the python interpreter |
|
598 | 598 | only source modules are allowed no .pyc or .pyo files. |
|
599 | 599 | For example:: |
|
600 | 600 | |
|
601 | 601 | %run -m example |
|
602 | 602 | |
|
603 | 603 | will run the example module. |
|
604 | 604 | |
|
605 | 605 | -G |
|
606 | 606 | disable shell-like glob expansion of arguments. |
|
607 | 607 | |
|
608 | 608 | """ |
|
609 | 609 | |
|
610 | 610 | # get arguments and set sys.argv for program to be run. |
|
611 | 611 | opts, arg_lst = self.parse_options(parameter_s, |
|
612 | 612 | 'nidtN:b:pD:l:rs:T:em:G', |
|
613 | 613 | mode='list', list_all=1) |
|
614 | 614 | if "m" in opts: |
|
615 | 615 | modulename = opts["m"][0] |
|
616 | 616 | modpath = find_mod(modulename) |
|
617 | 617 | if modpath is None: |
|
618 | 618 | warn('%r is not a valid modulename on sys.path'%modulename) |
|
619 | 619 | return |
|
620 | 620 | arg_lst = [modpath] + arg_lst |
|
621 | 621 | try: |
|
622 | 622 | filename = file_finder(arg_lst[0]) |
|
623 | 623 | except IndexError: |
|
624 | 624 | warn('you must provide at least a filename.') |
|
625 | 625 | print('\n%run:\n', oinspect.getdoc(self.run)) |
|
626 | 626 | return |
|
627 | 627 | except IOError as e: |
|
628 | 628 | try: |
|
629 | 629 | msg = str(e) |
|
630 | 630 | except UnicodeError: |
|
631 | 631 | msg = e.message |
|
632 | 632 | error(msg) |
|
633 | 633 | return |
|
634 | 634 | |
|
635 | 635 | if filename.lower().endswith(('.ipy', '.ipynb')): |
|
636 | 636 | with preserve_keys(self.shell.user_ns, '__file__'): |
|
637 | 637 | self.shell.user_ns['__file__'] = filename |
|
638 | 638 | self.shell.safe_execfile_ipy(filename) |
|
639 | 639 | return |
|
640 | 640 | |
|
641 | 641 | # Control the response to exit() calls made by the script being run |
|
642 | 642 | exit_ignore = 'e' in opts |
|
643 | 643 | |
|
644 | 644 | # Make sure that the running script gets a proper sys.argv as if it |
|
645 | 645 | # were run from a system shell. |
|
646 | 646 | save_argv = sys.argv # save it for later restoring |
|
647 | 647 | |
|
648 | 648 | if 'G' in opts: |
|
649 | 649 | args = arg_lst[1:] |
|
650 | 650 | else: |
|
651 | 651 | # tilde and glob expansion |
|
652 | 652 | args = shellglob(map(os.path.expanduser, arg_lst[1:])) |
|
653 | 653 | |
|
654 | 654 | sys.argv = [filename] + args # put in the proper filename |
|
655 | 655 | # protect sys.argv from potential unicode strings on Python 2: |
|
656 | 656 | if not py3compat.PY3: |
|
657 | 657 | sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ] |
|
658 | 658 | |
|
659 | 659 | if 'i' in opts: |
|
660 | 660 | # Run in user's interactive namespace |
|
661 | 661 | prog_ns = self.shell.user_ns |
|
662 | 662 | __name__save = self.shell.user_ns['__name__'] |
|
663 | 663 | prog_ns['__name__'] = '__main__' |
|
664 | 664 | main_mod = self.shell.user_module |
|
665 | 665 | |
|
666 | 666 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
667 | 667 | # set the __file__ global in the script's namespace |
|
668 | 668 | # TK: Is this necessary in interactive mode? |
|
669 | 669 | prog_ns['__file__'] = filename |
|
670 | 670 | else: |
|
671 | 671 | # Run in a fresh, empty namespace |
|
672 | 672 | if 'n' in opts: |
|
673 | 673 | name = os.path.splitext(os.path.basename(filename))[0] |
|
674 | 674 | else: |
|
675 | 675 | name = '__main__' |
|
676 | 676 | |
|
677 | 677 | # The shell MUST hold a reference to prog_ns so after %run |
|
678 | 678 | # exits, the python deletion mechanism doesn't zero it out |
|
679 | 679 | # (leaving dangling references). See interactiveshell for details |
|
680 | 680 | main_mod = self.shell.new_main_mod(filename, name) |
|
681 | 681 | prog_ns = main_mod.__dict__ |
|
682 | 682 | |
|
683 | 683 | # pickle fix. See interactiveshell for an explanation. But we need to |
|
684 | 684 | # make sure that, if we overwrite __main__, we replace it at the end |
|
685 | 685 | main_mod_name = prog_ns['__name__'] |
|
686 | 686 | |
|
687 | 687 | if main_mod_name == '__main__': |
|
688 | 688 | restore_main = sys.modules['__main__'] |
|
689 | 689 | else: |
|
690 | 690 | restore_main = False |
|
691 | 691 | |
|
692 | 692 | # This needs to be undone at the end to prevent holding references to |
|
693 | 693 | # every single object ever created. |
|
694 | 694 | sys.modules[main_mod_name] = main_mod |
|
695 | 695 | |
|
696 | 696 | if 'p' in opts or 'd' in opts: |
|
697 | 697 | if 'm' in opts: |
|
698 | 698 | code = 'run_module(modulename, prog_ns)' |
|
699 | 699 | code_ns = { |
|
700 | 700 | 'run_module': self.shell.safe_run_module, |
|
701 | 701 | 'prog_ns': prog_ns, |
|
702 | 702 | 'modulename': modulename, |
|
703 | 703 | } |
|
704 | 704 | else: |
|
705 | 705 | if 'd' in opts: |
|
706 | 706 | # allow exceptions to raise in debug mode |
|
707 | 707 | code = 'execfile(filename, prog_ns, raise_exceptions=True)' |
|
708 | 708 | else: |
|
709 | 709 | code = 'execfile(filename, prog_ns)' |
|
710 | 710 | code_ns = { |
|
711 | 711 | 'execfile': self.shell.safe_execfile, |
|
712 | 712 | 'prog_ns': prog_ns, |
|
713 | 713 | 'filename': get_py_filename(filename), |
|
714 | 714 | } |
|
715 | 715 | |
|
716 | 716 | try: |
|
717 | 717 | stats = None |
|
718 | 718 | if 'p' in opts: |
|
719 | 719 | stats = self._run_with_profiler(code, opts, code_ns) |
|
720 | 720 | else: |
|
721 | 721 | if 'd' in opts: |
|
722 | 722 | bp_file, bp_line = parse_breakpoint( |
|
723 | 723 | opts.get('b', ['1'])[0], filename) |
|
724 | 724 | self._run_with_debugger( |
|
725 | 725 | code, code_ns, filename, bp_line, bp_file) |
|
726 | 726 | else: |
|
727 | 727 | if 'm' in opts: |
|
728 | 728 | def run(): |
|
729 | 729 | self.shell.safe_run_module(modulename, prog_ns) |
|
730 | 730 | else: |
|
731 | 731 | if runner is None: |
|
732 | 732 | runner = self.default_runner |
|
733 | 733 | if runner is None: |
|
734 | 734 | runner = self.shell.safe_execfile |
|
735 | 735 | |
|
736 | 736 | def run(): |
|
737 | 737 | runner(filename, prog_ns, prog_ns, |
|
738 | 738 | exit_ignore=exit_ignore) |
|
739 | 739 | |
|
740 | 740 | if 't' in opts: |
|
741 | 741 | # timed execution |
|
742 | 742 | try: |
|
743 | 743 | nruns = int(opts['N'][0]) |
|
744 | 744 | if nruns < 1: |
|
745 | 745 | error('Number of runs must be >=1') |
|
746 | 746 | return |
|
747 | 747 | except (KeyError): |
|
748 | 748 | nruns = 1 |
|
749 | 749 | self._run_with_timing(run, nruns) |
|
750 | 750 | else: |
|
751 | 751 | # regular execution |
|
752 | 752 | run() |
|
753 | 753 | |
|
754 | 754 | if 'i' in opts: |
|
755 | 755 | self.shell.user_ns['__name__'] = __name__save |
|
756 | 756 | else: |
|
757 | 757 | # update IPython interactive namespace |
|
758 | 758 | |
|
759 | 759 | # Some forms of read errors on the file may mean the |
|
760 | 760 | # __name__ key was never set; using pop we don't have to |
|
761 | 761 | # worry about a possible KeyError. |
|
762 | 762 | prog_ns.pop('__name__', None) |
|
763 | 763 | |
|
764 | 764 | with preserve_keys(self.shell.user_ns, '__file__'): |
|
765 | 765 | self.shell.user_ns.update(prog_ns) |
|
766 | 766 | finally: |
|
767 | 767 | # It's a bit of a mystery why, but __builtins__ can change from |
|
768 | 768 | # being a module to becoming a dict missing some key data after |
|
769 | 769 | # %run. As best I can see, this is NOT something IPython is doing |
|
770 | 770 | # at all, and similar problems have been reported before: |
|
771 | 771 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html |
|
772 | 772 | # Since this seems to be done by the interpreter itself, the best |
|
773 | 773 | # we can do is to at least restore __builtins__ for the user on |
|
774 | 774 | # exit. |
|
775 | 775 | self.shell.user_ns['__builtins__'] = builtin_mod |
|
776 | 776 | |
|
777 | 777 | # Ensure key global structures are restored |
|
778 | 778 | sys.argv = save_argv |
|
779 | 779 | if restore_main: |
|
780 | 780 | sys.modules['__main__'] = restore_main |
|
781 | 781 | else: |
|
782 | 782 | # Remove from sys.modules the reference to main_mod we'd |
|
783 | 783 | # added. Otherwise it will trap references to objects |
|
784 | 784 | # contained therein. |
|
785 | 785 | del sys.modules[main_mod_name] |
|
786 | 786 | |
|
787 | 787 | return stats |
|
788 | 788 | |
|
789 | 789 | def _run_with_debugger(self, code, code_ns, filename=None, |
|
790 | 790 | bp_line=None, bp_file=None): |
|
791 | 791 | """ |
|
792 | 792 | Run `code` in debugger with a break point. |
|
793 | 793 | |
|
794 | 794 | Parameters |
|
795 | 795 | ---------- |
|
796 | 796 | code : str |
|
797 | 797 | Code to execute. |
|
798 | 798 | code_ns : dict |
|
799 | 799 | A namespace in which `code` is executed. |
|
800 | 800 | filename : str |
|
801 | 801 | `code` is ran as if it is in `filename`. |
|
802 | 802 | bp_line : int, optional |
|
803 | 803 | Line number of the break point. |
|
804 | 804 | bp_file : str, optional |
|
805 | 805 | Path to the file in which break point is specified. |
|
806 | 806 | `filename` is used if not given. |
|
807 | 807 | |
|
808 | 808 | Raises |
|
809 | 809 | ------ |
|
810 | 810 | UsageError |
|
811 | 811 | If the break point given by `bp_line` is not valid. |
|
812 | 812 | |
|
813 | 813 | """ |
|
814 | 814 | deb = self.shell.InteractiveTB.pdb |
|
815 | 815 | if not deb: |
|
816 | 816 | self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls() |
|
817 | 817 | deb = self.shell.InteractiveTB.pdb |
|
818 | 818 | |
|
819 | 819 | # deb.checkline() fails if deb.curframe exists but is None; it can |
|
820 | 820 | # handle it not existing. https://github.com/ipython/ipython/issues/10028 |
|
821 | 821 | if hasattr(deb, 'curframe'): |
|
822 | 822 | del deb.curframe |
|
823 | 823 | |
|
824 | 824 | # reset Breakpoint state, which is moronically kept |
|
825 | 825 | # in a class |
|
826 | 826 | bdb.Breakpoint.next = 1 |
|
827 | 827 | bdb.Breakpoint.bplist = {} |
|
828 | 828 | bdb.Breakpoint.bpbynumber = [None] |
|
829 | 829 | if bp_line is not None: |
|
830 | 830 | # Set an initial breakpoint to stop execution |
|
831 | 831 | maxtries = 10 |
|
832 | 832 | bp_file = bp_file or filename |
|
833 | 833 | checkline = deb.checkline(bp_file, bp_line) |
|
834 | 834 | if not checkline: |
|
835 | 835 | for bp in range(bp_line + 1, bp_line + maxtries + 1): |
|
836 | 836 | if deb.checkline(bp_file, bp): |
|
837 | 837 | break |
|
838 | 838 | else: |
|
839 | 839 | msg = ("\nI failed to find a valid line to set " |
|
840 | 840 | "a breakpoint\n" |
|
841 | 841 | "after trying up to line: %s.\n" |
|
842 | 842 | "Please set a valid breakpoint manually " |
|
843 | 843 | "with the -b option." % bp) |
|
844 | 844 | raise UsageError(msg) |
|
845 | 845 | # if we find a good linenumber, set the breakpoint |
|
846 | 846 | deb.do_break('%s:%s' % (bp_file, bp_line)) |
|
847 | 847 | |
|
848 | 848 | if filename: |
|
849 | 849 | # Mimic Pdb._runscript(...) |
|
850 | 850 | deb._wait_for_mainpyfile = True |
|
851 | 851 | deb.mainpyfile = deb.canonic(filename) |
|
852 | 852 | |
|
853 | 853 | # Start file run |
|
854 | 854 | print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt) |
|
855 | 855 | try: |
|
856 | 856 | if filename: |
|
857 | 857 | # save filename so it can be used by methods on the deb object |
|
858 | 858 | deb._exec_filename = filename |
|
859 | 859 | while True: |
|
860 | 860 | try: |
|
861 | 861 | deb.run(code, code_ns) |
|
862 | 862 | except Restart: |
|
863 | 863 | print("Restarting") |
|
864 | 864 | if filename: |
|
865 | 865 | deb._wait_for_mainpyfile = True |
|
866 | 866 | deb.mainpyfile = deb.canonic(filename) |
|
867 | 867 | continue |
|
868 | 868 | else: |
|
869 | 869 | break |
|
870 | 870 | |
|
871 | 871 | |
|
872 | 872 | except: |
|
873 | 873 | etype, value, tb = sys.exc_info() |
|
874 | 874 | # Skip three frames in the traceback: the %run one, |
|
875 | 875 | # one inside bdb.py, and the command-line typed by the |
|
876 | 876 | # user (run by exec in pdb itself). |
|
877 | 877 | self.shell.InteractiveTB(etype, value, tb, tb_offset=3) |
|
878 | 878 | |
|
879 | 879 | @staticmethod |
|
880 | 880 | def _run_with_timing(run, nruns): |
|
881 | 881 | """ |
|
882 | 882 | Run function `run` and print timing information. |
|
883 | 883 | |
|
884 | 884 | Parameters |
|
885 | 885 | ---------- |
|
886 | 886 | run : callable |
|
887 | 887 | Any callable object which takes no argument. |
|
888 | 888 | nruns : int |
|
889 | 889 | Number of times to execute `run`. |
|
890 | 890 | |
|
891 | 891 | """ |
|
892 | 892 | twall0 = time.time() |
|
893 | 893 | if nruns == 1: |
|
894 | 894 | t0 = clock2() |
|
895 | 895 | run() |
|
896 | 896 | t1 = clock2() |
|
897 | 897 | t_usr = t1[0] - t0[0] |
|
898 | 898 | t_sys = t1[1] - t0[1] |
|
899 | 899 | print("\nIPython CPU timings (estimated):") |
|
900 | 900 | print(" User : %10.2f s." % t_usr) |
|
901 | 901 | print(" System : %10.2f s." % t_sys) |
|
902 | 902 | else: |
|
903 | 903 | runs = range(nruns) |
|
904 | 904 | t0 = clock2() |
|
905 | 905 | for nr in runs: |
|
906 | 906 | run() |
|
907 | 907 | t1 = clock2() |
|
908 | 908 | t_usr = t1[0] - t0[0] |
|
909 | 909 | t_sys = t1[1] - t0[1] |
|
910 | 910 | print("\nIPython CPU timings (estimated):") |
|
911 | 911 | print("Total runs performed:", nruns) |
|
912 | 912 | print(" Times : %10s %10s" % ('Total', 'Per run')) |
|
913 | 913 | print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)) |
|
914 | 914 | print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)) |
|
915 | 915 | twall1 = time.time() |
|
916 | 916 | print("Wall time: %10.2f s." % (twall1 - twall0)) |
|
917 | 917 | |
|
918 | 918 | @skip_doctest |
|
919 | 919 | @line_cell_magic |
|
920 | 920 | def timeit(self, line='', cell=None): |
|
921 | 921 | """Time execution of a Python statement or expression |
|
922 | 922 | |
|
923 | 923 | Usage, in line mode: |
|
924 | 924 | %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement |
|
925 | 925 | or in cell mode: |
|
926 | 926 | %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code |
|
927 | 927 | code |
|
928 | 928 | code... |
|
929 | 929 | |
|
930 | 930 | Time execution of a Python statement or expression using the timeit |
|
931 | 931 | module. This function can be used both as a line and cell magic: |
|
932 | 932 | |
|
933 | 933 | - In line mode you can time a single-line statement (though multiple |
|
934 | 934 | ones can be chained with using semicolons). |
|
935 | 935 | |
|
936 | 936 | - In cell mode, the statement in the first line is used as setup code |
|
937 | 937 | (executed but not timed) and the body of the cell is timed. The cell |
|
938 | 938 | body has access to any variables created in the setup code. |
|
939 | 939 | |
|
940 | 940 | Options: |
|
941 | 941 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
942 | 942 | is not given, a fitting value is chosen. |
|
943 | 943 | |
|
944 | 944 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
945 | 945 | Default: 3 |
|
946 | 946 | |
|
947 | 947 | -t: use time.time to measure the time, which is the default on Unix. |
|
948 | 948 | This function measures wall time. |
|
949 | 949 | |
|
950 | 950 | -c: use time.clock to measure the time, which is the default on |
|
951 | 951 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
952 | 952 | instead and returns the CPU user time. |
|
953 | 953 | |
|
954 | 954 | -p<P>: use a precision of <P> digits to display the timing result. |
|
955 | 955 | Default: 3 |
|
956 | 956 | |
|
957 | 957 | -q: Quiet, do not print result. |
|
958 | 958 | |
|
959 | 959 | -o: return a TimeitResult that can be stored in a variable to inspect |
|
960 | 960 | the result in more details. |
|
961 | 961 | |
|
962 | 962 | |
|
963 | 963 | Examples |
|
964 | 964 | -------- |
|
965 | 965 | :: |
|
966 | 966 | |
|
967 | 967 | In [1]: %timeit pass |
|
968 | 968 | 100000000 loops, average of 7: 5.48 ns +- 0.354 ns per loop (using standard deviation) |
|
969 | 969 | |
|
970 | 970 | In [2]: u = None |
|
971 | 971 | |
|
972 | 972 | In [3]: %timeit u is None |
|
973 | 973 | 10000000 loops, average of 7: 22.7 ns +- 2.33 ns per loop (using standard deviation) |
|
974 | 974 | |
|
975 | 975 | In [4]: %timeit -r 4 u == None |
|
976 | 976 | 10000000 loops, average of 4: 27.5 ns +- 2.91 ns per loop (using standard deviation) |
|
977 | 977 | |
|
978 | 978 | In [5]: import time |
|
979 | 979 | |
|
980 | 980 | In [6]: %timeit -n1 time.sleep(2) |
|
981 | 981 | 1 loop, average of 7: 2 s +- 4.71 µs per loop (using standard deviation) |
|
982 | 982 | |
|
983 | 983 | |
|
984 | 984 | The times reported by %timeit will be slightly higher than those |
|
985 | 985 | reported by the timeit.py script when variables are accessed. This is |
|
986 | 986 | due to the fact that %timeit executes the statement in the namespace |
|
987 | 987 | of the shell, compared with timeit.py, which uses a single setup |
|
988 | 988 | statement to import function or create variables. Generally, the bias |
|
989 | 989 | does not matter as long as results from timeit.py are not mixed with |
|
990 | 990 | those from %timeit.""" |
|
991 | 991 | |
|
992 | 992 | opts, stmt = self.parse_options(line,'n:r:tcp:qo', |
|
993 | 993 | posix=False, strict=False) |
|
994 | 994 | if stmt == "" and cell is None: |
|
995 | 995 | return |
|
996 | 996 | |
|
997 | 997 | timefunc = timeit.default_timer |
|
998 | 998 | number = int(getattr(opts, "n", 0)) |
|
999 | 999 | default_repeat = 7 if timeit.default_repeat < 7 else timeit.default_repeat |
|
1000 | 1000 | repeat = int(getattr(opts, "r", default_repeat)) |
|
1001 | 1001 | precision = int(getattr(opts, "p", 3)) |
|
1002 | 1002 | quiet = 'q' in opts |
|
1003 | 1003 | return_result = 'o' in opts |
|
1004 | 1004 | if hasattr(opts, "t"): |
|
1005 | 1005 | timefunc = time.time |
|
1006 | 1006 | if hasattr(opts, "c"): |
|
1007 | 1007 | timefunc = clock |
|
1008 | 1008 | |
|
1009 | 1009 | timer = Timer(timer=timefunc) |
|
1010 | 1010 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1011 | 1011 | # but is there a better way to achieve that the code stmt has access |
|
1012 | 1012 | # to the shell namespace? |
|
1013 | 1013 | transform = self.shell.input_splitter.transform_cell |
|
1014 | 1014 | |
|
1015 | 1015 | if cell is None: |
|
1016 | 1016 | # called as line magic |
|
1017 | 1017 | ast_setup = self.shell.compile.ast_parse("pass") |
|
1018 | 1018 | ast_stmt = self.shell.compile.ast_parse(transform(stmt)) |
|
1019 | 1019 | else: |
|
1020 | 1020 | ast_setup = self.shell.compile.ast_parse(transform(stmt)) |
|
1021 | 1021 | ast_stmt = self.shell.compile.ast_parse(transform(cell)) |
|
1022 | 1022 | |
|
1023 | 1023 | ast_setup = self.shell.transform_ast(ast_setup) |
|
1024 | 1024 | ast_stmt = self.shell.transform_ast(ast_stmt) |
|
1025 | 1025 | |
|
1026 | 1026 | # This codestring is taken from timeit.template - we fill it in as an |
|
1027 | 1027 | # AST, so that we can apply our AST transformations to the user code |
|
1028 | 1028 | # without affecting the timing code. |
|
1029 | 1029 | timeit_ast_template = ast.parse('def inner(_it, _timer):\n' |
|
1030 | 1030 | ' setup\n' |
|
1031 | 1031 | ' _t0 = _timer()\n' |
|
1032 | 1032 | ' for _i in _it:\n' |
|
1033 | 1033 | ' stmt\n' |
|
1034 | 1034 | ' _t1 = _timer()\n' |
|
1035 | 1035 | ' return _t1 - _t0\n') |
|
1036 | 1036 | |
|
1037 | 1037 | timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template) |
|
1038 | 1038 | timeit_ast = ast.fix_missing_locations(timeit_ast) |
|
1039 | 1039 | |
|
1040 | 1040 | # Track compilation time so it can be reported if too long |
|
1041 | 1041 | # Minimum time above which compilation time will be reported |
|
1042 | 1042 | tc_min = 0.1 |
|
1043 | 1043 | |
|
1044 | 1044 | t0 = clock() |
|
1045 | 1045 | code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec") |
|
1046 | 1046 | tc = clock()-t0 |
|
1047 | 1047 | |
|
1048 | 1048 | ns = {} |
|
1049 | 1049 | exec(code, self.shell.user_ns, ns) |
|
1050 | 1050 | timer.inner = ns["inner"] |
|
1051 | 1051 | |
|
1052 | 1052 | # This is used to check if there is a huge difference between the |
|
1053 | 1053 | # best and worst timings. |
|
1054 | 1054 | # Issue: https://github.com/ipython/ipython/issues/6471 |
|
1055 | 1055 | if number == 0: |
|
1056 | 1056 | # determine number so that 0.2 <= total time < 2.0 |
|
1057 | 1057 | for index in range(0, 10): |
|
1058 | 1058 | number = 10 ** index |
|
1059 | 1059 | time_number = timer.timeit(number) |
|
1060 | 1060 | if time_number >= 0.2: |
|
1061 | 1061 | break |
|
1062 | 1062 | |
|
1063 | 1063 | all_runs = timer.repeat(repeat, number) |
|
1064 | 1064 | best = min(all_runs) / number |
|
1065 | 1065 | worst = max(all_runs) / number |
|
1066 | 1066 | timeit_result = TimeitResult(number, repeat, best, worst, all_runs, tc, precision) |
|
1067 | 1067 | |
|
1068 | 1068 | if not quiet : |
|
1069 | 1069 | # Check best timing is greater than zero to avoid a |
|
1070 | 1070 | # ZeroDivisionError. |
|
1071 | 1071 | # In cases where the slowest timing is lesser than a micosecond |
|
1072 | 1072 | # we assume that it does not really matter if the fastest |
|
1073 | 1073 | # timing is 4 times faster than the slowest timing or not. |
|
1074 | 1074 | if worst > 4 * best and best > 0 and worst > 1e-6: |
|
1075 | 1075 | print("The slowest run took %0.2f times longer than the " |
|
1076 | 1076 | "fastest. This could mean that an intermediate result " |
|
1077 | 1077 | "is being cached." % (worst / best)) |
|
1078 | 1078 | |
|
1079 | 1079 | print( timeit_result ) |
|
1080 | 1080 | |
|
1081 | 1081 | if tc > tc_min: |
|
1082 | 1082 | print("Compiler time: %.2f s" % tc) |
|
1083 | 1083 | if return_result: |
|
1084 | 1084 | return timeit_result |
|
1085 | 1085 | |
|
1086 | 1086 | @skip_doctest |
|
1087 | 1087 | @needs_local_scope |
|
1088 | 1088 | @line_cell_magic |
|
1089 | 1089 | def time(self,line='', cell=None, local_ns=None): |
|
1090 | 1090 | """Time execution of a Python statement or expression. |
|
1091 | 1091 | |
|
1092 | 1092 | The CPU and wall clock times are printed, and the value of the |
|
1093 | 1093 | expression (if any) is returned. Note that under Win32, system time |
|
1094 | 1094 | is always reported as 0, since it can not be measured. |
|
1095 | 1095 | |
|
1096 | 1096 | This function can be used both as a line and cell magic: |
|
1097 | 1097 | |
|
1098 | 1098 | - In line mode you can time a single-line statement (though multiple |
|
1099 | 1099 | ones can be chained with using semicolons). |
|
1100 | 1100 | |
|
1101 | 1101 | - In cell mode, you can time the cell body (a directly |
|
1102 | 1102 | following statement raises an error). |
|
1103 | 1103 | |
|
1104 | 1104 | This function provides very basic timing functionality. Use the timeit |
|
1105 | 1105 | magic for more control over the measurement. |
|
1106 | 1106 | |
|
1107 | 1107 | Examples |
|
1108 | 1108 | -------- |
|
1109 | 1109 | :: |
|
1110 | 1110 | |
|
1111 | 1111 | In [1]: %time 2**128 |
|
1112 | 1112 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1113 | 1113 | Wall time: 0.00 |
|
1114 | 1114 | Out[1]: 340282366920938463463374607431768211456L |
|
1115 | 1115 | |
|
1116 | 1116 | In [2]: n = 1000000 |
|
1117 | 1117 | |
|
1118 | 1118 | In [3]: %time sum(range(n)) |
|
1119 | 1119 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1120 | 1120 | Wall time: 1.37 |
|
1121 | 1121 | Out[3]: 499999500000L |
|
1122 | 1122 | |
|
1123 | 1123 | In [4]: %time print 'hello world' |
|
1124 | 1124 | hello world |
|
1125 | 1125 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1126 | 1126 | Wall time: 0.00 |
|
1127 | 1127 | |
|
1128 | 1128 | Note that the time needed by Python to compile the given expression |
|
1129 | 1129 | will be reported if it is more than 0.1s. In this example, the |
|
1130 | 1130 | actual exponentiation is done by Python at compilation time, so while |
|
1131 | 1131 | the expression can take a noticeable amount of time to compute, that |
|
1132 | 1132 | time is purely due to the compilation: |
|
1133 | 1133 | |
|
1134 | 1134 | In [5]: %time 3**9999; |
|
1135 | 1135 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1136 | 1136 | Wall time: 0.00 s |
|
1137 | 1137 | |
|
1138 | 1138 | In [6]: %time 3**999999; |
|
1139 | 1139 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1140 | 1140 | Wall time: 0.00 s |
|
1141 | 1141 | Compiler : 0.78 s |
|
1142 | 1142 | """ |
|
1143 | 1143 | |
|
1144 | 1144 | # fail immediately if the given expression can't be compiled |
|
1145 | 1145 | |
|
1146 | 1146 | if line and cell: |
|
1147 | 1147 | raise UsageError("Can't use statement directly after '%%time'!") |
|
1148 | 1148 | |
|
1149 | 1149 | if cell: |
|
1150 | 1150 | expr = self.shell.input_transformer_manager.transform_cell(cell) |
|
1151 | 1151 | else: |
|
1152 | 1152 | expr = self.shell.input_transformer_manager.transform_cell(line) |
|
1153 | 1153 | |
|
1154 | 1154 | # Minimum time above which parse time will be reported |
|
1155 | 1155 | tp_min = 0.1 |
|
1156 | 1156 | |
|
1157 | 1157 | t0 = clock() |
|
1158 | 1158 | expr_ast = self.shell.compile.ast_parse(expr) |
|
1159 | 1159 | tp = clock()-t0 |
|
1160 | 1160 | |
|
1161 | 1161 | # Apply AST transformations |
|
1162 | 1162 | expr_ast = self.shell.transform_ast(expr_ast) |
|
1163 | 1163 | |
|
1164 | 1164 | # Minimum time above which compilation time will be reported |
|
1165 | 1165 | tc_min = 0.1 |
|
1166 | 1166 | |
|
1167 | 1167 | if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr): |
|
1168 | 1168 | mode = 'eval' |
|
1169 | 1169 | source = '<timed eval>' |
|
1170 | 1170 | expr_ast = ast.Expression(expr_ast.body[0].value) |
|
1171 | 1171 | else: |
|
1172 | 1172 | mode = 'exec' |
|
1173 | 1173 | source = '<timed exec>' |
|
1174 | 1174 | t0 = clock() |
|
1175 | 1175 | code = self.shell.compile(expr_ast, source, mode) |
|
1176 | 1176 | tc = clock()-t0 |
|
1177 | 1177 | |
|
1178 | 1178 | # skew measurement as little as possible |
|
1179 | 1179 | glob = self.shell.user_ns |
|
1180 | 1180 | wtime = time.time |
|
1181 | 1181 | # time execution |
|
1182 | 1182 | wall_st = wtime() |
|
1183 | 1183 | if mode=='eval': |
|
1184 | 1184 | st = clock2() |
|
1185 | 1185 | try: |
|
1186 | 1186 | out = eval(code, glob, local_ns) |
|
1187 | 1187 | except: |
|
1188 | 1188 | self.shell.showtraceback() |
|
1189 | 1189 | return |
|
1190 | 1190 | end = clock2() |
|
1191 | 1191 | else: |
|
1192 | 1192 | st = clock2() |
|
1193 | 1193 | try: |
|
1194 | 1194 | exec(code, glob, local_ns) |
|
1195 | 1195 | except: |
|
1196 | 1196 | self.shell.showtraceback() |
|
1197 | 1197 | return |
|
1198 | 1198 | end = clock2() |
|
1199 | 1199 | out = None |
|
1200 | 1200 | wall_end = wtime() |
|
1201 | 1201 | # Compute actual times and report |
|
1202 | 1202 | wall_time = wall_end-wall_st |
|
1203 | 1203 | cpu_user = end[0]-st[0] |
|
1204 | 1204 | cpu_sys = end[1]-st[1] |
|
1205 | 1205 | cpu_tot = cpu_user+cpu_sys |
|
1206 | 1206 | # On windows cpu_sys is always zero, so no new information to the next print |
|
1207 | 1207 | if sys.platform != 'win32': |
|
1208 | 1208 | print("CPU times: user %s, sys: %s, total: %s" % \ |
|
1209 | 1209 | (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot))) |
|
1210 | 1210 | print("Wall time: %s" % _format_time(wall_time)) |
|
1211 | 1211 | if tc > tc_min: |
|
1212 | 1212 | print("Compiler : %s" % _format_time(tc)) |
|
1213 | 1213 | if tp > tp_min: |
|
1214 | 1214 | print("Parser : %s" % _format_time(tp)) |
|
1215 | 1215 | return out |
|
1216 | 1216 | |
|
1217 | 1217 | @skip_doctest |
|
1218 | 1218 | @line_magic |
|
1219 | 1219 | def macro(self, parameter_s=''): |
|
1220 | 1220 | """Define a macro for future re-execution. It accepts ranges of history, |
|
1221 | 1221 | filenames or string objects. |
|
1222 | 1222 | |
|
1223 | 1223 | Usage:\\ |
|
1224 | 1224 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1225 | 1225 | |
|
1226 | 1226 | Options: |
|
1227 | 1227 | |
|
1228 | 1228 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1229 | 1229 | so that magics are loaded in their transformed version to valid |
|
1230 | 1230 | Python. If this option is given, the raw input as typed at the |
|
1231 | 1231 | command line is used instead. |
|
1232 | 1232 | |
|
1233 | 1233 | -q: quiet macro definition. By default, a tag line is printed |
|
1234 | 1234 | to indicate the macro has been created, and then the contents of |
|
1235 | 1235 | the macro are printed. If this option is given, then no printout |
|
1236 | 1236 | is produced once the macro is created. |
|
1237 | 1237 | |
|
1238 | 1238 | This will define a global variable called `name` which is a string |
|
1239 | 1239 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1240 | 1240 | above) from your input history into a single string. This variable |
|
1241 | 1241 | acts like an automatic function which re-executes those lines as if |
|
1242 | 1242 | you had typed them. You just type 'name' at the prompt and the code |
|
1243 | 1243 | executes. |
|
1244 | 1244 | |
|
1245 | 1245 | The syntax for indicating input ranges is described in %history. |
|
1246 | 1246 | |
|
1247 | 1247 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
1248 | 1248 | notation, where N:M means numbers N through M-1. |
|
1249 | 1249 | |
|
1250 | 1250 | For example, if your history contains (print using %hist -n ):: |
|
1251 | 1251 | |
|
1252 | 1252 | 44: x=1 |
|
1253 | 1253 | 45: y=3 |
|
1254 | 1254 | 46: z=x+y |
|
1255 | 1255 | 47: print x |
|
1256 | 1256 | 48: a=5 |
|
1257 | 1257 | 49: print 'x',x,'y',y |
|
1258 | 1258 | |
|
1259 | 1259 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
1260 | 1260 | called my_macro with:: |
|
1261 | 1261 | |
|
1262 | 1262 | In [55]: %macro my_macro 44-47 49 |
|
1263 | 1263 | |
|
1264 | 1264 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
1265 | 1265 | in one pass. |
|
1266 | 1266 | |
|
1267 | 1267 | You don't need to give the line-numbers in order, and any given line |
|
1268 | 1268 | number can appear multiple times. You can assemble macros with any |
|
1269 | 1269 | lines from your input history in any order. |
|
1270 | 1270 | |
|
1271 | 1271 | The macro is a simple object which holds its value in an attribute, |
|
1272 | 1272 | but IPython's display system checks for macros and executes them as |
|
1273 | 1273 | code instead of printing them when you type their name. |
|
1274 | 1274 | |
|
1275 | 1275 | You can view a macro's contents by explicitly printing it with:: |
|
1276 | 1276 | |
|
1277 | 1277 | print macro_name |
|
1278 | 1278 | |
|
1279 | 1279 | """ |
|
1280 | 1280 | opts,args = self.parse_options(parameter_s,'rq',mode='list') |
|
1281 | 1281 | if not args: # List existing macros |
|
1282 |
return sorted(k for k,v in |
|
|
1283 | isinstance(v, Macro)) | |
|
1282 | return sorted(k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)) | |
|
1284 | 1283 | if len(args) == 1: |
|
1285 | 1284 | raise UsageError( |
|
1286 | 1285 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
1287 | 1286 | name, codefrom = args[0], " ".join(args[1:]) |
|
1288 | 1287 | |
|
1289 | 1288 | #print 'rng',ranges # dbg |
|
1290 | 1289 | try: |
|
1291 | 1290 | lines = self.shell.find_user_code(codefrom, 'r' in opts) |
|
1292 | 1291 | except (ValueError, TypeError) as e: |
|
1293 | 1292 | print(e.args[0]) |
|
1294 | 1293 | return |
|
1295 | 1294 | macro = Macro(lines) |
|
1296 | 1295 | self.shell.define_macro(name, macro) |
|
1297 | 1296 | if not ( 'q' in opts) : |
|
1298 | 1297 | print('Macro `%s` created. To execute, type its name (without quotes).' % name) |
|
1299 | 1298 | print('=== Macro contents: ===') |
|
1300 | 1299 | print(macro, end=' ') |
|
1301 | 1300 | |
|
1302 | 1301 | @magic_arguments.magic_arguments() |
|
1303 | 1302 | @magic_arguments.argument('output', type=str, default='', nargs='?', |
|
1304 | 1303 | help="""The name of the variable in which to store output. |
|
1305 | 1304 | This is a utils.io.CapturedIO object with stdout/err attributes |
|
1306 | 1305 | for the text of the captured output. |
|
1307 | 1306 | |
|
1308 | 1307 | CapturedOutput also has a show() method for displaying the output, |
|
1309 | 1308 | and __call__ as well, so you can use that to quickly display the |
|
1310 | 1309 | output. |
|
1311 | 1310 | |
|
1312 | 1311 | If unspecified, captured output is discarded. |
|
1313 | 1312 | """ |
|
1314 | 1313 | ) |
|
1315 | 1314 | @magic_arguments.argument('--no-stderr', action="store_true", |
|
1316 | 1315 | help="""Don't capture stderr.""" |
|
1317 | 1316 | ) |
|
1318 | 1317 | @magic_arguments.argument('--no-stdout', action="store_true", |
|
1319 | 1318 | help="""Don't capture stdout.""" |
|
1320 | 1319 | ) |
|
1321 | 1320 | @magic_arguments.argument('--no-display', action="store_true", |
|
1322 | 1321 | help="""Don't capture IPython's rich display.""" |
|
1323 | 1322 | ) |
|
1324 | 1323 | @cell_magic |
|
1325 | 1324 | def capture(self, line, cell): |
|
1326 | 1325 | """run the cell, capturing stdout, stderr, and IPython's rich display() calls.""" |
|
1327 | 1326 | args = magic_arguments.parse_argstring(self.capture, line) |
|
1328 | 1327 | out = not args.no_stdout |
|
1329 | 1328 | err = not args.no_stderr |
|
1330 | 1329 | disp = not args.no_display |
|
1331 | 1330 | with capture_output(out, err, disp) as io: |
|
1332 | 1331 | self.shell.run_cell(cell) |
|
1333 | 1332 | if args.output: |
|
1334 | 1333 | self.shell.user_ns[args.output] = io |
|
1335 | 1334 | |
|
1336 | 1335 | def parse_breakpoint(text, current_file): |
|
1337 | 1336 | '''Returns (file, line) for file:line and (current_file, line) for line''' |
|
1338 | 1337 | colon = text.find(':') |
|
1339 | 1338 | if colon == -1: |
|
1340 | 1339 | return current_file, int(text) |
|
1341 | 1340 | else: |
|
1342 | 1341 | return text[:colon], int(text[colon+1:]) |
|
1343 | 1342 | |
|
1344 | 1343 | def _format_time(timespan, precision=3): |
|
1345 | 1344 | """Formats the timespan in a human readable form""" |
|
1346 | 1345 | |
|
1347 | 1346 | if timespan >= 60.0: |
|
1348 | 1347 | # we have more than a minute, format that in a human readable form |
|
1349 | 1348 | # Idea from http://snipplr.com/view/5713/ |
|
1350 | 1349 | parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)] |
|
1351 | 1350 | time = [] |
|
1352 | 1351 | leftover = timespan |
|
1353 | 1352 | for suffix, length in parts: |
|
1354 | 1353 | value = int(leftover / length) |
|
1355 | 1354 | if value > 0: |
|
1356 | 1355 | leftover = leftover % length |
|
1357 | 1356 | time.append(u'%s%s' % (str(value), suffix)) |
|
1358 | 1357 | if leftover < 1: |
|
1359 | 1358 | break |
|
1360 | 1359 | return " ".join(time) |
|
1361 | 1360 | |
|
1362 | 1361 | |
|
1363 | 1362 | # Unfortunately the unicode 'micro' symbol can cause problems in |
|
1364 | 1363 | # certain terminals. |
|
1365 | 1364 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 |
|
1366 | 1365 | # Try to prevent crashes by being more secure than it needs to |
|
1367 | 1366 | # E.g. eclipse is able to print a µ, but has no sys.stdout.encoding set. |
|
1368 | 1367 | units = [u"s", u"ms",u'us',"ns"] # the save value |
|
1369 | 1368 | if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding: |
|
1370 | 1369 | try: |
|
1371 | 1370 | u'\xb5'.encode(sys.stdout.encoding) |
|
1372 | 1371 | units = [u"s", u"ms",u'\xb5s',"ns"] |
|
1373 | 1372 | except: |
|
1374 | 1373 | pass |
|
1375 | 1374 | scaling = [1, 1e3, 1e6, 1e9] |
|
1376 | 1375 | |
|
1377 | 1376 | if timespan > 0.0: |
|
1378 | 1377 | order = min(-int(math.floor(math.log10(timespan)) // 3), 3) |
|
1379 | 1378 | else: |
|
1380 | 1379 | order = 3 |
|
1381 | 1380 | return u"%.*g %s" % (precision, timespan * scaling[order], units[order]) |
@@ -1,184 +1,183 b'' | |||
|
1 | 1 | """Implementation of magic functions for IPython's own logging. |
|
2 | 2 | """ |
|
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 os |
|
17 | 17 | import sys |
|
18 | 18 | |
|
19 | 19 | # Our own packages |
|
20 | 20 | from IPython.core.magic import Magics, magics_class, line_magic |
|
21 | 21 | from warnings import warn |
|
22 | from IPython.utils.py3compat import str_to_unicode | |
|
23 | 22 | |
|
24 | 23 | #----------------------------------------------------------------------------- |
|
25 | 24 | # Magic implementation classes |
|
26 | 25 | #----------------------------------------------------------------------------- |
|
27 | 26 | |
|
28 | 27 | @magics_class |
|
29 | 28 | class LoggingMagics(Magics): |
|
30 | 29 | """Magics related to all logging machinery.""" |
|
31 | 30 | |
|
32 | 31 | @line_magic |
|
33 | 32 | def logstart(self, parameter_s=''): |
|
34 | 33 | """Start logging anywhere in a session. |
|
35 | 34 | |
|
36 | 35 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
37 | 36 | |
|
38 | 37 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
39 | 38 | current directory, in 'rotate' mode (see below). |
|
40 | 39 | |
|
41 | 40 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
42 | 41 | history up to that point and then continues logging. |
|
43 | 42 | |
|
44 | 43 | %logstart takes a second optional parameter: logging mode. This can be one |
|
45 | 44 | of (note that the modes are given unquoted): |
|
46 | 45 | |
|
47 | 46 | append |
|
48 | 47 | Keep logging at the end of any existing file. |
|
49 | 48 | |
|
50 | 49 | backup |
|
51 | 50 | Rename any existing file to name~ and start name. |
|
52 | 51 | |
|
53 | 52 | global |
|
54 | 53 | Append to a single logfile in your home directory. |
|
55 | 54 | |
|
56 | 55 | over |
|
57 | 56 | Overwrite any existing log. |
|
58 | 57 | |
|
59 | 58 | rotate |
|
60 | 59 | Create rotating logs: name.1~, name.2~, etc. |
|
61 | 60 | |
|
62 | 61 | Options: |
|
63 | 62 | |
|
64 | 63 | -o |
|
65 | 64 | log also IPython's output. In this mode, all commands which |
|
66 | 65 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
67 | 66 | their corresponding input line. The output lines are always |
|
68 | 67 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
69 | 68 | Python code. |
|
70 | 69 | |
|
71 | 70 | Since this marker is always the same, filtering only the output from |
|
72 | 71 | a log is very easy, using for example a simple awk call:: |
|
73 | 72 | |
|
74 | 73 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
75 | 74 | |
|
76 | 75 | -r |
|
77 | 76 | log 'raw' input. Normally, IPython's logs contain the processed |
|
78 | 77 | input, so that user lines are logged in their final form, converted |
|
79 | 78 | into valid Python. For example, %Exit is logged as |
|
80 | 79 | _ip.magic("Exit"). If the -r flag is given, all input is logged |
|
81 | 80 | exactly as typed, with no transformations applied. |
|
82 | 81 | |
|
83 | 82 | -t |
|
84 | 83 | put timestamps before each input line logged (these are put in |
|
85 | 84 | comments). |
|
86 | 85 | """ |
|
87 | 86 | |
|
88 | 87 | opts,par = self.parse_options(parameter_s,'ort') |
|
89 | 88 | log_output = 'o' in opts |
|
90 | 89 | log_raw_input = 'r' in opts |
|
91 | 90 | timestamp = 't' in opts |
|
92 | 91 | |
|
93 | 92 | logger = self.shell.logger |
|
94 | 93 | |
|
95 | 94 | # if no args are given, the defaults set in the logger constructor by |
|
96 | 95 | # ipython remain valid |
|
97 | 96 | if par: |
|
98 | 97 | try: |
|
99 | 98 | logfname,logmode = par.split() |
|
100 | 99 | except: |
|
101 | 100 | logfname = par |
|
102 | 101 | logmode = 'backup' |
|
103 | 102 | else: |
|
104 | 103 | logfname = logger.logfname |
|
105 | 104 | logmode = logger.logmode |
|
106 | 105 | # put logfname into rc struct as if it had been called on the command |
|
107 | 106 | # line, so it ends up saved in the log header Save it in case we need |
|
108 | 107 | # to restore it... |
|
109 | 108 | old_logfile = self.shell.logfile |
|
110 | 109 | if logfname: |
|
111 | 110 | logfname = os.path.expanduser(logfname) |
|
112 | 111 | self.shell.logfile = logfname |
|
113 | 112 | |
|
114 | 113 | loghead = u'# IPython log file\n\n' |
|
115 | 114 | try: |
|
116 | 115 | logger.logstart(logfname, loghead, logmode, log_output, timestamp, |
|
117 | 116 | log_raw_input) |
|
118 | 117 | except: |
|
119 | 118 | self.shell.logfile = old_logfile |
|
120 | 119 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
121 | 120 | else: |
|
122 | 121 | # log input history up to this point, optionally interleaving |
|
123 | 122 | # output if requested |
|
124 | 123 | |
|
125 | 124 | if timestamp: |
|
126 | 125 | # disable timestamping for the previous history, since we've |
|
127 | 126 | # lost those already (no time machine here). |
|
128 | 127 | logger.timestamp = False |
|
129 | 128 | |
|
130 | 129 | if log_raw_input: |
|
131 | 130 | input_hist = self.shell.history_manager.input_hist_raw |
|
132 | 131 | else: |
|
133 | 132 | input_hist = self.shell.history_manager.input_hist_parsed |
|
134 | 133 | |
|
135 | 134 | if log_output: |
|
136 | 135 | log_write = logger.log_write |
|
137 | 136 | output_hist = self.shell.history_manager.output_hist |
|
138 | 137 | for n in range(1,len(input_hist)-1): |
|
139 | 138 | log_write(input_hist[n].rstrip() + u'\n') |
|
140 | 139 | if n in output_hist: |
|
141 |
log_write |
|
|
140 | log_write(repr(output_hist[n]),'output') | |
|
142 | 141 | else: |
|
143 | 142 | logger.log_write(u'\n'.join(input_hist[1:])) |
|
144 | 143 | logger.log_write(u'\n') |
|
145 | 144 | if timestamp: |
|
146 | 145 | # re-enable timestamping |
|
147 | 146 | logger.timestamp = True |
|
148 | 147 | |
|
149 | 148 | print ('Activating auto-logging. ' |
|
150 | 149 | 'Current session state plus future input saved.') |
|
151 | 150 | logger.logstate() |
|
152 | 151 | |
|
153 | 152 | @line_magic |
|
154 | 153 | def logstop(self, parameter_s=''): |
|
155 | 154 | """Fully stop logging and close log file. |
|
156 | 155 | |
|
157 | 156 | In order to start logging again, a new %logstart call needs to be made, |
|
158 | 157 | possibly (though not necessarily) with a new filename, mode and other |
|
159 | 158 | options.""" |
|
160 | 159 | self.shell.logger.logstop() |
|
161 | 160 | |
|
162 | 161 | @line_magic |
|
163 | 162 | def logoff(self, parameter_s=''): |
|
164 | 163 | """Temporarily stop logging. |
|
165 | 164 | |
|
166 | 165 | You must have previously started logging.""" |
|
167 | 166 | self.shell.logger.switch_log(0) |
|
168 | 167 | |
|
169 | 168 | @line_magic |
|
170 | 169 | def logon(self, parameter_s=''): |
|
171 | 170 | """Restart logging. |
|
172 | 171 | |
|
173 | 172 | This function is for restarting logging which you've temporarily |
|
174 | 173 | stopped with %logoff. For starting logging for the first time, you |
|
175 | 174 | must use the %logstart function, which allows you to specify an |
|
176 | 175 | optional log filename.""" |
|
177 | 176 | |
|
178 | 177 | self.shell.logger.switch_log(1) |
|
179 | 178 | |
|
180 | 179 | @line_magic |
|
181 | 180 | def logstate(self, parameter_s=''): |
|
182 | 181 | """Print the status of the logging system.""" |
|
183 | 182 | |
|
184 | 183 | self.shell.logger.logstate() |
|
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 |
|
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