Show More
@@ -1,270 +1,270 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Displayhook for IPython. |
|
3 | 3 | |
|
4 | 4 | This defines a callable class that IPython uses for `sys.displayhook`. |
|
5 | 5 | |
|
6 | 6 | Authors: |
|
7 | 7 | |
|
8 | 8 | * Fernando Perez |
|
9 | 9 | * Brian Granger |
|
10 | 10 | * Robert Kern |
|
11 | 11 | """ |
|
12 | 12 | |
|
13 | 13 | #----------------------------------------------------------------------------- |
|
14 | 14 | # Copyright (C) 2008-2011 The IPython Development Team |
|
15 | 15 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> |
|
16 | 16 | # |
|
17 | 17 | # Distributed under the terms of the BSD License. The full license is in |
|
18 | 18 | # the file COPYING, distributed as part of this software. |
|
19 | 19 | #----------------------------------------------------------------------------- |
|
20 | 20 | |
|
21 | 21 | #----------------------------------------------------------------------------- |
|
22 | 22 | # Imports |
|
23 | 23 | #----------------------------------------------------------------------------- |
|
24 | 24 | from __future__ import print_function |
|
25 | 25 | |
|
26 | 26 | import __builtin__ |
|
27 | 27 | |
|
28 | 28 | from IPython.config.configurable import Configurable |
|
29 | 29 | from IPython.utils import io |
|
30 | 30 | from IPython.utils.traitlets import Instance, List |
|
31 | 31 | from IPython.utils.warn import warn |
|
32 | 32 | |
|
33 | 33 | #----------------------------------------------------------------------------- |
|
34 | 34 | # Main displayhook class |
|
35 | 35 | #----------------------------------------------------------------------------- |
|
36 | 36 | |
|
37 | 37 | # TODO: Move the various attributes (cache_size, [others now moved]). Some |
|
38 | 38 | # of these are also attributes of InteractiveShell. They should be on ONE object |
|
39 | 39 | # only and the other objects should ask that one object for their values. |
|
40 | 40 | |
|
41 | 41 | class DisplayHook(Configurable): |
|
42 | 42 | """The custom IPython displayhook to replace sys.displayhook. |
|
43 | 43 | |
|
44 | 44 | This class does many things, but the basic idea is that it is a callable |
|
45 | 45 | that gets called anytime user code returns a value. |
|
46 | 46 | """ |
|
47 | 47 | |
|
48 | 48 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
49 | 49 | |
|
50 | 50 | def __init__(self, shell=None, cache_size=1000, config=None): |
|
51 | 51 | super(DisplayHook, self).__init__(shell=shell, config=config) |
|
52 | 52 | |
|
53 | 53 | cache_size_min = 3 |
|
54 | 54 | if cache_size <= 0: |
|
55 | 55 | self.do_full_cache = 0 |
|
56 | 56 | cache_size = 0 |
|
57 | 57 | elif cache_size < cache_size_min: |
|
58 | 58 | self.do_full_cache = 0 |
|
59 | 59 | cache_size = 0 |
|
60 | 60 | warn('caching was disabled (min value for cache size is %s).' % |
|
61 | 61 | cache_size_min,level=3) |
|
62 | 62 | else: |
|
63 | 63 | self.do_full_cache = 1 |
|
64 | 64 | |
|
65 | 65 | self.cache_size = cache_size |
|
66 | 66 | |
|
67 | 67 | # we need a reference to the user-level namespace |
|
68 | 68 | self.shell = shell |
|
69 | 69 | |
|
70 | 70 | self._,self.__,self.___ = '','','' |
|
71 | 71 | |
|
72 | 72 | # these are deliberately global: |
|
73 | 73 | to_user_ns = {'_':self._,'__':self.__,'___':self.___} |
|
74 | 74 | self.shell.user_ns.update(to_user_ns) |
|
75 | 75 | |
|
76 | 76 | @property |
|
77 | 77 | def prompt_count(self): |
|
78 | 78 | return self.shell.execution_count |
|
79 | 79 | |
|
80 | 80 | #------------------------------------------------------------------------- |
|
81 | 81 | # Methods used in __call__. Override these methods to modify the behavior |
|
82 | 82 | # of the displayhook. |
|
83 | 83 | #------------------------------------------------------------------------- |
|
84 | 84 | |
|
85 | 85 | def check_for_underscore(self): |
|
86 | 86 | """Check if the user has set the '_' variable by hand.""" |
|
87 | 87 | # If something injected a '_' variable in __builtin__, delete |
|
88 | 88 | # ipython's automatic one so we don't clobber that. gettext() in |
|
89 | 89 | # particular uses _, so we need to stay away from it. |
|
90 | 90 | if '_' in __builtin__.__dict__: |
|
91 | 91 | try: |
|
92 | 92 | del self.shell.user_ns['_'] |
|
93 | 93 | except KeyError: |
|
94 | 94 | pass |
|
95 | 95 | |
|
96 | 96 | def quiet(self): |
|
97 | 97 | """Should we silence the display hook because of ';'?""" |
|
98 | 98 | # do not print output if input ends in ';' |
|
99 | 99 | try: |
|
100 | 100 | cell = self.shell.history_manager.input_hist_parsed[self.prompt_count] |
|
101 | 101 | if cell.rstrip().endswith(';'): |
|
102 | 102 | return True |
|
103 | 103 | except IndexError: |
|
104 | 104 | # some uses of ipshellembed may fail here |
|
105 | 105 | pass |
|
106 | 106 | return False |
|
107 | 107 | |
|
108 | 108 | def start_displayhook(self): |
|
109 | 109 | """Start the displayhook, initializing resources.""" |
|
110 | 110 | pass |
|
111 | 111 | |
|
112 | 112 | def write_output_prompt(self): |
|
113 | 113 | """Write the output prompt. |
|
114 | 114 | |
|
115 | 115 | The default implementation simply writes the prompt to |
|
116 | 116 | ``io.stdout``. |
|
117 | 117 | """ |
|
118 | 118 | # Use write, not print which adds an extra space. |
|
119 | 119 | io.stdout.write(self.shell.separate_out) |
|
120 | 120 | outprompt = self.shell.prompt_manager.render('out') |
|
121 | 121 | if self.do_full_cache: |
|
122 | 122 | io.stdout.write(outprompt) |
|
123 | 123 | |
|
124 | 124 | def compute_format_data(self, result): |
|
125 | 125 | """Compute format data of the object to be displayed. |
|
126 | 126 | |
|
127 | 127 | The format data is a generalization of the :func:`repr` of an object. |
|
128 | 128 | In the default implementation the format data is a :class:`dict` of |
|
129 | 129 | key value pair where the keys are valid MIME types and the values |
|
130 | 130 | are JSON'able data structure containing the raw data for that MIME |
|
131 | 131 | type. It is up to frontends to determine pick a MIME to to use and |
|
132 | 132 | display that data in an appropriate manner. |
|
133 | 133 | |
|
134 | 134 | This method only computes the format data for the object and should |
|
135 | 135 | NOT actually print or write that to a stream. |
|
136 | 136 | |
|
137 | 137 | Parameters |
|
138 | 138 | ---------- |
|
139 | 139 | result : object |
|
140 | 140 | The Python object passed to the display hook, whose format will be |
|
141 | 141 | computed. |
|
142 | 142 | |
|
143 | 143 | Returns |
|
144 | 144 | ------- |
|
145 | 145 | format_data : dict |
|
146 | 146 | A :class:`dict` whose keys are valid MIME types and values are |
|
147 | 147 | JSON'able raw data for that MIME type. It is recommended that |
|
148 | 148 | all return values of this should always include the "text/plain" |
|
149 | 149 | MIME type representation of the object. |
|
150 | 150 | """ |
|
151 | 151 | return self.shell.display_formatter.format(result) |
|
152 | 152 | |
|
153 | 153 | def write_format_data(self, format_dict): |
|
154 | 154 | """Write the format data dict to the frontend. |
|
155 | 155 | |
|
156 | 156 | This default version of this method simply writes the plain text |
|
157 | 157 | representation of the object to ``io.stdout``. Subclasses should |
|
158 | 158 | override this method to send the entire `format_dict` to the |
|
159 | 159 | frontends. |
|
160 | 160 | |
|
161 | 161 | Parameters |
|
162 | 162 | ---------- |
|
163 | 163 | format_dict : dict |
|
164 | 164 | The format dict for the object passed to `sys.displayhook`. |
|
165 | 165 | """ |
|
166 | 166 | # We want to print because we want to always make sure we have a |
|
167 | 167 | # newline, even if all the prompt separators are ''. This is the |
|
168 | 168 | # standard IPython behavior. |
|
169 | 169 | result_repr = format_dict['text/plain'] |
|
170 | 170 | if '\n' in result_repr: |
|
171 | 171 | # So that multi-line strings line up with the left column of |
|
172 | 172 | # the screen, instead of having the output prompt mess up |
|
173 | 173 | # their first line. |
|
174 | 174 | # We use the prompt template instead of the expanded prompt |
|
175 | 175 | # because the expansion may add ANSI escapes that will interfere |
|
176 | 176 | # with our ability to determine whether or not we should add |
|
177 | 177 | # a newline. |
|
178 | 178 | prompt_template = self.shell.prompt_manager.out_template |
|
179 | 179 | if prompt_template and not prompt_template.endswith('\n'): |
|
180 | 180 | # But avoid extraneous empty lines. |
|
181 | 181 | result_repr = '\n' + result_repr |
|
182 | 182 | |
|
183 | 183 | print(result_repr, file=io.stdout) |
|
184 | 184 | |
|
185 | 185 | def update_user_ns(self, result): |
|
186 | 186 | """Update user_ns with various things like _, __, _1, etc.""" |
|
187 | 187 | |
|
188 | 188 | # Avoid recursive reference when displaying _oh/Out |
|
189 | 189 | if result is not self.shell.user_ns['_oh']: |
|
190 | 190 | if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache: |
|
191 | 191 | warn('Output cache limit (currently '+ |
|
192 | 192 | repr(self.cache_size)+' entries) hit.\n' |
|
193 | 193 | 'Flushing cache and resetting history counter...\n' |
|
194 | 194 | 'The only history variables available will be _,__,___ and _1\n' |
|
195 | 195 | 'with the current result.') |
|
196 | 196 | |
|
197 | 197 | self.flush() |
|
198 | 198 | # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise |
|
199 | 199 | # we cause buggy behavior for things like gettext). |
|
200 | 200 | |
|
201 | 201 | if '_' not in __builtin__.__dict__: |
|
202 | 202 | self.___ = self.__ |
|
203 | 203 | self.__ = self._ |
|
204 | 204 | self._ = result |
|
205 | 205 | self.shell.push({'_':self._, |
|
206 | 206 | '__':self.__, |
|
207 | 207 | '___':self.___}, interactive=False) |
|
208 | 208 | |
|
209 | 209 | # hackish access to top-level namespace to create _1,_2... dynamically |
|
210 | 210 | to_main = {} |
|
211 | 211 | if self.do_full_cache: |
|
212 | 212 | new_result = '_'+repr(self.prompt_count) |
|
213 | 213 | to_main[new_result] = result |
|
214 | 214 | self.shell.push(to_main, interactive=False) |
|
215 | 215 | self.shell.user_ns['_oh'][self.prompt_count] = result |
|
216 | 216 | |
|
217 | 217 | def log_output(self, format_dict): |
|
218 | 218 | """Log the output.""" |
|
219 | 219 | if self.shell.logger.log_output: |
|
220 | 220 | self.shell.logger.log_write(format_dict['text/plain'], 'output') |
|
221 | 221 | self.shell.history_manager.output_hist_reprs[self.prompt_count] = \ |
|
222 | 222 | format_dict['text/plain'] |
|
223 | 223 | |
|
224 | 224 | def finish_displayhook(self): |
|
225 | 225 | """Finish up all displayhook activities.""" |
|
226 | 226 | io.stdout.write(self.shell.separate_out2) |
|
227 | 227 | io.stdout.flush() |
|
228 | 228 | |
|
229 | 229 | def __call__(self, result=None): |
|
230 | 230 | """Printing with history cache management. |
|
231 | 231 | |
|
232 | 232 | This is invoked everytime the interpreter needs to print, and is |
|
233 | 233 | activated by setting the variable sys.displayhook to it. |
|
234 | 234 | """ |
|
235 | 235 | self.check_for_underscore() |
|
236 | 236 | if result is not None and not self.quiet(): |
|
237 | 237 | self.start_displayhook() |
|
238 | 238 | self.write_output_prompt() |
|
239 | 239 | format_dict = self.compute_format_data(result) |
|
240 | 240 | self.write_format_data(format_dict) |
|
241 | 241 | self.update_user_ns(result) |
|
242 | 242 | self.log_output(format_dict) |
|
243 | 243 | self.finish_displayhook() |
|
244 | 244 | |
|
245 | 245 | def flush(self): |
|
246 | 246 | if not self.do_full_cache: |
|
247 |
raise ValueError |
|
|
248 | "if full caching is not enabled!" | |
|
247 | raise ValueError("You shouldn't have reached the cache flush " | |
|
248 | "if full caching is not enabled!") | |
|
249 | 249 | # delete auto-generated vars from global namespace |
|
250 | 250 | |
|
251 | 251 | for n in range(1,self.prompt_count + 1): |
|
252 | 252 | key = '_'+repr(n) |
|
253 | 253 | try: |
|
254 | 254 | del self.shell.user_ns[key] |
|
255 | 255 | except: pass |
|
256 | 256 | # In some embedded circumstances, the user_ns doesn't have the |
|
257 | 257 | # '_oh' key set up. |
|
258 | 258 | oh = self.shell.user_ns.get('_oh', None) |
|
259 | 259 | if oh is not None: |
|
260 | 260 | oh.clear() |
|
261 | 261 | |
|
262 | 262 | # Release our own references to objects: |
|
263 | 263 | self._, self.__, self.___ = '', '', '' |
|
264 | 264 | |
|
265 | 265 | if '_' not in __builtin__.__dict__: |
|
266 | 266 | self.shell.user_ns.update({'_':None,'__':None, '___':None}) |
|
267 | 267 | import gc |
|
268 | 268 | # TODO: Is this really needed? |
|
269 | 269 | gc.collect() |
|
270 | 270 |
@@ -1,3010 +1,3010 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 | # Imports |
|
15 | 15 | #----------------------------------------------------------------------------- |
|
16 | 16 | |
|
17 | 17 | from __future__ import with_statement |
|
18 | 18 | from __future__ import absolute_import |
|
19 | 19 | from __future__ import print_function |
|
20 | 20 | |
|
21 | 21 | import __builtin__ as builtin_mod |
|
22 | 22 | import __future__ |
|
23 | 23 | import abc |
|
24 | 24 | import ast |
|
25 | 25 | import atexit |
|
26 | 26 | import os |
|
27 | 27 | import re |
|
28 | 28 | import runpy |
|
29 | 29 | import sys |
|
30 | 30 | import tempfile |
|
31 | 31 | import types |
|
32 | 32 | |
|
33 | 33 | # We need to use nested to support python 2.6, once we move to >=2.7, we can |
|
34 | 34 | # use the with keyword's new builtin support for nested managers |
|
35 | 35 | try: |
|
36 | 36 | from contextlib import nested |
|
37 | 37 | except: |
|
38 | 38 | from IPython.utils.nested_context import nested |
|
39 | 39 | |
|
40 | 40 | from IPython.config.configurable import SingletonConfigurable |
|
41 | 41 | from IPython.core import debugger, oinspect |
|
42 | 42 | from IPython.core import history as ipcorehist |
|
43 | 43 | from IPython.core import magic |
|
44 | 44 | from IPython.core import page |
|
45 | 45 | from IPython.core import prefilter |
|
46 | 46 | from IPython.core import shadowns |
|
47 | 47 | from IPython.core import ultratb |
|
48 | 48 | from IPython.core.alias import AliasManager, AliasError |
|
49 | 49 | from IPython.core.autocall import ExitAutocall |
|
50 | 50 | from IPython.core.builtin_trap import BuiltinTrap |
|
51 | 51 | from IPython.core.compilerop import CachingCompiler |
|
52 | 52 | from IPython.core.display_trap import DisplayTrap |
|
53 | 53 | from IPython.core.displayhook import DisplayHook |
|
54 | 54 | from IPython.core.displaypub import DisplayPublisher |
|
55 | 55 | from IPython.core.error import UsageError |
|
56 | 56 | from IPython.core.extensions import ExtensionManager |
|
57 | 57 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict |
|
58 | 58 | from IPython.core.formatters import DisplayFormatter |
|
59 | 59 | from IPython.core.history import HistoryManager |
|
60 | 60 | from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC, ESC_MAGIC2 |
|
61 | 61 | from IPython.core.logger import Logger |
|
62 | 62 | from IPython.core.macro import Macro |
|
63 | 63 | from IPython.core.payload import PayloadManager |
|
64 | 64 | from IPython.core.plugin import PluginManager |
|
65 | 65 | from IPython.core.prefilter import PrefilterManager |
|
66 | 66 | from IPython.core.profiledir import ProfileDir |
|
67 | 67 | from IPython.core.pylabtools import pylab_activate |
|
68 | 68 | from IPython.core.prompts import PromptManager |
|
69 | 69 | from IPython.utils import PyColorize |
|
70 | 70 | from IPython.utils import io |
|
71 | 71 | from IPython.utils import py3compat |
|
72 | 72 | from IPython.utils import openpy |
|
73 | 73 | from IPython.utils.doctestreload import doctest_reload |
|
74 | 74 | from IPython.utils.io import ask_yes_no |
|
75 | 75 | from IPython.utils.ipstruct import Struct |
|
76 | 76 | from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename |
|
77 | 77 | from IPython.utils.pickleshare import PickleShareDB |
|
78 | 78 | from IPython.utils.process import system, getoutput |
|
79 | 79 | from IPython.utils.strdispatch import StrDispatch |
|
80 | 80 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
81 | 81 | from IPython.utils.text import (format_screen, LSString, SList, |
|
82 | 82 | DollarFormatter) |
|
83 | 83 | from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum, |
|
84 | 84 | List, Unicode, Instance, Type) |
|
85 | 85 | from IPython.utils.warn import warn, error |
|
86 | 86 | import IPython.core.hooks |
|
87 | 87 | |
|
88 | 88 | # FIXME: do this in a function to avoid circular dependencies |
|
89 | 89 | # A better solution is to remove IPython.parallel.error, |
|
90 | 90 | # and place those classes in IPython.core.error. |
|
91 | 91 | |
|
92 | 92 | class RemoteError(Exception): |
|
93 | 93 | pass |
|
94 | 94 | |
|
95 | 95 | def _import_remote_error(): |
|
96 | 96 | global RemoteError |
|
97 | 97 | try: |
|
98 | 98 | from IPython.parallel.error import RemoteError |
|
99 | 99 | except: |
|
100 | 100 | pass |
|
101 | 101 | |
|
102 | 102 | _import_remote_error() |
|
103 | 103 | |
|
104 | 104 | #----------------------------------------------------------------------------- |
|
105 | 105 | # Globals |
|
106 | 106 | #----------------------------------------------------------------------------- |
|
107 | 107 | |
|
108 | 108 | # compiled regexps for autoindent management |
|
109 | 109 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
110 | 110 | |
|
111 | 111 | #----------------------------------------------------------------------------- |
|
112 | 112 | # Utilities |
|
113 | 113 | #----------------------------------------------------------------------------- |
|
114 | 114 | |
|
115 | 115 | def softspace(file, newvalue): |
|
116 | 116 | """Copied from code.py, to remove the dependency""" |
|
117 | 117 | |
|
118 | 118 | oldvalue = 0 |
|
119 | 119 | try: |
|
120 | 120 | oldvalue = file.softspace |
|
121 | 121 | except AttributeError: |
|
122 | 122 | pass |
|
123 | 123 | try: |
|
124 | 124 | file.softspace = newvalue |
|
125 | 125 | except (AttributeError, TypeError): |
|
126 | 126 | # "attribute-less object" or "read-only attributes" |
|
127 | 127 | pass |
|
128 | 128 | return oldvalue |
|
129 | 129 | |
|
130 | 130 | |
|
131 | 131 | def no_op(*a, **kw): pass |
|
132 | 132 | |
|
133 | 133 | class NoOpContext(object): |
|
134 | 134 | def __enter__(self): pass |
|
135 | 135 | def __exit__(self, type, value, traceback): pass |
|
136 | 136 | no_op_context = NoOpContext() |
|
137 | 137 | |
|
138 | 138 | class SpaceInInput(Exception): pass |
|
139 | 139 | |
|
140 | 140 | class Bunch: pass |
|
141 | 141 | |
|
142 | 142 | |
|
143 | 143 | def get_default_colors(): |
|
144 | 144 | if sys.platform=='darwin': |
|
145 | 145 | return "LightBG" |
|
146 | 146 | elif os.name=='nt': |
|
147 | 147 | return 'Linux' |
|
148 | 148 | else: |
|
149 | 149 | return 'Linux' |
|
150 | 150 | |
|
151 | 151 | |
|
152 | 152 | class SeparateUnicode(Unicode): |
|
153 | 153 | """A Unicode subclass to validate separate_in, separate_out, etc. |
|
154 | 154 | |
|
155 | 155 | This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'. |
|
156 | 156 | """ |
|
157 | 157 | |
|
158 | 158 | def validate(self, obj, value): |
|
159 | 159 | if value == '0': value = '' |
|
160 | 160 | value = value.replace('\\n','\n') |
|
161 | 161 | return super(SeparateUnicode, self).validate(obj, value) |
|
162 | 162 | |
|
163 | 163 | |
|
164 | 164 | class ReadlineNoRecord(object): |
|
165 | 165 | """Context manager to execute some code, then reload readline history |
|
166 | 166 | so that interactive input to the code doesn't appear when pressing up.""" |
|
167 | 167 | def __init__(self, shell): |
|
168 | 168 | self.shell = shell |
|
169 | 169 | self._nested_level = 0 |
|
170 | 170 | |
|
171 | 171 | def __enter__(self): |
|
172 | 172 | if self._nested_level == 0: |
|
173 | 173 | try: |
|
174 | 174 | self.orig_length = self.current_length() |
|
175 | 175 | self.readline_tail = self.get_readline_tail() |
|
176 | 176 | except (AttributeError, IndexError): # Can fail with pyreadline |
|
177 | 177 | self.orig_length, self.readline_tail = 999999, [] |
|
178 | 178 | self._nested_level += 1 |
|
179 | 179 | |
|
180 | 180 | def __exit__(self, type, value, traceback): |
|
181 | 181 | self._nested_level -= 1 |
|
182 | 182 | if self._nested_level == 0: |
|
183 | 183 | # Try clipping the end if it's got longer |
|
184 | 184 | try: |
|
185 | 185 | e = self.current_length() - self.orig_length |
|
186 | 186 | if e > 0: |
|
187 | 187 | for _ in range(e): |
|
188 | 188 | self.shell.readline.remove_history_item(self.orig_length) |
|
189 | 189 | |
|
190 | 190 | # If it still doesn't match, just reload readline history. |
|
191 | 191 | if self.current_length() != self.orig_length \ |
|
192 | 192 | or self.get_readline_tail() != self.readline_tail: |
|
193 | 193 | self.shell.refill_readline_hist() |
|
194 | 194 | except (AttributeError, IndexError): |
|
195 | 195 | pass |
|
196 | 196 | # Returning False will cause exceptions to propagate |
|
197 | 197 | return False |
|
198 | 198 | |
|
199 | 199 | def current_length(self): |
|
200 | 200 | return self.shell.readline.get_current_history_length() |
|
201 | 201 | |
|
202 | 202 | def get_readline_tail(self, n=10): |
|
203 | 203 | """Get the last n items in readline history.""" |
|
204 | 204 | end = self.shell.readline.get_current_history_length() + 1 |
|
205 | 205 | start = max(end-n, 1) |
|
206 | 206 | ghi = self.shell.readline.get_history_item |
|
207 | 207 | return [ghi(x) for x in range(start, end)] |
|
208 | 208 | |
|
209 | 209 | #----------------------------------------------------------------------------- |
|
210 | 210 | # Main IPython class |
|
211 | 211 | #----------------------------------------------------------------------------- |
|
212 | 212 | |
|
213 | 213 | class InteractiveShell(SingletonConfigurable): |
|
214 | 214 | """An enhanced, interactive shell for Python.""" |
|
215 | 215 | |
|
216 | 216 | _instance = None |
|
217 | 217 | |
|
218 | 218 | autocall = Enum((0,1,2), default_value=0, config=True, help= |
|
219 | 219 | """ |
|
220 | 220 | Make IPython automatically call any callable object even if you didn't |
|
221 | 221 | type explicit parentheses. For example, 'str 43' becomes 'str(43)' |
|
222 | 222 | automatically. The value can be '0' to disable the feature, '1' for |
|
223 | 223 | 'smart' autocall, where it is not applied if there are no more |
|
224 | 224 | arguments on the line, and '2' for 'full' autocall, where all callable |
|
225 | 225 | objects are automatically called (even if no arguments are present). |
|
226 | 226 | """ |
|
227 | 227 | ) |
|
228 | 228 | # TODO: remove all autoindent logic and put into frontends. |
|
229 | 229 | # We can't do this yet because even runlines uses the autoindent. |
|
230 | 230 | autoindent = CBool(True, config=True, help= |
|
231 | 231 | """ |
|
232 | 232 | Autoindent IPython code entered interactively. |
|
233 | 233 | """ |
|
234 | 234 | ) |
|
235 | 235 | automagic = CBool(True, config=True, help= |
|
236 | 236 | """ |
|
237 | 237 | Enable magic commands to be called without the leading %. |
|
238 | 238 | """ |
|
239 | 239 | ) |
|
240 | 240 | cache_size = Integer(1000, config=True, help= |
|
241 | 241 | """ |
|
242 | 242 | Set the size of the output cache. The default is 1000, you can |
|
243 | 243 | change it permanently in your config file. Setting it to 0 completely |
|
244 | 244 | disables the caching system, and the minimum value accepted is 20 (if |
|
245 | 245 | you provide a value less than 20, it is reset to 0 and a warning is |
|
246 | 246 | issued). This limit is defined because otherwise you'll spend more |
|
247 | 247 | time re-flushing a too small cache than working |
|
248 | 248 | """ |
|
249 | 249 | ) |
|
250 | 250 | color_info = CBool(True, config=True, help= |
|
251 | 251 | """ |
|
252 | 252 | Use colors for displaying information about objects. Because this |
|
253 | 253 | information is passed through a pager (like 'less'), and some pagers |
|
254 | 254 | get confused with color codes, this capability can be turned off. |
|
255 | 255 | """ |
|
256 | 256 | ) |
|
257 | 257 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), |
|
258 | 258 | default_value=get_default_colors(), config=True, |
|
259 | 259 | help="Set the color scheme (NoColor, Linux, or LightBG)." |
|
260 | 260 | ) |
|
261 | 261 | colors_force = CBool(False, help= |
|
262 | 262 | """ |
|
263 | 263 | Force use of ANSI color codes, regardless of OS and readline |
|
264 | 264 | availability. |
|
265 | 265 | """ |
|
266 | 266 | # FIXME: This is essentially a hack to allow ZMQShell to show colors |
|
267 | 267 | # without readline on Win32. When the ZMQ formatting system is |
|
268 | 268 | # refactored, this should be removed. |
|
269 | 269 | ) |
|
270 | 270 | debug = CBool(False, config=True) |
|
271 | 271 | deep_reload = CBool(False, config=True, help= |
|
272 | 272 | """ |
|
273 | 273 | Enable deep (recursive) reloading by default. IPython can use the |
|
274 | 274 | deep_reload module which reloads changes in modules recursively (it |
|
275 | 275 | replaces the reload() function, so you don't need to change anything to |
|
276 | 276 | use it). deep_reload() forces a full reload of modules whose code may |
|
277 | 277 | have changed, which the default reload() function does not. When |
|
278 | 278 | deep_reload is off, IPython will use the normal reload(), but |
|
279 | 279 | deep_reload will still be available as dreload(). |
|
280 | 280 | """ |
|
281 | 281 | ) |
|
282 | 282 | disable_failing_post_execute = CBool(False, config=True, |
|
283 | 283 | help="Don't call post-execute functions that have failed in the past." |
|
284 | 284 | ) |
|
285 | 285 | display_formatter = Instance(DisplayFormatter) |
|
286 | 286 | displayhook_class = Type(DisplayHook) |
|
287 | 287 | display_pub_class = Type(DisplayPublisher) |
|
288 | 288 | |
|
289 | 289 | exit_now = CBool(False) |
|
290 | 290 | exiter = Instance(ExitAutocall) |
|
291 | 291 | def _exiter_default(self): |
|
292 | 292 | return ExitAutocall(self) |
|
293 | 293 | # Monotonically increasing execution counter |
|
294 | 294 | execution_count = Integer(1) |
|
295 | 295 | filename = Unicode("<ipython console>") |
|
296 | 296 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ |
|
297 | 297 | |
|
298 | 298 | # Input splitter, to split entire cells of input into either individual |
|
299 | 299 | # interactive statements or whole blocks. |
|
300 | 300 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', |
|
301 | 301 | (), {}) |
|
302 | 302 | logstart = CBool(False, config=True, help= |
|
303 | 303 | """ |
|
304 | 304 | Start logging to the default log file. |
|
305 | 305 | """ |
|
306 | 306 | ) |
|
307 | 307 | logfile = Unicode('', config=True, help= |
|
308 | 308 | """ |
|
309 | 309 | The name of the logfile to use. |
|
310 | 310 | """ |
|
311 | 311 | ) |
|
312 | 312 | logappend = Unicode('', config=True, help= |
|
313 | 313 | """ |
|
314 | 314 | Start logging to the given file in append mode. |
|
315 | 315 | """ |
|
316 | 316 | ) |
|
317 | 317 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
318 | 318 | config=True) |
|
319 | 319 | pdb = CBool(False, config=True, help= |
|
320 | 320 | """ |
|
321 | 321 | Automatically call the pdb debugger after every exception. |
|
322 | 322 | """ |
|
323 | 323 | ) |
|
324 | 324 | multiline_history = CBool(sys.platform != 'win32', config=True, |
|
325 | 325 | help="Save multi-line entries as one entry in readline history" |
|
326 | 326 | ) |
|
327 | 327 | |
|
328 | 328 | # deprecated prompt traits: |
|
329 | 329 | |
|
330 | 330 | prompt_in1 = Unicode('In [\\#]: ', config=True, |
|
331 | 331 | help="Deprecated, use PromptManager.in_template") |
|
332 | 332 | prompt_in2 = Unicode(' .\\D.: ', config=True, |
|
333 | 333 | help="Deprecated, use PromptManager.in2_template") |
|
334 | 334 | prompt_out = Unicode('Out[\\#]: ', config=True, |
|
335 | 335 | help="Deprecated, use PromptManager.out_template") |
|
336 | 336 | prompts_pad_left = CBool(True, config=True, |
|
337 | 337 | help="Deprecated, use PromptManager.justify") |
|
338 | 338 | |
|
339 | 339 | def _prompt_trait_changed(self, name, old, new): |
|
340 | 340 | table = { |
|
341 | 341 | 'prompt_in1' : 'in_template', |
|
342 | 342 | 'prompt_in2' : 'in2_template', |
|
343 | 343 | 'prompt_out' : 'out_template', |
|
344 | 344 | 'prompts_pad_left' : 'justify', |
|
345 | 345 | } |
|
346 | 346 | warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}\n".format( |
|
347 | 347 | name=name, newname=table[name]) |
|
348 | 348 | ) |
|
349 | 349 | # protect against weird cases where self.config may not exist: |
|
350 | 350 | if self.config is not None: |
|
351 | 351 | # propagate to corresponding PromptManager trait |
|
352 | 352 | setattr(self.config.PromptManager, table[name], new) |
|
353 | 353 | |
|
354 | 354 | _prompt_in1_changed = _prompt_trait_changed |
|
355 | 355 | _prompt_in2_changed = _prompt_trait_changed |
|
356 | 356 | _prompt_out_changed = _prompt_trait_changed |
|
357 | 357 | _prompt_pad_left_changed = _prompt_trait_changed |
|
358 | 358 | |
|
359 | 359 | show_rewritten_input = CBool(True, config=True, |
|
360 | 360 | help="Show rewritten input, e.g. for autocall." |
|
361 | 361 | ) |
|
362 | 362 | |
|
363 | 363 | quiet = CBool(False, config=True) |
|
364 | 364 | |
|
365 | 365 | history_length = Integer(10000, config=True) |
|
366 | 366 | |
|
367 | 367 | # The readline stuff will eventually be moved to the terminal subclass |
|
368 | 368 | # but for now, we can't do that as readline is welded in everywhere. |
|
369 | 369 | readline_use = CBool(True, config=True) |
|
370 | 370 | readline_remove_delims = Unicode('-/~', config=True) |
|
371 | 371 | # don't use \M- bindings by default, because they |
|
372 | 372 | # conflict with 8-bit encodings. See gh-58,gh-88 |
|
373 | 373 | readline_parse_and_bind = List([ |
|
374 | 374 | 'tab: complete', |
|
375 | 375 | '"\C-l": clear-screen', |
|
376 | 376 | 'set show-all-if-ambiguous on', |
|
377 | 377 | '"\C-o": tab-insert', |
|
378 | 378 | '"\C-r": reverse-search-history', |
|
379 | 379 | '"\C-s": forward-search-history', |
|
380 | 380 | '"\C-p": history-search-backward', |
|
381 | 381 | '"\C-n": history-search-forward', |
|
382 | 382 | '"\e[A": history-search-backward', |
|
383 | 383 | '"\e[B": history-search-forward', |
|
384 | 384 | '"\C-k": kill-line', |
|
385 | 385 | '"\C-u": unix-line-discard', |
|
386 | 386 | ], allow_none=False, config=True) |
|
387 | 387 | |
|
388 | 388 | ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'], |
|
389 | 389 | default_value='last_expr', config=True, |
|
390 | 390 | help=""" |
|
391 | 391 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be |
|
392 | 392 | run interactively (displaying output from expressions).""") |
|
393 | 393 | |
|
394 | 394 | # TODO: this part of prompt management should be moved to the frontends. |
|
395 | 395 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' |
|
396 | 396 | separate_in = SeparateUnicode('\n', config=True) |
|
397 | 397 | separate_out = SeparateUnicode('', config=True) |
|
398 | 398 | separate_out2 = SeparateUnicode('', config=True) |
|
399 | 399 | wildcards_case_sensitive = CBool(True, config=True) |
|
400 | 400 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
401 | 401 | default_value='Context', config=True) |
|
402 | 402 | |
|
403 | 403 | # Subcomponents of InteractiveShell |
|
404 | 404 | alias_manager = Instance('IPython.core.alias.AliasManager') |
|
405 | 405 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
406 | 406 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') |
|
407 | 407 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') |
|
408 | 408 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') |
|
409 | 409 | plugin_manager = Instance('IPython.core.plugin.PluginManager') |
|
410 | 410 | payload_manager = Instance('IPython.core.payload.PayloadManager') |
|
411 | 411 | history_manager = Instance('IPython.core.history.HistoryManager') |
|
412 | 412 | magics_manager = Instance('IPython.core.magic.MagicsManager') |
|
413 | 413 | |
|
414 | 414 | profile_dir = Instance('IPython.core.application.ProfileDir') |
|
415 | 415 | @property |
|
416 | 416 | def profile(self): |
|
417 | 417 | if self.profile_dir is not None: |
|
418 | 418 | name = os.path.basename(self.profile_dir.location) |
|
419 | 419 | return name.replace('profile_','') |
|
420 | 420 | |
|
421 | 421 | |
|
422 | 422 | # Private interface |
|
423 | 423 | _post_execute = Instance(dict) |
|
424 | 424 | |
|
425 | 425 | def __init__(self, config=None, ipython_dir=None, profile_dir=None, |
|
426 | 426 | user_module=None, user_ns=None, |
|
427 | 427 | custom_exceptions=((), None)): |
|
428 | 428 | |
|
429 | 429 | # This is where traits with a config_key argument are updated |
|
430 | 430 | # from the values on config. |
|
431 | 431 | super(InteractiveShell, self).__init__(config=config) |
|
432 | 432 | self.configurables = [self] |
|
433 | 433 | |
|
434 | 434 | # These are relatively independent and stateless |
|
435 | 435 | self.init_ipython_dir(ipython_dir) |
|
436 | 436 | self.init_profile_dir(profile_dir) |
|
437 | 437 | self.init_instance_attrs() |
|
438 | 438 | self.init_environment() |
|
439 | 439 | |
|
440 | 440 | # Check if we're in a virtualenv, and set up sys.path. |
|
441 | 441 | self.init_virtualenv() |
|
442 | 442 | |
|
443 | 443 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
444 | 444 | self.init_create_namespaces(user_module, user_ns) |
|
445 | 445 | # This has to be done after init_create_namespaces because it uses |
|
446 | 446 | # something in self.user_ns, but before init_sys_modules, which |
|
447 | 447 | # is the first thing to modify sys. |
|
448 | 448 | # TODO: When we override sys.stdout and sys.stderr before this class |
|
449 | 449 | # is created, we are saving the overridden ones here. Not sure if this |
|
450 | 450 | # is what we want to do. |
|
451 | 451 | self.save_sys_module_state() |
|
452 | 452 | self.init_sys_modules() |
|
453 | 453 | |
|
454 | 454 | # While we're trying to have each part of the code directly access what |
|
455 | 455 | # it needs without keeping redundant references to objects, we have too |
|
456 | 456 | # much legacy code that expects ip.db to exist. |
|
457 | 457 | self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db')) |
|
458 | 458 | |
|
459 | 459 | self.init_history() |
|
460 | 460 | self.init_encoding() |
|
461 | 461 | self.init_prefilter() |
|
462 | 462 | |
|
463 | 463 | self.init_syntax_highlighting() |
|
464 | 464 | self.init_hooks() |
|
465 | 465 | self.init_pushd_popd_magic() |
|
466 | 466 | # self.init_traceback_handlers use to be here, but we moved it below |
|
467 | 467 | # because it and init_io have to come after init_readline. |
|
468 | 468 | self.init_user_ns() |
|
469 | 469 | self.init_logger() |
|
470 | 470 | self.init_alias() |
|
471 | 471 | self.init_builtins() |
|
472 | 472 | |
|
473 | 473 | # pre_config_initialization |
|
474 | 474 | |
|
475 | 475 | # The next section should contain everything that was in ipmaker. |
|
476 | 476 | self.init_logstart() |
|
477 | 477 | |
|
478 | 478 | # The following was in post_config_initialization |
|
479 | 479 | self.init_inspector() |
|
480 | 480 | # init_readline() must come before init_io(), because init_io uses |
|
481 | 481 | # readline related things. |
|
482 | 482 | self.init_readline() |
|
483 | 483 | # We save this here in case user code replaces raw_input, but it needs |
|
484 | 484 | # to be after init_readline(), because PyPy's readline works by replacing |
|
485 | 485 | # raw_input. |
|
486 | 486 | if py3compat.PY3: |
|
487 | 487 | self.raw_input_original = input |
|
488 | 488 | else: |
|
489 | 489 | self.raw_input_original = raw_input |
|
490 | 490 | # init_completer must come after init_readline, because it needs to |
|
491 | 491 | # know whether readline is present or not system-wide to configure the |
|
492 | 492 | # completers, since the completion machinery can now operate |
|
493 | 493 | # independently of readline (e.g. over the network) |
|
494 | 494 | self.init_completer() |
|
495 | 495 | # TODO: init_io() needs to happen before init_traceback handlers |
|
496 | 496 | # because the traceback handlers hardcode the stdout/stderr streams. |
|
497 | 497 | # This logic in in debugger.Pdb and should eventually be changed. |
|
498 | 498 | self.init_io() |
|
499 | 499 | self.init_traceback_handlers(custom_exceptions) |
|
500 | 500 | self.init_prompts() |
|
501 | 501 | self.init_display_formatter() |
|
502 | 502 | self.init_display_pub() |
|
503 | 503 | self.init_displayhook() |
|
504 | 504 | self.init_reload_doctest() |
|
505 | 505 | self.init_magics() |
|
506 | 506 | self.init_pdb() |
|
507 | 507 | self.init_extension_manager() |
|
508 | 508 | self.init_plugin_manager() |
|
509 | 509 | self.init_payload() |
|
510 | 510 | self.hooks.late_startup_hook() |
|
511 | 511 | atexit.register(self.atexit_operations) |
|
512 | 512 | |
|
513 | 513 | def get_ipython(self): |
|
514 | 514 | """Return the currently running IPython instance.""" |
|
515 | 515 | return self |
|
516 | 516 | |
|
517 | 517 | #------------------------------------------------------------------------- |
|
518 | 518 | # Trait changed handlers |
|
519 | 519 | #------------------------------------------------------------------------- |
|
520 | 520 | |
|
521 | 521 | def _ipython_dir_changed(self, name, new): |
|
522 | 522 | if not os.path.isdir(new): |
|
523 | 523 | os.makedirs(new, mode = 0777) |
|
524 | 524 | |
|
525 | 525 | def set_autoindent(self,value=None): |
|
526 | 526 | """Set the autoindent flag, checking for readline support. |
|
527 | 527 | |
|
528 | 528 | If called with no arguments, it acts as a toggle.""" |
|
529 | 529 | |
|
530 | 530 | if value != 0 and not self.has_readline: |
|
531 | 531 | if os.name == 'posix': |
|
532 | 532 | warn("The auto-indent feature requires the readline library") |
|
533 | 533 | self.autoindent = 0 |
|
534 | 534 | return |
|
535 | 535 | if value is None: |
|
536 | 536 | self.autoindent = not self.autoindent |
|
537 | 537 | else: |
|
538 | 538 | self.autoindent = value |
|
539 | 539 | |
|
540 | 540 | #------------------------------------------------------------------------- |
|
541 | 541 | # init_* methods called by __init__ |
|
542 | 542 | #------------------------------------------------------------------------- |
|
543 | 543 | |
|
544 | 544 | def init_ipython_dir(self, ipython_dir): |
|
545 | 545 | if ipython_dir is not None: |
|
546 | 546 | self.ipython_dir = ipython_dir |
|
547 | 547 | return |
|
548 | 548 | |
|
549 | 549 | self.ipython_dir = get_ipython_dir() |
|
550 | 550 | |
|
551 | 551 | def init_profile_dir(self, profile_dir): |
|
552 | 552 | if profile_dir is not None: |
|
553 | 553 | self.profile_dir = profile_dir |
|
554 | 554 | return |
|
555 | 555 | self.profile_dir =\ |
|
556 | 556 | ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default') |
|
557 | 557 | |
|
558 | 558 | def init_instance_attrs(self): |
|
559 | 559 | self.more = False |
|
560 | 560 | |
|
561 | 561 | # command compiler |
|
562 | 562 | self.compile = CachingCompiler() |
|
563 | 563 | |
|
564 | 564 | # Make an empty namespace, which extension writers can rely on both |
|
565 | 565 | # existing and NEVER being used by ipython itself. This gives them a |
|
566 | 566 | # convenient location for storing additional information and state |
|
567 | 567 | # their extensions may require, without fear of collisions with other |
|
568 | 568 | # ipython names that may develop later. |
|
569 | 569 | self.meta = Struct() |
|
570 | 570 | |
|
571 | 571 | # Temporary files used for various purposes. Deleted at exit. |
|
572 | 572 | self.tempfiles = [] |
|
573 | 573 | |
|
574 | 574 | # Keep track of readline usage (later set by init_readline) |
|
575 | 575 | self.has_readline = False |
|
576 | 576 | |
|
577 | 577 | # keep track of where we started running (mainly for crash post-mortem) |
|
578 | 578 | # This is not being used anywhere currently. |
|
579 | 579 | self.starting_dir = os.getcwdu() |
|
580 | 580 | |
|
581 | 581 | # Indentation management |
|
582 | 582 | self.indent_current_nsp = 0 |
|
583 | 583 | |
|
584 | 584 | # Dict to track post-execution functions that have been registered |
|
585 | 585 | self._post_execute = {} |
|
586 | 586 | |
|
587 | 587 | def init_environment(self): |
|
588 | 588 | """Any changes we need to make to the user's environment.""" |
|
589 | 589 | pass |
|
590 | 590 | |
|
591 | 591 | def init_encoding(self): |
|
592 | 592 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
593 | 593 | # under Win32 have it set to None, and we need to have a known valid |
|
594 | 594 | # encoding to use in the raw_input() method |
|
595 | 595 | try: |
|
596 | 596 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
597 | 597 | except AttributeError: |
|
598 | 598 | self.stdin_encoding = 'ascii' |
|
599 | 599 | |
|
600 | 600 | def init_syntax_highlighting(self): |
|
601 | 601 | # Python source parser/formatter for syntax highlighting |
|
602 | 602 | pyformat = PyColorize.Parser().format |
|
603 | 603 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) |
|
604 | 604 | |
|
605 | 605 | def init_pushd_popd_magic(self): |
|
606 | 606 | # for pushd/popd management |
|
607 | 607 | self.home_dir = get_home_dir() |
|
608 | 608 | |
|
609 | 609 | self.dir_stack = [] |
|
610 | 610 | |
|
611 | 611 | def init_logger(self): |
|
612 | 612 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', |
|
613 | 613 | logmode='rotate') |
|
614 | 614 | |
|
615 | 615 | def init_logstart(self): |
|
616 | 616 | """Initialize logging in case it was requested at the command line. |
|
617 | 617 | """ |
|
618 | 618 | if self.logappend: |
|
619 | 619 | self.magic('logstart %s append' % self.logappend) |
|
620 | 620 | elif self.logfile: |
|
621 | 621 | self.magic('logstart %' % self.logfile) |
|
622 | 622 | elif self.logstart: |
|
623 | 623 | self.magic('logstart') |
|
624 | 624 | |
|
625 | 625 | def init_builtins(self): |
|
626 | 626 | # A single, static flag that we set to True. Its presence indicates |
|
627 | 627 | # that an IPython shell has been created, and we make no attempts at |
|
628 | 628 | # removing on exit or representing the existence of more than one |
|
629 | 629 | # IPython at a time. |
|
630 | 630 | builtin_mod.__dict__['__IPYTHON__'] = True |
|
631 | 631 | |
|
632 | 632 | # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to |
|
633 | 633 | # manage on enter/exit, but with all our shells it's virtually |
|
634 | 634 | # impossible to get all the cases right. We're leaving the name in for |
|
635 | 635 | # those who adapted their codes to check for this flag, but will |
|
636 | 636 | # eventually remove it after a few more releases. |
|
637 | 637 | builtin_mod.__dict__['__IPYTHON__active'] = \ |
|
638 | 638 | 'Deprecated, check for __IPYTHON__' |
|
639 | 639 | |
|
640 | 640 | self.builtin_trap = BuiltinTrap(shell=self) |
|
641 | 641 | |
|
642 | 642 | def init_inspector(self): |
|
643 | 643 | # Object inspector |
|
644 | 644 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
645 | 645 | PyColorize.ANSICodeColors, |
|
646 | 646 | 'NoColor', |
|
647 | 647 | self.object_info_string_level) |
|
648 | 648 | |
|
649 | 649 | def init_io(self): |
|
650 | 650 | # This will just use sys.stdout and sys.stderr. If you want to |
|
651 | 651 | # override sys.stdout and sys.stderr themselves, you need to do that |
|
652 | 652 | # *before* instantiating this class, because io holds onto |
|
653 | 653 | # references to the underlying streams. |
|
654 | 654 | if sys.platform == 'win32' and self.has_readline: |
|
655 | 655 | io.stdout = io.stderr = io.IOStream(self.readline._outputfile) |
|
656 | 656 | else: |
|
657 | 657 | io.stdout = io.IOStream(sys.stdout) |
|
658 | 658 | io.stderr = io.IOStream(sys.stderr) |
|
659 | 659 | |
|
660 | 660 | def init_prompts(self): |
|
661 | 661 | self.prompt_manager = PromptManager(shell=self, config=self.config) |
|
662 | 662 | self.configurables.append(self.prompt_manager) |
|
663 | 663 | # Set system prompts, so that scripts can decide if they are running |
|
664 | 664 | # interactively. |
|
665 | 665 | sys.ps1 = 'In : ' |
|
666 | 666 | sys.ps2 = '...: ' |
|
667 | 667 | sys.ps3 = 'Out: ' |
|
668 | 668 | |
|
669 | 669 | def init_display_formatter(self): |
|
670 | 670 | self.display_formatter = DisplayFormatter(config=self.config) |
|
671 | 671 | self.configurables.append(self.display_formatter) |
|
672 | 672 | |
|
673 | 673 | def init_display_pub(self): |
|
674 | 674 | self.display_pub = self.display_pub_class(config=self.config) |
|
675 | 675 | self.configurables.append(self.display_pub) |
|
676 | 676 | |
|
677 | 677 | def init_displayhook(self): |
|
678 | 678 | # Initialize displayhook, set in/out prompts and printing system |
|
679 | 679 | self.displayhook = self.displayhook_class( |
|
680 | 680 | config=self.config, |
|
681 | 681 | shell=self, |
|
682 | 682 | cache_size=self.cache_size, |
|
683 | 683 | ) |
|
684 | 684 | self.configurables.append(self.displayhook) |
|
685 | 685 | # This is a context manager that installs/revmoes the displayhook at |
|
686 | 686 | # the appropriate time. |
|
687 | 687 | self.display_trap = DisplayTrap(hook=self.displayhook) |
|
688 | 688 | |
|
689 | 689 | def init_reload_doctest(self): |
|
690 | 690 | # Do a proper resetting of doctest, including the necessary displayhook |
|
691 | 691 | # monkeypatching |
|
692 | 692 | try: |
|
693 | 693 | doctest_reload() |
|
694 | 694 | except ImportError: |
|
695 | 695 | warn("doctest module does not exist.") |
|
696 | 696 | |
|
697 | 697 | def init_virtualenv(self): |
|
698 | 698 | """Add a virtualenv to sys.path so the user can import modules from it. |
|
699 | 699 | This isn't perfect: it doesn't use the Python interpreter with which the |
|
700 | 700 | virtualenv was built, and it ignores the --no-site-packages option. A |
|
701 | 701 | warning will appear suggesting the user installs IPython in the |
|
702 | 702 | virtualenv, but for many cases, it probably works well enough. |
|
703 | 703 | |
|
704 | 704 | Adapted from code snippets online. |
|
705 | 705 | |
|
706 | 706 | http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv |
|
707 | 707 | """ |
|
708 | 708 | if 'VIRTUAL_ENV' not in os.environ: |
|
709 | 709 | # Not in a virtualenv |
|
710 | 710 | return |
|
711 | 711 | |
|
712 | 712 | if sys.executable.startswith(os.environ['VIRTUAL_ENV']): |
|
713 | 713 | # Running properly in the virtualenv, don't need to do anything |
|
714 | 714 | return |
|
715 | 715 | |
|
716 | 716 | warn("Attempting to work in a virtualenv. If you encounter problems, please " |
|
717 | 717 | "install IPython inside the virtualenv.\n") |
|
718 | 718 | if sys.platform == "win32": |
|
719 | 719 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages') |
|
720 | 720 | else: |
|
721 | 721 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib', |
|
722 | 722 | 'python%d.%d' % sys.version_info[:2], 'site-packages') |
|
723 | 723 | |
|
724 | 724 | import site |
|
725 | 725 | sys.path.insert(0, virtual_env) |
|
726 | 726 | site.addsitedir(virtual_env) |
|
727 | 727 | |
|
728 | 728 | #------------------------------------------------------------------------- |
|
729 | 729 | # Things related to injections into the sys module |
|
730 | 730 | #------------------------------------------------------------------------- |
|
731 | 731 | |
|
732 | 732 | def save_sys_module_state(self): |
|
733 | 733 | """Save the state of hooks in the sys module. |
|
734 | 734 | |
|
735 | 735 | This has to be called after self.user_module is created. |
|
736 | 736 | """ |
|
737 | 737 | self._orig_sys_module_state = {} |
|
738 | 738 | self._orig_sys_module_state['stdin'] = sys.stdin |
|
739 | 739 | self._orig_sys_module_state['stdout'] = sys.stdout |
|
740 | 740 | self._orig_sys_module_state['stderr'] = sys.stderr |
|
741 | 741 | self._orig_sys_module_state['excepthook'] = sys.excepthook |
|
742 | 742 | self._orig_sys_modules_main_name = self.user_module.__name__ |
|
743 | 743 | self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__) |
|
744 | 744 | |
|
745 | 745 | def restore_sys_module_state(self): |
|
746 | 746 | """Restore the state of the sys module.""" |
|
747 | 747 | try: |
|
748 | 748 | for k, v in self._orig_sys_module_state.iteritems(): |
|
749 | 749 | setattr(sys, k, v) |
|
750 | 750 | except AttributeError: |
|
751 | 751 | pass |
|
752 | 752 | # Reset what what done in self.init_sys_modules |
|
753 | 753 | if self._orig_sys_modules_main_mod is not None: |
|
754 | 754 | sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod |
|
755 | 755 | |
|
756 | 756 | #------------------------------------------------------------------------- |
|
757 | 757 | # Things related to hooks |
|
758 | 758 | #------------------------------------------------------------------------- |
|
759 | 759 | |
|
760 | 760 | def init_hooks(self): |
|
761 | 761 | # hooks holds pointers used for user-side customizations |
|
762 | 762 | self.hooks = Struct() |
|
763 | 763 | |
|
764 | 764 | self.strdispatchers = {} |
|
765 | 765 | |
|
766 | 766 | # Set all default hooks, defined in the IPython.hooks module. |
|
767 | 767 | hooks = IPython.core.hooks |
|
768 | 768 | for hook_name in hooks.__all__: |
|
769 | 769 | # default hooks have priority 100, i.e. low; user hooks should have |
|
770 | 770 | # 0-100 priority |
|
771 | 771 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
772 | 772 | |
|
773 | 773 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
774 | 774 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
775 | 775 | |
|
776 | 776 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
777 | 777 | adding your function to one of these hooks, you can modify IPython's |
|
778 | 778 | behavior to call at runtime your own routines.""" |
|
779 | 779 | |
|
780 | 780 | # At some point in the future, this should validate the hook before it |
|
781 | 781 | # accepts it. Probably at least check that the hook takes the number |
|
782 | 782 | # of args it's supposed to. |
|
783 | 783 | |
|
784 | 784 | f = types.MethodType(hook,self) |
|
785 | 785 | |
|
786 | 786 | # check if the hook is for strdispatcher first |
|
787 | 787 | if str_key is not None: |
|
788 | 788 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
789 | 789 | sdp.add_s(str_key, f, priority ) |
|
790 | 790 | self.strdispatchers[name] = sdp |
|
791 | 791 | return |
|
792 | 792 | if re_key is not None: |
|
793 | 793 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
794 | 794 | sdp.add_re(re.compile(re_key), f, priority ) |
|
795 | 795 | self.strdispatchers[name] = sdp |
|
796 | 796 | return |
|
797 | 797 | |
|
798 | 798 | dp = getattr(self.hooks, name, None) |
|
799 | 799 | if name not in IPython.core.hooks.__all__: |
|
800 | 800 | print("Warning! Hook '%s' is not one of %s" % \ |
|
801 | 801 | (name, IPython.core.hooks.__all__ )) |
|
802 | 802 | if not dp: |
|
803 | 803 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
804 | 804 | |
|
805 | 805 | try: |
|
806 | 806 | dp.add(f,priority) |
|
807 | 807 | except AttributeError: |
|
808 | 808 | # it was not commandchain, plain old func - replace |
|
809 | 809 | dp = f |
|
810 | 810 | |
|
811 | 811 | setattr(self.hooks,name, dp) |
|
812 | 812 | |
|
813 | 813 | def register_post_execute(self, func): |
|
814 | 814 | """Register a function for calling after code execution. |
|
815 | 815 | """ |
|
816 | 816 | if not callable(func): |
|
817 | 817 | raise ValueError('argument %s must be callable' % func) |
|
818 | 818 | self._post_execute[func] = True |
|
819 | 819 | |
|
820 | 820 | #------------------------------------------------------------------------- |
|
821 | 821 | # Things related to the "main" module |
|
822 | 822 | #------------------------------------------------------------------------- |
|
823 | 823 | |
|
824 | 824 | def new_main_mod(self,ns=None): |
|
825 | 825 | """Return a new 'main' module object for user code execution. |
|
826 | 826 | """ |
|
827 | 827 | main_mod = self._user_main_module |
|
828 | 828 | init_fakemod_dict(main_mod,ns) |
|
829 | 829 | return main_mod |
|
830 | 830 | |
|
831 | 831 | def cache_main_mod(self,ns,fname): |
|
832 | 832 | """Cache a main module's namespace. |
|
833 | 833 | |
|
834 | 834 | When scripts are executed via %run, we must keep a reference to the |
|
835 | 835 | namespace of their __main__ module (a FakeModule instance) around so |
|
836 | 836 | that Python doesn't clear it, rendering objects defined therein |
|
837 | 837 | useless. |
|
838 | 838 | |
|
839 | 839 | This method keeps said reference in a private dict, keyed by the |
|
840 | 840 | absolute path of the module object (which corresponds to the script |
|
841 | 841 | path). This way, for multiple executions of the same script we only |
|
842 | 842 | keep one copy of the namespace (the last one), thus preventing memory |
|
843 | 843 | leaks from old references while allowing the objects from the last |
|
844 | 844 | execution to be accessible. |
|
845 | 845 | |
|
846 | 846 | Note: we can not allow the actual FakeModule instances to be deleted, |
|
847 | 847 | because of how Python tears down modules (it hard-sets all their |
|
848 | 848 | references to None without regard for reference counts). This method |
|
849 | 849 | must therefore make a *copy* of the given namespace, to allow the |
|
850 | 850 | original module's __dict__ to be cleared and reused. |
|
851 | 851 | |
|
852 | 852 | |
|
853 | 853 | Parameters |
|
854 | 854 | ---------- |
|
855 | 855 | ns : a namespace (a dict, typically) |
|
856 | 856 | |
|
857 | 857 | fname : str |
|
858 | 858 | Filename associated with the namespace. |
|
859 | 859 | |
|
860 | 860 | Examples |
|
861 | 861 | -------- |
|
862 | 862 | |
|
863 | 863 | In [10]: import IPython |
|
864 | 864 | |
|
865 | 865 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
866 | 866 | |
|
867 | 867 | In [12]: IPython.__file__ in _ip._main_ns_cache |
|
868 | 868 | Out[12]: True |
|
869 | 869 | """ |
|
870 | 870 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() |
|
871 | 871 | |
|
872 | 872 | def clear_main_mod_cache(self): |
|
873 | 873 | """Clear the cache of main modules. |
|
874 | 874 | |
|
875 | 875 | Mainly for use by utilities like %reset. |
|
876 | 876 | |
|
877 | 877 | Examples |
|
878 | 878 | -------- |
|
879 | 879 | |
|
880 | 880 | In [15]: import IPython |
|
881 | 881 | |
|
882 | 882 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
883 | 883 | |
|
884 | 884 | In [17]: len(_ip._main_ns_cache) > 0 |
|
885 | 885 | Out[17]: True |
|
886 | 886 | |
|
887 | 887 | In [18]: _ip.clear_main_mod_cache() |
|
888 | 888 | |
|
889 | 889 | In [19]: len(_ip._main_ns_cache) == 0 |
|
890 | 890 | Out[19]: True |
|
891 | 891 | """ |
|
892 | 892 | self._main_ns_cache.clear() |
|
893 | 893 | |
|
894 | 894 | #------------------------------------------------------------------------- |
|
895 | 895 | # Things related to debugging |
|
896 | 896 | #------------------------------------------------------------------------- |
|
897 | 897 | |
|
898 | 898 | def init_pdb(self): |
|
899 | 899 | # Set calling of pdb on exceptions |
|
900 | 900 | # self.call_pdb is a property |
|
901 | 901 | self.call_pdb = self.pdb |
|
902 | 902 | |
|
903 | 903 | def _get_call_pdb(self): |
|
904 | 904 | return self._call_pdb |
|
905 | 905 | |
|
906 | 906 | def _set_call_pdb(self,val): |
|
907 | 907 | |
|
908 | 908 | if val not in (0,1,False,True): |
|
909 |
raise ValueError |
|
|
909 | raise ValueError('new call_pdb value must be boolean') | |
|
910 | 910 | |
|
911 | 911 | # store value in instance |
|
912 | 912 | self._call_pdb = val |
|
913 | 913 | |
|
914 | 914 | # notify the actual exception handlers |
|
915 | 915 | self.InteractiveTB.call_pdb = val |
|
916 | 916 | |
|
917 | 917 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
918 | 918 | 'Control auto-activation of pdb at exceptions') |
|
919 | 919 | |
|
920 | 920 | def debugger(self,force=False): |
|
921 | 921 | """Call the pydb/pdb debugger. |
|
922 | 922 | |
|
923 | 923 | Keywords: |
|
924 | 924 | |
|
925 | 925 | - force(False): by default, this routine checks the instance call_pdb |
|
926 | 926 | flag and does not actually invoke the debugger if the flag is false. |
|
927 | 927 | The 'force' option forces the debugger to activate even if the flag |
|
928 | 928 | is false. |
|
929 | 929 | """ |
|
930 | 930 | |
|
931 | 931 | if not (force or self.call_pdb): |
|
932 | 932 | return |
|
933 | 933 | |
|
934 | 934 | if not hasattr(sys,'last_traceback'): |
|
935 | 935 | error('No traceback has been produced, nothing to debug.') |
|
936 | 936 | return |
|
937 | 937 | |
|
938 | 938 | # use pydb if available |
|
939 | 939 | if debugger.has_pydb: |
|
940 | 940 | from pydb import pm |
|
941 | 941 | else: |
|
942 | 942 | # fallback to our internal debugger |
|
943 | 943 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
944 | 944 | |
|
945 | 945 | with self.readline_no_record: |
|
946 | 946 | pm() |
|
947 | 947 | |
|
948 | 948 | #------------------------------------------------------------------------- |
|
949 | 949 | # Things related to IPython's various namespaces |
|
950 | 950 | #------------------------------------------------------------------------- |
|
951 | 951 | default_user_namespaces = True |
|
952 | 952 | |
|
953 | 953 | def init_create_namespaces(self, user_module=None, user_ns=None): |
|
954 | 954 | # Create the namespace where the user will operate. user_ns is |
|
955 | 955 | # normally the only one used, and it is passed to the exec calls as |
|
956 | 956 | # the locals argument. But we do carry a user_global_ns namespace |
|
957 | 957 | # given as the exec 'globals' argument, This is useful in embedding |
|
958 | 958 | # situations where the ipython shell opens in a context where the |
|
959 | 959 | # distinction between locals and globals is meaningful. For |
|
960 | 960 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
961 | 961 | |
|
962 | 962 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
963 | 963 | # level as a dict instead of a module. This is a manual fix, but I |
|
964 | 964 | # should really track down where the problem is coming from. Alex |
|
965 | 965 | # Schmolck reported this problem first. |
|
966 | 966 | |
|
967 | 967 | # A useful post by Alex Martelli on this topic: |
|
968 | 968 | # Re: inconsistent value from __builtins__ |
|
969 | 969 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
970 | 970 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
971 | 971 | # Gruppen: comp.lang.python |
|
972 | 972 | |
|
973 | 973 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
974 | 974 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
975 | 975 | # > <type 'dict'> |
|
976 | 976 | # > >>> print type(__builtins__) |
|
977 | 977 | # > <type 'module'> |
|
978 | 978 | # > Is this difference in return value intentional? |
|
979 | 979 | |
|
980 | 980 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
981 | 981 | # or a module, and it's been that way for a long time. Whether it's |
|
982 | 982 | # intentional (or sensible), I don't know. In any case, the idea is |
|
983 | 983 | # that if you need to access the built-in namespace directly, you |
|
984 | 984 | # should start with "import __builtin__" (note, no 's') which will |
|
985 | 985 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
986 | 986 | |
|
987 | 987 | # These routines return a properly built module and dict as needed by |
|
988 | 988 | # the rest of the code, and can also be used by extension writers to |
|
989 | 989 | # generate properly initialized namespaces. |
|
990 | 990 | if (user_ns is not None) or (user_module is not None): |
|
991 | 991 | self.default_user_namespaces = False |
|
992 | 992 | self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns) |
|
993 | 993 | |
|
994 | 994 | # A record of hidden variables we have added to the user namespace, so |
|
995 | 995 | # we can list later only variables defined in actual interactive use. |
|
996 | 996 | self.user_ns_hidden = set() |
|
997 | 997 | |
|
998 | 998 | # Now that FakeModule produces a real module, we've run into a nasty |
|
999 | 999 | # problem: after script execution (via %run), the module where the user |
|
1000 | 1000 | # code ran is deleted. Now that this object is a true module (needed |
|
1001 | 1001 | # so docetst and other tools work correctly), the Python module |
|
1002 | 1002 | # teardown mechanism runs over it, and sets to None every variable |
|
1003 | 1003 | # present in that module. Top-level references to objects from the |
|
1004 | 1004 | # script survive, because the user_ns is updated with them. However, |
|
1005 | 1005 | # calling functions defined in the script that use other things from |
|
1006 | 1006 | # the script will fail, because the function's closure had references |
|
1007 | 1007 | # to the original objects, which are now all None. So we must protect |
|
1008 | 1008 | # these modules from deletion by keeping a cache. |
|
1009 | 1009 | # |
|
1010 | 1010 | # To avoid keeping stale modules around (we only need the one from the |
|
1011 | 1011 | # last run), we use a dict keyed with the full path to the script, so |
|
1012 | 1012 | # only the last version of the module is held in the cache. Note, |
|
1013 | 1013 | # however, that we must cache the module *namespace contents* (their |
|
1014 | 1014 | # __dict__). Because if we try to cache the actual modules, old ones |
|
1015 | 1015 | # (uncached) could be destroyed while still holding references (such as |
|
1016 | 1016 | # those held by GUI objects that tend to be long-lived)> |
|
1017 | 1017 | # |
|
1018 | 1018 | # The %reset command will flush this cache. See the cache_main_mod() |
|
1019 | 1019 | # and clear_main_mod_cache() methods for details on use. |
|
1020 | 1020 | |
|
1021 | 1021 | # This is the cache used for 'main' namespaces |
|
1022 | 1022 | self._main_ns_cache = {} |
|
1023 | 1023 | # And this is the single instance of FakeModule whose __dict__ we keep |
|
1024 | 1024 | # copying and clearing for reuse on each %run |
|
1025 | 1025 | self._user_main_module = FakeModule() |
|
1026 | 1026 | |
|
1027 | 1027 | # A table holding all the namespaces IPython deals with, so that |
|
1028 | 1028 | # introspection facilities can search easily. |
|
1029 | 1029 | self.ns_table = {'user_global':self.user_module.__dict__, |
|
1030 | 1030 | 'user_local':self.user_ns, |
|
1031 | 1031 | 'builtin':builtin_mod.__dict__ |
|
1032 | 1032 | } |
|
1033 | 1033 | |
|
1034 | 1034 | @property |
|
1035 | 1035 | def user_global_ns(self): |
|
1036 | 1036 | return self.user_module.__dict__ |
|
1037 | 1037 | |
|
1038 | 1038 | def prepare_user_module(self, user_module=None, user_ns=None): |
|
1039 | 1039 | """Prepare the module and namespace in which user code will be run. |
|
1040 | 1040 | |
|
1041 | 1041 | When IPython is started normally, both parameters are None: a new module |
|
1042 | 1042 | is created automatically, and its __dict__ used as the namespace. |
|
1043 | 1043 | |
|
1044 | 1044 | If only user_module is provided, its __dict__ is used as the namespace. |
|
1045 | 1045 | If only user_ns is provided, a dummy module is created, and user_ns |
|
1046 | 1046 | becomes the global namespace. If both are provided (as they may be |
|
1047 | 1047 | when embedding), user_ns is the local namespace, and user_module |
|
1048 | 1048 | provides the global namespace. |
|
1049 | 1049 | |
|
1050 | 1050 | Parameters |
|
1051 | 1051 | ---------- |
|
1052 | 1052 | user_module : module, optional |
|
1053 | 1053 | The current user module in which IPython is being run. If None, |
|
1054 | 1054 | a clean module will be created. |
|
1055 | 1055 | user_ns : dict, optional |
|
1056 | 1056 | A namespace in which to run interactive commands. |
|
1057 | 1057 | |
|
1058 | 1058 | Returns |
|
1059 | 1059 | ------- |
|
1060 | 1060 | A tuple of user_module and user_ns, each properly initialised. |
|
1061 | 1061 | """ |
|
1062 | 1062 | if user_module is None and user_ns is not None: |
|
1063 | 1063 | user_ns.setdefault("__name__", "__main__") |
|
1064 | 1064 | class DummyMod(object): |
|
1065 | 1065 | "A dummy module used for IPython's interactive namespace." |
|
1066 | 1066 | pass |
|
1067 | 1067 | user_module = DummyMod() |
|
1068 | 1068 | user_module.__dict__ = user_ns |
|
1069 | 1069 | |
|
1070 | 1070 | if user_module is None: |
|
1071 | 1071 | user_module = types.ModuleType("__main__", |
|
1072 | 1072 | doc="Automatically created module for IPython interactive environment") |
|
1073 | 1073 | |
|
1074 | 1074 | # We must ensure that __builtin__ (without the final 's') is always |
|
1075 | 1075 | # available and pointing to the __builtin__ *module*. For more details: |
|
1076 | 1076 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
1077 | 1077 | user_module.__dict__.setdefault('__builtin__', builtin_mod) |
|
1078 | 1078 | user_module.__dict__.setdefault('__builtins__', builtin_mod) |
|
1079 | 1079 | |
|
1080 | 1080 | if user_ns is None: |
|
1081 | 1081 | user_ns = user_module.__dict__ |
|
1082 | 1082 | |
|
1083 | 1083 | return user_module, user_ns |
|
1084 | 1084 | |
|
1085 | 1085 | def init_sys_modules(self): |
|
1086 | 1086 | # We need to insert into sys.modules something that looks like a |
|
1087 | 1087 | # module but which accesses the IPython namespace, for shelve and |
|
1088 | 1088 | # pickle to work interactively. Normally they rely on getting |
|
1089 | 1089 | # everything out of __main__, but for embedding purposes each IPython |
|
1090 | 1090 | # instance has its own private namespace, so we can't go shoving |
|
1091 | 1091 | # everything into __main__. |
|
1092 | 1092 | |
|
1093 | 1093 | # note, however, that we should only do this for non-embedded |
|
1094 | 1094 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
1095 | 1095 | # namespace. Embedded instances, on the other hand, should not do |
|
1096 | 1096 | # this because they need to manage the user local/global namespaces |
|
1097 | 1097 | # only, but they live within a 'normal' __main__ (meaning, they |
|
1098 | 1098 | # shouldn't overtake the execution environment of the script they're |
|
1099 | 1099 | # embedded in). |
|
1100 | 1100 | |
|
1101 | 1101 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
1102 | 1102 | main_name = self.user_module.__name__ |
|
1103 | 1103 | sys.modules[main_name] = self.user_module |
|
1104 | 1104 | |
|
1105 | 1105 | def init_user_ns(self): |
|
1106 | 1106 | """Initialize all user-visible namespaces to their minimum defaults. |
|
1107 | 1107 | |
|
1108 | 1108 | Certain history lists are also initialized here, as they effectively |
|
1109 | 1109 | act as user namespaces. |
|
1110 | 1110 | |
|
1111 | 1111 | Notes |
|
1112 | 1112 | ----- |
|
1113 | 1113 | All data structures here are only filled in, they are NOT reset by this |
|
1114 | 1114 | method. If they were not empty before, data will simply be added to |
|
1115 | 1115 | therm. |
|
1116 | 1116 | """ |
|
1117 | 1117 | # This function works in two parts: first we put a few things in |
|
1118 | 1118 | # user_ns, and we sync that contents into user_ns_hidden so that these |
|
1119 | 1119 | # initial variables aren't shown by %who. After the sync, we add the |
|
1120 | 1120 | # rest of what we *do* want the user to see with %who even on a new |
|
1121 | 1121 | # session (probably nothing, so theye really only see their own stuff) |
|
1122 | 1122 | |
|
1123 | 1123 | # The user dict must *always* have a __builtin__ reference to the |
|
1124 | 1124 | # Python standard __builtin__ namespace, which must be imported. |
|
1125 | 1125 | # This is so that certain operations in prompt evaluation can be |
|
1126 | 1126 | # reliably executed with builtins. Note that we can NOT use |
|
1127 | 1127 | # __builtins__ (note the 's'), because that can either be a dict or a |
|
1128 | 1128 | # module, and can even mutate at runtime, depending on the context |
|
1129 | 1129 | # (Python makes no guarantees on it). In contrast, __builtin__ is |
|
1130 | 1130 | # always a module object, though it must be explicitly imported. |
|
1131 | 1131 | |
|
1132 | 1132 | # For more details: |
|
1133 | 1133 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
1134 | 1134 | ns = dict() |
|
1135 | 1135 | |
|
1136 | 1136 | # Put 'help' in the user namespace |
|
1137 | 1137 | try: |
|
1138 | 1138 | from site import _Helper |
|
1139 | 1139 | ns['help'] = _Helper() |
|
1140 | 1140 | except ImportError: |
|
1141 | 1141 | warn('help() not available - check site.py') |
|
1142 | 1142 | |
|
1143 | 1143 | # make global variables for user access to the histories |
|
1144 | 1144 | ns['_ih'] = self.history_manager.input_hist_parsed |
|
1145 | 1145 | ns['_oh'] = self.history_manager.output_hist |
|
1146 | 1146 | ns['_dh'] = self.history_manager.dir_hist |
|
1147 | 1147 | |
|
1148 | 1148 | ns['_sh'] = shadowns |
|
1149 | 1149 | |
|
1150 | 1150 | # user aliases to input and output histories. These shouldn't show up |
|
1151 | 1151 | # in %who, as they can have very large reprs. |
|
1152 | 1152 | ns['In'] = self.history_manager.input_hist_parsed |
|
1153 | 1153 | ns['Out'] = self.history_manager.output_hist |
|
1154 | 1154 | |
|
1155 | 1155 | # Store myself as the public api!!! |
|
1156 | 1156 | ns['get_ipython'] = self.get_ipython |
|
1157 | 1157 | |
|
1158 | 1158 | ns['exit'] = self.exiter |
|
1159 | 1159 | ns['quit'] = self.exiter |
|
1160 | 1160 | |
|
1161 | 1161 | # Sync what we've added so far to user_ns_hidden so these aren't seen |
|
1162 | 1162 | # by %who |
|
1163 | 1163 | self.user_ns_hidden.update(ns) |
|
1164 | 1164 | |
|
1165 | 1165 | # Anything put into ns now would show up in %who. Think twice before |
|
1166 | 1166 | # putting anything here, as we really want %who to show the user their |
|
1167 | 1167 | # stuff, not our variables. |
|
1168 | 1168 | |
|
1169 | 1169 | # Finally, update the real user's namespace |
|
1170 | 1170 | self.user_ns.update(ns) |
|
1171 | 1171 | |
|
1172 | 1172 | @property |
|
1173 | 1173 | def all_ns_refs(self): |
|
1174 | 1174 | """Get a list of references to all the namespace dictionaries in which |
|
1175 | 1175 | IPython might store a user-created object. |
|
1176 | 1176 | |
|
1177 | 1177 | Note that this does not include the displayhook, which also caches |
|
1178 | 1178 | objects from the output.""" |
|
1179 | 1179 | return [self.user_ns, self.user_global_ns, |
|
1180 | 1180 | self._user_main_module.__dict__] + self._main_ns_cache.values() |
|
1181 | 1181 | |
|
1182 | 1182 | def reset(self, new_session=True): |
|
1183 | 1183 | """Clear all internal namespaces, and attempt to release references to |
|
1184 | 1184 | user objects. |
|
1185 | 1185 | |
|
1186 | 1186 | If new_session is True, a new history session will be opened. |
|
1187 | 1187 | """ |
|
1188 | 1188 | # Clear histories |
|
1189 | 1189 | self.history_manager.reset(new_session) |
|
1190 | 1190 | # Reset counter used to index all histories |
|
1191 | 1191 | if new_session: |
|
1192 | 1192 | self.execution_count = 1 |
|
1193 | 1193 | |
|
1194 | 1194 | # Flush cached output items |
|
1195 | 1195 | if self.displayhook.do_full_cache: |
|
1196 | 1196 | self.displayhook.flush() |
|
1197 | 1197 | |
|
1198 | 1198 | # The main execution namespaces must be cleared very carefully, |
|
1199 | 1199 | # skipping the deletion of the builtin-related keys, because doing so |
|
1200 | 1200 | # would cause errors in many object's __del__ methods. |
|
1201 | 1201 | if self.user_ns is not self.user_global_ns: |
|
1202 | 1202 | self.user_ns.clear() |
|
1203 | 1203 | ns = self.user_global_ns |
|
1204 | 1204 | drop_keys = set(ns.keys()) |
|
1205 | 1205 | drop_keys.discard('__builtin__') |
|
1206 | 1206 | drop_keys.discard('__builtins__') |
|
1207 | 1207 | drop_keys.discard('__name__') |
|
1208 | 1208 | for k in drop_keys: |
|
1209 | 1209 | del ns[k] |
|
1210 | 1210 | |
|
1211 | 1211 | self.user_ns_hidden.clear() |
|
1212 | 1212 | |
|
1213 | 1213 | # Restore the user namespaces to minimal usability |
|
1214 | 1214 | self.init_user_ns() |
|
1215 | 1215 | |
|
1216 | 1216 | # Restore the default and user aliases |
|
1217 | 1217 | self.alias_manager.clear_aliases() |
|
1218 | 1218 | self.alias_manager.init_aliases() |
|
1219 | 1219 | |
|
1220 | 1220 | # Flush the private list of module references kept for script |
|
1221 | 1221 | # execution protection |
|
1222 | 1222 | self.clear_main_mod_cache() |
|
1223 | 1223 | |
|
1224 | 1224 | # Clear out the namespace from the last %run |
|
1225 | 1225 | self.new_main_mod() |
|
1226 | 1226 | |
|
1227 | 1227 | def del_var(self, varname, by_name=False): |
|
1228 | 1228 | """Delete a variable from the various namespaces, so that, as |
|
1229 | 1229 | far as possible, we're not keeping any hidden references to it. |
|
1230 | 1230 | |
|
1231 | 1231 | Parameters |
|
1232 | 1232 | ---------- |
|
1233 | 1233 | varname : str |
|
1234 | 1234 | The name of the variable to delete. |
|
1235 | 1235 | by_name : bool |
|
1236 | 1236 | If True, delete variables with the given name in each |
|
1237 | 1237 | namespace. If False (default), find the variable in the user |
|
1238 | 1238 | namespace, and delete references to it. |
|
1239 | 1239 | """ |
|
1240 | 1240 | if varname in ('__builtin__', '__builtins__'): |
|
1241 | 1241 | raise ValueError("Refusing to delete %s" % varname) |
|
1242 | 1242 | |
|
1243 | 1243 | ns_refs = self.all_ns_refs |
|
1244 | 1244 | |
|
1245 | 1245 | if by_name: # Delete by name |
|
1246 | 1246 | for ns in ns_refs: |
|
1247 | 1247 | try: |
|
1248 | 1248 | del ns[varname] |
|
1249 | 1249 | except KeyError: |
|
1250 | 1250 | pass |
|
1251 | 1251 | else: # Delete by object |
|
1252 | 1252 | try: |
|
1253 | 1253 | obj = self.user_ns[varname] |
|
1254 | 1254 | except KeyError: |
|
1255 | 1255 | raise NameError("name '%s' is not defined" % varname) |
|
1256 | 1256 | # Also check in output history |
|
1257 | 1257 | ns_refs.append(self.history_manager.output_hist) |
|
1258 | 1258 | for ns in ns_refs: |
|
1259 | 1259 | to_delete = [n for n, o in ns.iteritems() if o is obj] |
|
1260 | 1260 | for name in to_delete: |
|
1261 | 1261 | del ns[name] |
|
1262 | 1262 | |
|
1263 | 1263 | # displayhook keeps extra references, but not in a dictionary |
|
1264 | 1264 | for name in ('_', '__', '___'): |
|
1265 | 1265 | if getattr(self.displayhook, name) is obj: |
|
1266 | 1266 | setattr(self.displayhook, name, None) |
|
1267 | 1267 | |
|
1268 | 1268 | def reset_selective(self, regex=None): |
|
1269 | 1269 | """Clear selective variables from internal namespaces based on a |
|
1270 | 1270 | specified regular expression. |
|
1271 | 1271 | |
|
1272 | 1272 | Parameters |
|
1273 | 1273 | ---------- |
|
1274 | 1274 | regex : string or compiled pattern, optional |
|
1275 | 1275 | A regular expression pattern that will be used in searching |
|
1276 | 1276 | variable names in the users namespaces. |
|
1277 | 1277 | """ |
|
1278 | 1278 | if regex is not None: |
|
1279 | 1279 | try: |
|
1280 | 1280 | m = re.compile(regex) |
|
1281 | 1281 | except TypeError: |
|
1282 | 1282 | raise TypeError('regex must be a string or compiled pattern') |
|
1283 | 1283 | # Search for keys in each namespace that match the given regex |
|
1284 | 1284 | # If a match is found, delete the key/value pair. |
|
1285 | 1285 | for ns in self.all_ns_refs: |
|
1286 | 1286 | for var in ns: |
|
1287 | 1287 | if m.search(var): |
|
1288 | 1288 | del ns[var] |
|
1289 | 1289 | |
|
1290 | 1290 | def push(self, variables, interactive=True): |
|
1291 | 1291 | """Inject a group of variables into the IPython user namespace. |
|
1292 | 1292 | |
|
1293 | 1293 | Parameters |
|
1294 | 1294 | ---------- |
|
1295 | 1295 | variables : dict, str or list/tuple of str |
|
1296 | 1296 | The variables to inject into the user's namespace. If a dict, a |
|
1297 | 1297 | simple update is done. If a str, the string is assumed to have |
|
1298 | 1298 | variable names separated by spaces. A list/tuple of str can also |
|
1299 | 1299 | be used to give the variable names. If just the variable names are |
|
1300 | 1300 | give (list/tuple/str) then the variable values looked up in the |
|
1301 | 1301 | callers frame. |
|
1302 | 1302 | interactive : bool |
|
1303 | 1303 | If True (default), the variables will be listed with the ``who`` |
|
1304 | 1304 | magic. |
|
1305 | 1305 | """ |
|
1306 | 1306 | vdict = None |
|
1307 | 1307 | |
|
1308 | 1308 | # We need a dict of name/value pairs to do namespace updates. |
|
1309 | 1309 | if isinstance(variables, dict): |
|
1310 | 1310 | vdict = variables |
|
1311 | 1311 | elif isinstance(variables, (basestring, list, tuple)): |
|
1312 | 1312 | if isinstance(variables, basestring): |
|
1313 | 1313 | vlist = variables.split() |
|
1314 | 1314 | else: |
|
1315 | 1315 | vlist = variables |
|
1316 | 1316 | vdict = {} |
|
1317 | 1317 | cf = sys._getframe(1) |
|
1318 | 1318 | for name in vlist: |
|
1319 | 1319 | try: |
|
1320 | 1320 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1321 | 1321 | except: |
|
1322 | 1322 | print('Could not get variable %s from %s' % |
|
1323 | 1323 | (name,cf.f_code.co_name)) |
|
1324 | 1324 | else: |
|
1325 | 1325 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1326 | 1326 | |
|
1327 | 1327 | # Propagate variables to user namespace |
|
1328 | 1328 | self.user_ns.update(vdict) |
|
1329 | 1329 | |
|
1330 | 1330 | # And configure interactive visibility |
|
1331 | 1331 | user_ns_hidden = self.user_ns_hidden |
|
1332 | 1332 | if interactive: |
|
1333 | 1333 | user_ns_hidden.difference_update(vdict) |
|
1334 | 1334 | else: |
|
1335 | 1335 | user_ns_hidden.update(vdict) |
|
1336 | 1336 | |
|
1337 | 1337 | def drop_by_id(self, variables): |
|
1338 | 1338 | """Remove a dict of variables from the user namespace, if they are the |
|
1339 | 1339 | same as the values in the dictionary. |
|
1340 | 1340 | |
|
1341 | 1341 | This is intended for use by extensions: variables that they've added can |
|
1342 | 1342 | be taken back out if they are unloaded, without removing any that the |
|
1343 | 1343 | user has overwritten. |
|
1344 | 1344 | |
|
1345 | 1345 | Parameters |
|
1346 | 1346 | ---------- |
|
1347 | 1347 | variables : dict |
|
1348 | 1348 | A dictionary mapping object names (as strings) to the objects. |
|
1349 | 1349 | """ |
|
1350 | 1350 | for name, obj in variables.iteritems(): |
|
1351 | 1351 | if name in self.user_ns and self.user_ns[name] is obj: |
|
1352 | 1352 | del self.user_ns[name] |
|
1353 | 1353 | self.user_ns_hidden.discard(name) |
|
1354 | 1354 | |
|
1355 | 1355 | #------------------------------------------------------------------------- |
|
1356 | 1356 | # Things related to object introspection |
|
1357 | 1357 | #------------------------------------------------------------------------- |
|
1358 | 1358 | |
|
1359 | 1359 | def _ofind(self, oname, namespaces=None): |
|
1360 | 1360 | """Find an object in the available namespaces. |
|
1361 | 1361 | |
|
1362 | 1362 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
1363 | 1363 | |
|
1364 | 1364 | Has special code to detect magic functions. |
|
1365 | 1365 | """ |
|
1366 | 1366 | oname = oname.strip() |
|
1367 | 1367 | #print '1- oname: <%r>' % oname # dbg |
|
1368 | 1368 | if not oname.startswith(ESC_MAGIC) and \ |
|
1369 | 1369 | not oname.startswith(ESC_MAGIC2) and \ |
|
1370 | 1370 | not py3compat.isidentifier(oname, dotted=True): |
|
1371 | 1371 | return dict(found=False) |
|
1372 | 1372 | |
|
1373 | 1373 | alias_ns = None |
|
1374 | 1374 | if namespaces is None: |
|
1375 | 1375 | # Namespaces to search in: |
|
1376 | 1376 | # Put them in a list. The order is important so that we |
|
1377 | 1377 | # find things in the same order that Python finds them. |
|
1378 | 1378 | namespaces = [ ('Interactive', self.user_ns), |
|
1379 | 1379 | ('Interactive (global)', self.user_global_ns), |
|
1380 | 1380 | ('Python builtin', builtin_mod.__dict__), |
|
1381 | 1381 | ('Alias', self.alias_manager.alias_table), |
|
1382 | 1382 | ] |
|
1383 | 1383 | alias_ns = self.alias_manager.alias_table |
|
1384 | 1384 | |
|
1385 | 1385 | # initialize results to 'null' |
|
1386 | 1386 | found = False; obj = None; ospace = None; ds = None; |
|
1387 | 1387 | ismagic = False; isalias = False; parent = None |
|
1388 | 1388 | |
|
1389 | 1389 | # We need to special-case 'print', which as of python2.6 registers as a |
|
1390 | 1390 | # function but should only be treated as one if print_function was |
|
1391 | 1391 | # loaded with a future import. In this case, just bail. |
|
1392 | 1392 | if (oname == 'print' and not py3compat.PY3 and not \ |
|
1393 | 1393 | (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)): |
|
1394 | 1394 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1395 | 1395 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1396 | 1396 | |
|
1397 | 1397 | # Look for the given name by splitting it in parts. If the head is |
|
1398 | 1398 | # found, then we look for all the remaining parts as members, and only |
|
1399 | 1399 | # declare success if we can find them all. |
|
1400 | 1400 | oname_parts = oname.split('.') |
|
1401 | 1401 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
1402 | 1402 | for nsname,ns in namespaces: |
|
1403 | 1403 | try: |
|
1404 | 1404 | obj = ns[oname_head] |
|
1405 | 1405 | except KeyError: |
|
1406 | 1406 | continue |
|
1407 | 1407 | else: |
|
1408 | 1408 | #print 'oname_rest:', oname_rest # dbg |
|
1409 | 1409 | for part in oname_rest: |
|
1410 | 1410 | try: |
|
1411 | 1411 | parent = obj |
|
1412 | 1412 | obj = getattr(obj,part) |
|
1413 | 1413 | except: |
|
1414 | 1414 | # Blanket except b/c some badly implemented objects |
|
1415 | 1415 | # allow __getattr__ to raise exceptions other than |
|
1416 | 1416 | # AttributeError, which then crashes IPython. |
|
1417 | 1417 | break |
|
1418 | 1418 | else: |
|
1419 | 1419 | # If we finish the for loop (no break), we got all members |
|
1420 | 1420 | found = True |
|
1421 | 1421 | ospace = nsname |
|
1422 | 1422 | if ns == alias_ns: |
|
1423 | 1423 | isalias = True |
|
1424 | 1424 | break # namespace loop |
|
1425 | 1425 | |
|
1426 | 1426 | # Try to see if it's magic |
|
1427 | 1427 | if not found: |
|
1428 | 1428 | obj = None |
|
1429 | 1429 | if oname.startswith(ESC_MAGIC2): |
|
1430 | 1430 | oname = oname.lstrip(ESC_MAGIC2) |
|
1431 | 1431 | obj = self.find_cell_magic(oname) |
|
1432 | 1432 | elif oname.startswith(ESC_MAGIC): |
|
1433 | 1433 | oname = oname.lstrip(ESC_MAGIC) |
|
1434 | 1434 | obj = self.find_line_magic(oname) |
|
1435 | 1435 | else: |
|
1436 | 1436 | # search without prefix, so run? will find %run? |
|
1437 | 1437 | obj = self.find_line_magic(oname) |
|
1438 | 1438 | if obj is None: |
|
1439 | 1439 | obj = self.find_cell_magic(oname) |
|
1440 | 1440 | if obj is not None: |
|
1441 | 1441 | found = True |
|
1442 | 1442 | ospace = 'IPython internal' |
|
1443 | 1443 | ismagic = True |
|
1444 | 1444 | |
|
1445 | 1445 | # Last try: special-case some literals like '', [], {}, etc: |
|
1446 | 1446 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
1447 | 1447 | obj = eval(oname_head) |
|
1448 | 1448 | found = True |
|
1449 | 1449 | ospace = 'Interactive' |
|
1450 | 1450 | |
|
1451 | 1451 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1452 | 1452 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1453 | 1453 | |
|
1454 | 1454 | def _ofind_property(self, oname, info): |
|
1455 | 1455 | """Second part of object finding, to look for property details.""" |
|
1456 | 1456 | if info.found: |
|
1457 | 1457 | # Get the docstring of the class property if it exists. |
|
1458 | 1458 | path = oname.split('.') |
|
1459 | 1459 | root = '.'.join(path[:-1]) |
|
1460 | 1460 | if info.parent is not None: |
|
1461 | 1461 | try: |
|
1462 | 1462 | target = getattr(info.parent, '__class__') |
|
1463 | 1463 | # The object belongs to a class instance. |
|
1464 | 1464 | try: |
|
1465 | 1465 | target = getattr(target, path[-1]) |
|
1466 | 1466 | # The class defines the object. |
|
1467 | 1467 | if isinstance(target, property): |
|
1468 | 1468 | oname = root + '.__class__.' + path[-1] |
|
1469 | 1469 | info = Struct(self._ofind(oname)) |
|
1470 | 1470 | except AttributeError: pass |
|
1471 | 1471 | except AttributeError: pass |
|
1472 | 1472 | |
|
1473 | 1473 | # We return either the new info or the unmodified input if the object |
|
1474 | 1474 | # hadn't been found |
|
1475 | 1475 | return info |
|
1476 | 1476 | |
|
1477 | 1477 | def _object_find(self, oname, namespaces=None): |
|
1478 | 1478 | """Find an object and return a struct with info about it.""" |
|
1479 | 1479 | inf = Struct(self._ofind(oname, namespaces)) |
|
1480 | 1480 | return Struct(self._ofind_property(oname, inf)) |
|
1481 | 1481 | |
|
1482 | 1482 | def _inspect(self, meth, oname, namespaces=None, **kw): |
|
1483 | 1483 | """Generic interface to the inspector system. |
|
1484 | 1484 | |
|
1485 | 1485 | This function is meant to be called by pdef, pdoc & friends.""" |
|
1486 | 1486 | info = self._object_find(oname) |
|
1487 | 1487 | if info.found: |
|
1488 | 1488 | pmethod = getattr(self.inspector, meth) |
|
1489 | 1489 | formatter = format_screen if info.ismagic else None |
|
1490 | 1490 | if meth == 'pdoc': |
|
1491 | 1491 | pmethod(info.obj, oname, formatter) |
|
1492 | 1492 | elif meth == 'pinfo': |
|
1493 | 1493 | pmethod(info.obj, oname, formatter, info, **kw) |
|
1494 | 1494 | else: |
|
1495 | 1495 | pmethod(info.obj, oname) |
|
1496 | 1496 | else: |
|
1497 | 1497 | print('Object `%s` not found.' % oname) |
|
1498 | 1498 | return 'not found' # so callers can take other action |
|
1499 | 1499 | |
|
1500 | 1500 | def object_inspect(self, oname, detail_level=0): |
|
1501 | 1501 | with self.builtin_trap: |
|
1502 | 1502 | info = self._object_find(oname) |
|
1503 | 1503 | if info.found: |
|
1504 | 1504 | return self.inspector.info(info.obj, oname, info=info, |
|
1505 | 1505 | detail_level=detail_level |
|
1506 | 1506 | ) |
|
1507 | 1507 | else: |
|
1508 | 1508 | return oinspect.object_info(name=oname, found=False) |
|
1509 | 1509 | |
|
1510 | 1510 | #------------------------------------------------------------------------- |
|
1511 | 1511 | # Things related to history management |
|
1512 | 1512 | #------------------------------------------------------------------------- |
|
1513 | 1513 | |
|
1514 | 1514 | def init_history(self): |
|
1515 | 1515 | """Sets up the command history, and starts regular autosaves.""" |
|
1516 | 1516 | self.history_manager = HistoryManager(shell=self, config=self.config) |
|
1517 | 1517 | self.configurables.append(self.history_manager) |
|
1518 | 1518 | |
|
1519 | 1519 | #------------------------------------------------------------------------- |
|
1520 | 1520 | # Things related to exception handling and tracebacks (not debugging) |
|
1521 | 1521 | #------------------------------------------------------------------------- |
|
1522 | 1522 | |
|
1523 | 1523 | def init_traceback_handlers(self, custom_exceptions): |
|
1524 | 1524 | # Syntax error handler. |
|
1525 | 1525 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') |
|
1526 | 1526 | |
|
1527 | 1527 | # The interactive one is initialized with an offset, meaning we always |
|
1528 | 1528 | # want to remove the topmost item in the traceback, which is our own |
|
1529 | 1529 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1530 | 1530 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1531 | 1531 | color_scheme='NoColor', |
|
1532 | 1532 | tb_offset = 1, |
|
1533 | 1533 | check_cache=self.compile.check_cache) |
|
1534 | 1534 | |
|
1535 | 1535 | # The instance will store a pointer to the system-wide exception hook, |
|
1536 | 1536 | # so that runtime code (such as magics) can access it. This is because |
|
1537 | 1537 | # during the read-eval loop, it may get temporarily overwritten. |
|
1538 | 1538 | self.sys_excepthook = sys.excepthook |
|
1539 | 1539 | |
|
1540 | 1540 | # and add any custom exception handlers the user may have specified |
|
1541 | 1541 | self.set_custom_exc(*custom_exceptions) |
|
1542 | 1542 | |
|
1543 | 1543 | # Set the exception mode |
|
1544 | 1544 | self.InteractiveTB.set_mode(mode=self.xmode) |
|
1545 | 1545 | |
|
1546 | 1546 | def set_custom_exc(self, exc_tuple, handler): |
|
1547 | 1547 | """set_custom_exc(exc_tuple,handler) |
|
1548 | 1548 | |
|
1549 | 1549 | Set a custom exception handler, which will be called if any of the |
|
1550 | 1550 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1551 | 1551 | run_code() method). |
|
1552 | 1552 | |
|
1553 | 1553 | Parameters |
|
1554 | 1554 | ---------- |
|
1555 | 1555 | |
|
1556 | 1556 | exc_tuple : tuple of exception classes |
|
1557 | 1557 | A *tuple* of exception classes, for which to call the defined |
|
1558 | 1558 | handler. It is very important that you use a tuple, and NOT A |
|
1559 | 1559 | LIST here, because of the way Python's except statement works. If |
|
1560 | 1560 | you only want to trap a single exception, use a singleton tuple:: |
|
1561 | 1561 | |
|
1562 | 1562 | exc_tuple == (MyCustomException,) |
|
1563 | 1563 | |
|
1564 | 1564 | handler : callable |
|
1565 | 1565 | handler must have the following signature:: |
|
1566 | 1566 | |
|
1567 | 1567 | def my_handler(self, etype, value, tb, tb_offset=None): |
|
1568 | 1568 | ... |
|
1569 | 1569 | return structured_traceback |
|
1570 | 1570 | |
|
1571 | 1571 | Your handler must return a structured traceback (a list of strings), |
|
1572 | 1572 | or None. |
|
1573 | 1573 | |
|
1574 | 1574 | This will be made into an instance method (via types.MethodType) |
|
1575 | 1575 | of IPython itself, and it will be called if any of the exceptions |
|
1576 | 1576 | listed in the exc_tuple are caught. If the handler is None, an |
|
1577 | 1577 | internal basic one is used, which just prints basic info. |
|
1578 | 1578 | |
|
1579 | 1579 | To protect IPython from crashes, if your handler ever raises an |
|
1580 | 1580 | exception or returns an invalid result, it will be immediately |
|
1581 | 1581 | disabled. |
|
1582 | 1582 | |
|
1583 | 1583 | WARNING: by putting in your own exception handler into IPython's main |
|
1584 | 1584 | execution loop, you run a very good chance of nasty crashes. This |
|
1585 | 1585 | facility should only be used if you really know what you are doing.""" |
|
1586 | 1586 | |
|
1587 | 1587 | assert type(exc_tuple)==type(()) , \ |
|
1588 | 1588 | "The custom exceptions must be given AS A TUPLE." |
|
1589 | 1589 | |
|
1590 | 1590 | def dummy_handler(self,etype,value,tb,tb_offset=None): |
|
1591 | 1591 | print('*** Simple custom exception handler ***') |
|
1592 | 1592 | print('Exception type :',etype) |
|
1593 | 1593 | print('Exception value:',value) |
|
1594 | 1594 | print('Traceback :',tb) |
|
1595 | 1595 | #print 'Source code :','\n'.join(self.buffer) |
|
1596 | 1596 | |
|
1597 | 1597 | def validate_stb(stb): |
|
1598 | 1598 | """validate structured traceback return type |
|
1599 | 1599 | |
|
1600 | 1600 | return type of CustomTB *should* be a list of strings, but allow |
|
1601 | 1601 | single strings or None, which are harmless. |
|
1602 | 1602 | |
|
1603 | 1603 | This function will *always* return a list of strings, |
|
1604 | 1604 | and will raise a TypeError if stb is inappropriate. |
|
1605 | 1605 | """ |
|
1606 | 1606 | msg = "CustomTB must return list of strings, not %r" % stb |
|
1607 | 1607 | if stb is None: |
|
1608 | 1608 | return [] |
|
1609 | 1609 | elif isinstance(stb, basestring): |
|
1610 | 1610 | return [stb] |
|
1611 | 1611 | elif not isinstance(stb, list): |
|
1612 | 1612 | raise TypeError(msg) |
|
1613 | 1613 | # it's a list |
|
1614 | 1614 | for line in stb: |
|
1615 | 1615 | # check every element |
|
1616 | 1616 | if not isinstance(line, basestring): |
|
1617 | 1617 | raise TypeError(msg) |
|
1618 | 1618 | return stb |
|
1619 | 1619 | |
|
1620 | 1620 | if handler is None: |
|
1621 | 1621 | wrapped = dummy_handler |
|
1622 | 1622 | else: |
|
1623 | 1623 | def wrapped(self,etype,value,tb,tb_offset=None): |
|
1624 | 1624 | """wrap CustomTB handler, to protect IPython from user code |
|
1625 | 1625 | |
|
1626 | 1626 | This makes it harder (but not impossible) for custom exception |
|
1627 | 1627 | handlers to crash IPython. |
|
1628 | 1628 | """ |
|
1629 | 1629 | try: |
|
1630 | 1630 | stb = handler(self,etype,value,tb,tb_offset=tb_offset) |
|
1631 | 1631 | return validate_stb(stb) |
|
1632 | 1632 | except: |
|
1633 | 1633 | # clear custom handler immediately |
|
1634 | 1634 | self.set_custom_exc((), None) |
|
1635 | 1635 | print("Custom TB Handler failed, unregistering", file=io.stderr) |
|
1636 | 1636 | # show the exception in handler first |
|
1637 | 1637 | stb = self.InteractiveTB.structured_traceback(*sys.exc_info()) |
|
1638 | 1638 | print(self.InteractiveTB.stb2text(stb), file=io.stdout) |
|
1639 | 1639 | print("The original exception:", file=io.stdout) |
|
1640 | 1640 | stb = self.InteractiveTB.structured_traceback( |
|
1641 | 1641 | (etype,value,tb), tb_offset=tb_offset |
|
1642 | 1642 | ) |
|
1643 | 1643 | return stb |
|
1644 | 1644 | |
|
1645 | 1645 | self.CustomTB = types.MethodType(wrapped,self) |
|
1646 | 1646 | self.custom_exceptions = exc_tuple |
|
1647 | 1647 | |
|
1648 | 1648 | def excepthook(self, etype, value, tb): |
|
1649 | 1649 | """One more defense for GUI apps that call sys.excepthook. |
|
1650 | 1650 | |
|
1651 | 1651 | GUI frameworks like wxPython trap exceptions and call |
|
1652 | 1652 | sys.excepthook themselves. I guess this is a feature that |
|
1653 | 1653 | enables them to keep running after exceptions that would |
|
1654 | 1654 | otherwise kill their mainloop. This is a bother for IPython |
|
1655 | 1655 | which excepts to catch all of the program exceptions with a try: |
|
1656 | 1656 | except: statement. |
|
1657 | 1657 | |
|
1658 | 1658 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1659 | 1659 | any app directly invokes sys.excepthook, it will look to the user like |
|
1660 | 1660 | IPython crashed. In order to work around this, we can disable the |
|
1661 | 1661 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1662 | 1662 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1663 | 1663 | call sys.excepthook will generate a regular-looking exception from |
|
1664 | 1664 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1665 | 1665 | crashes. |
|
1666 | 1666 | |
|
1667 | 1667 | This hook should be used sparingly, only in places which are not likely |
|
1668 | 1668 | to be true IPython errors. |
|
1669 | 1669 | """ |
|
1670 | 1670 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1671 | 1671 | |
|
1672 | 1672 | def _get_exc_info(self, exc_tuple=None): |
|
1673 | 1673 | """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc. |
|
1674 | 1674 | |
|
1675 | 1675 | Ensures sys.last_type,value,traceback hold the exc_info we found, |
|
1676 | 1676 | from whichever source. |
|
1677 | 1677 | |
|
1678 | 1678 | raises ValueError if none of these contain any information |
|
1679 | 1679 | """ |
|
1680 | 1680 | if exc_tuple is None: |
|
1681 | 1681 | etype, value, tb = sys.exc_info() |
|
1682 | 1682 | else: |
|
1683 | 1683 | etype, value, tb = exc_tuple |
|
1684 | 1684 | |
|
1685 | 1685 | if etype is None: |
|
1686 | 1686 | if hasattr(sys, 'last_type'): |
|
1687 | 1687 | etype, value, tb = sys.last_type, sys.last_value, \ |
|
1688 | 1688 | sys.last_traceback |
|
1689 | 1689 | |
|
1690 | 1690 | if etype is None: |
|
1691 | 1691 | raise ValueError("No exception to find") |
|
1692 | 1692 | |
|
1693 | 1693 | # Now store the exception info in sys.last_type etc. |
|
1694 | 1694 | # WARNING: these variables are somewhat deprecated and not |
|
1695 | 1695 | # necessarily safe to use in a threaded environment, but tools |
|
1696 | 1696 | # like pdb depend on their existence, so let's set them. If we |
|
1697 | 1697 | # find problems in the field, we'll need to revisit their use. |
|
1698 | 1698 | sys.last_type = etype |
|
1699 | 1699 | sys.last_value = value |
|
1700 | 1700 | sys.last_traceback = tb |
|
1701 | 1701 | |
|
1702 | 1702 | return etype, value, tb |
|
1703 | 1703 | |
|
1704 | 1704 | |
|
1705 | 1705 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, |
|
1706 | 1706 | exception_only=False): |
|
1707 | 1707 | """Display the exception that just occurred. |
|
1708 | 1708 | |
|
1709 | 1709 | If nothing is known about the exception, this is the method which |
|
1710 | 1710 | should be used throughout the code for presenting user tracebacks, |
|
1711 | 1711 | rather than directly invoking the InteractiveTB object. |
|
1712 | 1712 | |
|
1713 | 1713 | A specific showsyntaxerror() also exists, but this method can take |
|
1714 | 1714 | care of calling it if needed, so unless you are explicitly catching a |
|
1715 | 1715 | SyntaxError exception, don't try to analyze the stack manually and |
|
1716 | 1716 | simply call this method.""" |
|
1717 | 1717 | |
|
1718 | 1718 | try: |
|
1719 | 1719 | try: |
|
1720 | 1720 | etype, value, tb = self._get_exc_info(exc_tuple) |
|
1721 | 1721 | except ValueError: |
|
1722 | 1722 | self.write_err('No traceback available to show.\n') |
|
1723 | 1723 | return |
|
1724 | 1724 | |
|
1725 | 1725 | if etype is SyntaxError: |
|
1726 | 1726 | # Though this won't be called by syntax errors in the input |
|
1727 | 1727 | # line, there may be SyntaxError cases with imported code. |
|
1728 | 1728 | self.showsyntaxerror(filename) |
|
1729 | 1729 | elif etype is UsageError: |
|
1730 | 1730 | self.write_err("UsageError: %s" % value) |
|
1731 | 1731 | elif issubclass(etype, RemoteError): |
|
1732 | 1732 | # IPython.parallel remote exceptions. |
|
1733 | 1733 | # Draw the remote traceback, not the local one. |
|
1734 | 1734 | self._showtraceback(etype, value, value.render_traceback()) |
|
1735 | 1735 | else: |
|
1736 | 1736 | if exception_only: |
|
1737 | 1737 | stb = ['An exception has occurred, use %tb to see ' |
|
1738 | 1738 | 'the full traceback.\n'] |
|
1739 | 1739 | stb.extend(self.InteractiveTB.get_exception_only(etype, |
|
1740 | 1740 | value)) |
|
1741 | 1741 | else: |
|
1742 | 1742 | stb = self.InteractiveTB.structured_traceback(etype, |
|
1743 | 1743 | value, tb, tb_offset=tb_offset) |
|
1744 | 1744 | |
|
1745 | 1745 | self._showtraceback(etype, value, stb) |
|
1746 | 1746 | if self.call_pdb: |
|
1747 | 1747 | # drop into debugger |
|
1748 | 1748 | self.debugger(force=True) |
|
1749 | 1749 | return |
|
1750 | 1750 | |
|
1751 | 1751 | # Actually show the traceback |
|
1752 | 1752 | self._showtraceback(etype, value, stb) |
|
1753 | 1753 | |
|
1754 | 1754 | except KeyboardInterrupt: |
|
1755 | 1755 | self.write_err("\nKeyboardInterrupt\n") |
|
1756 | 1756 | |
|
1757 | 1757 | def _showtraceback(self, etype, evalue, stb): |
|
1758 | 1758 | """Actually show a traceback. |
|
1759 | 1759 | |
|
1760 | 1760 | Subclasses may override this method to put the traceback on a different |
|
1761 | 1761 | place, like a side channel. |
|
1762 | 1762 | """ |
|
1763 | 1763 | print(self.InteractiveTB.stb2text(stb), file=io.stdout) |
|
1764 | 1764 | |
|
1765 | 1765 | def showsyntaxerror(self, filename=None): |
|
1766 | 1766 | """Display the syntax error that just occurred. |
|
1767 | 1767 | |
|
1768 | 1768 | This doesn't display a stack trace because there isn't one. |
|
1769 | 1769 | |
|
1770 | 1770 | If a filename is given, it is stuffed in the exception instead |
|
1771 | 1771 | of what was there before (because Python's parser always uses |
|
1772 | 1772 | "<string>" when reading from a string). |
|
1773 | 1773 | """ |
|
1774 | 1774 | etype, value, last_traceback = self._get_exc_info() |
|
1775 | 1775 | |
|
1776 | 1776 | if filename and etype is SyntaxError: |
|
1777 | 1777 | try: |
|
1778 | 1778 | value.filename = filename |
|
1779 | 1779 | except: |
|
1780 | 1780 | # Not the format we expect; leave it alone |
|
1781 | 1781 | pass |
|
1782 | 1782 | |
|
1783 | 1783 | stb = self.SyntaxTB.structured_traceback(etype, value, []) |
|
1784 | 1784 | self._showtraceback(etype, value, stb) |
|
1785 | 1785 | |
|
1786 | 1786 | # This is overridden in TerminalInteractiveShell to show a message about |
|
1787 | 1787 | # the %paste magic. |
|
1788 | 1788 | def showindentationerror(self): |
|
1789 | 1789 | """Called by run_cell when there's an IndentationError in code entered |
|
1790 | 1790 | at the prompt. |
|
1791 | 1791 | |
|
1792 | 1792 | This is overridden in TerminalInteractiveShell to show a message about |
|
1793 | 1793 | the %paste magic.""" |
|
1794 | 1794 | self.showsyntaxerror() |
|
1795 | 1795 | |
|
1796 | 1796 | #------------------------------------------------------------------------- |
|
1797 | 1797 | # Things related to readline |
|
1798 | 1798 | #------------------------------------------------------------------------- |
|
1799 | 1799 | |
|
1800 | 1800 | def init_readline(self): |
|
1801 | 1801 | """Command history completion/saving/reloading.""" |
|
1802 | 1802 | |
|
1803 | 1803 | if self.readline_use: |
|
1804 | 1804 | import IPython.utils.rlineimpl as readline |
|
1805 | 1805 | |
|
1806 | 1806 | self.rl_next_input = None |
|
1807 | 1807 | self.rl_do_indent = False |
|
1808 | 1808 | |
|
1809 | 1809 | if not self.readline_use or not readline.have_readline: |
|
1810 | 1810 | self.has_readline = False |
|
1811 | 1811 | self.readline = None |
|
1812 | 1812 | # Set a number of methods that depend on readline to be no-op |
|
1813 | 1813 | self.readline_no_record = no_op_context |
|
1814 | 1814 | self.set_readline_completer = no_op |
|
1815 | 1815 | self.set_custom_completer = no_op |
|
1816 | 1816 | self.set_completer_frame = no_op |
|
1817 | 1817 | if self.readline_use: |
|
1818 | 1818 | warn('Readline services not available or not loaded.') |
|
1819 | 1819 | else: |
|
1820 | 1820 | self.has_readline = True |
|
1821 | 1821 | self.readline = readline |
|
1822 | 1822 | sys.modules['readline'] = readline |
|
1823 | 1823 | |
|
1824 | 1824 | # Platform-specific configuration |
|
1825 | 1825 | if os.name == 'nt': |
|
1826 | 1826 | # FIXME - check with Frederick to see if we can harmonize |
|
1827 | 1827 | # naming conventions with pyreadline to avoid this |
|
1828 | 1828 | # platform-dependent check |
|
1829 | 1829 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1830 | 1830 | else: |
|
1831 | 1831 | self.readline_startup_hook = readline.set_startup_hook |
|
1832 | 1832 | |
|
1833 | 1833 | # Load user's initrc file (readline config) |
|
1834 | 1834 | # Or if libedit is used, load editrc. |
|
1835 | 1835 | inputrc_name = os.environ.get('INPUTRC') |
|
1836 | 1836 | if inputrc_name is None: |
|
1837 | 1837 | inputrc_name = '.inputrc' |
|
1838 | 1838 | if readline.uses_libedit: |
|
1839 | 1839 | inputrc_name = '.editrc' |
|
1840 | 1840 | inputrc_name = os.path.join(self.home_dir, inputrc_name) |
|
1841 | 1841 | if os.path.isfile(inputrc_name): |
|
1842 | 1842 | try: |
|
1843 | 1843 | readline.read_init_file(inputrc_name) |
|
1844 | 1844 | except: |
|
1845 | 1845 | warn('Problems reading readline initialization file <%s>' |
|
1846 | 1846 | % inputrc_name) |
|
1847 | 1847 | |
|
1848 | 1848 | # Configure readline according to user's prefs |
|
1849 | 1849 | # This is only done if GNU readline is being used. If libedit |
|
1850 | 1850 | # is being used (as on Leopard) the readline config is |
|
1851 | 1851 | # not run as the syntax for libedit is different. |
|
1852 | 1852 | if not readline.uses_libedit: |
|
1853 | 1853 | for rlcommand in self.readline_parse_and_bind: |
|
1854 | 1854 | #print "loading rl:",rlcommand # dbg |
|
1855 | 1855 | readline.parse_and_bind(rlcommand) |
|
1856 | 1856 | |
|
1857 | 1857 | # Remove some chars from the delimiters list. If we encounter |
|
1858 | 1858 | # unicode chars, discard them. |
|
1859 | 1859 | delims = readline.get_completer_delims() |
|
1860 | 1860 | if not py3compat.PY3: |
|
1861 | 1861 | delims = delims.encode("ascii", "ignore") |
|
1862 | 1862 | for d in self.readline_remove_delims: |
|
1863 | 1863 | delims = delims.replace(d, "") |
|
1864 | 1864 | delims = delims.replace(ESC_MAGIC, '') |
|
1865 | 1865 | readline.set_completer_delims(delims) |
|
1866 | 1866 | # otherwise we end up with a monster history after a while: |
|
1867 | 1867 | readline.set_history_length(self.history_length) |
|
1868 | 1868 | |
|
1869 | 1869 | self.refill_readline_hist() |
|
1870 | 1870 | self.readline_no_record = ReadlineNoRecord(self) |
|
1871 | 1871 | |
|
1872 | 1872 | # Configure auto-indent for all platforms |
|
1873 | 1873 | self.set_autoindent(self.autoindent) |
|
1874 | 1874 | |
|
1875 | 1875 | def refill_readline_hist(self): |
|
1876 | 1876 | # Load the last 1000 lines from history |
|
1877 | 1877 | self.readline.clear_history() |
|
1878 | 1878 | stdin_encoding = sys.stdin.encoding or "utf-8" |
|
1879 | 1879 | last_cell = u"" |
|
1880 | 1880 | for _, _, cell in self.history_manager.get_tail(1000, |
|
1881 | 1881 | include_latest=True): |
|
1882 | 1882 | # Ignore blank lines and consecutive duplicates |
|
1883 | 1883 | cell = cell.rstrip() |
|
1884 | 1884 | if cell and (cell != last_cell): |
|
1885 | 1885 | if self.multiline_history: |
|
1886 | 1886 | self.readline.add_history(py3compat.unicode_to_str(cell, |
|
1887 | 1887 | stdin_encoding)) |
|
1888 | 1888 | else: |
|
1889 | 1889 | for line in cell.splitlines(): |
|
1890 | 1890 | self.readline.add_history(py3compat.unicode_to_str(line, |
|
1891 | 1891 | stdin_encoding)) |
|
1892 | 1892 | last_cell = cell |
|
1893 | 1893 | |
|
1894 | 1894 | def set_next_input(self, s): |
|
1895 | 1895 | """ Sets the 'default' input string for the next command line. |
|
1896 | 1896 | |
|
1897 | 1897 | Requires readline. |
|
1898 | 1898 | |
|
1899 | 1899 | Example: |
|
1900 | 1900 | |
|
1901 | 1901 | [D:\ipython]|1> _ip.set_next_input("Hello Word") |
|
1902 | 1902 | [D:\ipython]|2> Hello Word_ # cursor is here |
|
1903 | 1903 | """ |
|
1904 | 1904 | self.rl_next_input = py3compat.cast_bytes_py2(s) |
|
1905 | 1905 | |
|
1906 | 1906 | # Maybe move this to the terminal subclass? |
|
1907 | 1907 | def pre_readline(self): |
|
1908 | 1908 | """readline hook to be used at the start of each line. |
|
1909 | 1909 | |
|
1910 | 1910 | Currently it handles auto-indent only.""" |
|
1911 | 1911 | |
|
1912 | 1912 | if self.rl_do_indent: |
|
1913 | 1913 | self.readline.insert_text(self._indent_current_str()) |
|
1914 | 1914 | if self.rl_next_input is not None: |
|
1915 | 1915 | self.readline.insert_text(self.rl_next_input) |
|
1916 | 1916 | self.rl_next_input = None |
|
1917 | 1917 | |
|
1918 | 1918 | def _indent_current_str(self): |
|
1919 | 1919 | """return the current level of indentation as a string""" |
|
1920 | 1920 | return self.input_splitter.indent_spaces * ' ' |
|
1921 | 1921 | |
|
1922 | 1922 | #------------------------------------------------------------------------- |
|
1923 | 1923 | # Things related to text completion |
|
1924 | 1924 | #------------------------------------------------------------------------- |
|
1925 | 1925 | |
|
1926 | 1926 | def init_completer(self): |
|
1927 | 1927 | """Initialize the completion machinery. |
|
1928 | 1928 | |
|
1929 | 1929 | This creates completion machinery that can be used by client code, |
|
1930 | 1930 | either interactively in-process (typically triggered by the readline |
|
1931 | 1931 | library), programatically (such as in test suites) or out-of-prcess |
|
1932 | 1932 | (typically over the network by remote frontends). |
|
1933 | 1933 | """ |
|
1934 | 1934 | from IPython.core.completer import IPCompleter |
|
1935 | 1935 | from IPython.core.completerlib import (module_completer, |
|
1936 | 1936 | magic_run_completer, cd_completer, reset_completer) |
|
1937 | 1937 | |
|
1938 | 1938 | self.Completer = IPCompleter(shell=self, |
|
1939 | 1939 | namespace=self.user_ns, |
|
1940 | 1940 | global_namespace=self.user_global_ns, |
|
1941 | 1941 | alias_table=self.alias_manager.alias_table, |
|
1942 | 1942 | use_readline=self.has_readline, |
|
1943 | 1943 | config=self.config, |
|
1944 | 1944 | ) |
|
1945 | 1945 | self.configurables.append(self.Completer) |
|
1946 | 1946 | |
|
1947 | 1947 | # Add custom completers to the basic ones built into IPCompleter |
|
1948 | 1948 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1949 | 1949 | self.strdispatchers['complete_command'] = sdisp |
|
1950 | 1950 | self.Completer.custom_completers = sdisp |
|
1951 | 1951 | |
|
1952 | 1952 | self.set_hook('complete_command', module_completer, str_key = 'import') |
|
1953 | 1953 | self.set_hook('complete_command', module_completer, str_key = 'from') |
|
1954 | 1954 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') |
|
1955 | 1955 | self.set_hook('complete_command', cd_completer, str_key = '%cd') |
|
1956 | 1956 | self.set_hook('complete_command', reset_completer, str_key = '%reset') |
|
1957 | 1957 | |
|
1958 | 1958 | # Only configure readline if we truly are using readline. IPython can |
|
1959 | 1959 | # do tab-completion over the network, in GUIs, etc, where readline |
|
1960 | 1960 | # itself may be absent |
|
1961 | 1961 | if self.has_readline: |
|
1962 | 1962 | self.set_readline_completer() |
|
1963 | 1963 | |
|
1964 | 1964 | def complete(self, text, line=None, cursor_pos=None): |
|
1965 | 1965 | """Return the completed text and a list of completions. |
|
1966 | 1966 | |
|
1967 | 1967 | Parameters |
|
1968 | 1968 | ---------- |
|
1969 | 1969 | |
|
1970 | 1970 | text : string |
|
1971 | 1971 | A string of text to be completed on. It can be given as empty and |
|
1972 | 1972 | instead a line/position pair are given. In this case, the |
|
1973 | 1973 | completer itself will split the line like readline does. |
|
1974 | 1974 | |
|
1975 | 1975 | line : string, optional |
|
1976 | 1976 | The complete line that text is part of. |
|
1977 | 1977 | |
|
1978 | 1978 | cursor_pos : int, optional |
|
1979 | 1979 | The position of the cursor on the input line. |
|
1980 | 1980 | |
|
1981 | 1981 | Returns |
|
1982 | 1982 | ------- |
|
1983 | 1983 | text : string |
|
1984 | 1984 | The actual text that was completed. |
|
1985 | 1985 | |
|
1986 | 1986 | matches : list |
|
1987 | 1987 | A sorted list with all possible completions. |
|
1988 | 1988 | |
|
1989 | 1989 | The optional arguments allow the completion to take more context into |
|
1990 | 1990 | account, and are part of the low-level completion API. |
|
1991 | 1991 | |
|
1992 | 1992 | This is a wrapper around the completion mechanism, similar to what |
|
1993 | 1993 | readline does at the command line when the TAB key is hit. By |
|
1994 | 1994 | exposing it as a method, it can be used by other non-readline |
|
1995 | 1995 | environments (such as GUIs) for text completion. |
|
1996 | 1996 | |
|
1997 | 1997 | Simple usage example: |
|
1998 | 1998 | |
|
1999 | 1999 | In [1]: x = 'hello' |
|
2000 | 2000 | |
|
2001 | 2001 | In [2]: _ip.complete('x.l') |
|
2002 | 2002 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) |
|
2003 | 2003 | """ |
|
2004 | 2004 | |
|
2005 | 2005 | # Inject names into __builtin__ so we can complete on the added names. |
|
2006 | 2006 | with self.builtin_trap: |
|
2007 | 2007 | return self.Completer.complete(text, line, cursor_pos) |
|
2008 | 2008 | |
|
2009 | 2009 | def set_custom_completer(self, completer, pos=0): |
|
2010 | 2010 | """Adds a new custom completer function. |
|
2011 | 2011 | |
|
2012 | 2012 | The position argument (defaults to 0) is the index in the completers |
|
2013 | 2013 | list where you want the completer to be inserted.""" |
|
2014 | 2014 | |
|
2015 | 2015 | newcomp = types.MethodType(completer,self.Completer) |
|
2016 | 2016 | self.Completer.matchers.insert(pos,newcomp) |
|
2017 | 2017 | |
|
2018 | 2018 | def set_readline_completer(self): |
|
2019 | 2019 | """Reset readline's completer to be our own.""" |
|
2020 | 2020 | self.readline.set_completer(self.Completer.rlcomplete) |
|
2021 | 2021 | |
|
2022 | 2022 | def set_completer_frame(self, frame=None): |
|
2023 | 2023 | """Set the frame of the completer.""" |
|
2024 | 2024 | if frame: |
|
2025 | 2025 | self.Completer.namespace = frame.f_locals |
|
2026 | 2026 | self.Completer.global_namespace = frame.f_globals |
|
2027 | 2027 | else: |
|
2028 | 2028 | self.Completer.namespace = self.user_ns |
|
2029 | 2029 | self.Completer.global_namespace = self.user_global_ns |
|
2030 | 2030 | |
|
2031 | 2031 | #------------------------------------------------------------------------- |
|
2032 | 2032 | # Things related to magics |
|
2033 | 2033 | #------------------------------------------------------------------------- |
|
2034 | 2034 | |
|
2035 | 2035 | def init_magics(self): |
|
2036 | 2036 | from IPython.core import magics as m |
|
2037 | 2037 | self.magics_manager = magic.MagicsManager(shell=self, |
|
2038 | 2038 | confg=self.config, |
|
2039 | 2039 | user_magics=m.UserMagics(self)) |
|
2040 | 2040 | self.configurables.append(self.magics_manager) |
|
2041 | 2041 | |
|
2042 | 2042 | # Expose as public API from the magics manager |
|
2043 | 2043 | self.register_magics = self.magics_manager.register |
|
2044 | 2044 | self.register_magic_function = self.magics_manager.register_function |
|
2045 | 2045 | self.define_magic = self.magics_manager.define_magic |
|
2046 | 2046 | |
|
2047 | 2047 | self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics, |
|
2048 | 2048 | m.ConfigMagics, m.DeprecatedMagics, m.ExecutionMagics, |
|
2049 | 2049 | m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics, |
|
2050 | 2050 | m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics, |
|
2051 | 2051 | ) |
|
2052 | 2052 | |
|
2053 | 2053 | # FIXME: Move the color initialization to the DisplayHook, which |
|
2054 | 2054 | # should be split into a prompt manager and displayhook. We probably |
|
2055 | 2055 | # even need a centralize colors management object. |
|
2056 | 2056 | self.magic('colors %s' % self.colors) |
|
2057 | 2057 | |
|
2058 | 2058 | def run_line_magic(self, magic_name, line): |
|
2059 | 2059 | """Execute the given line magic. |
|
2060 | 2060 | |
|
2061 | 2061 | Parameters |
|
2062 | 2062 | ---------- |
|
2063 | 2063 | magic_name : str |
|
2064 | 2064 | Name of the desired magic function, without '%' prefix. |
|
2065 | 2065 | |
|
2066 | 2066 | line : str |
|
2067 | 2067 | The rest of the input line as a single string. |
|
2068 | 2068 | """ |
|
2069 | 2069 | fn = self.find_line_magic(magic_name) |
|
2070 | 2070 | if fn is None: |
|
2071 | 2071 | cm = self.find_cell_magic(magic_name) |
|
2072 | 2072 | etpl = "Line magic function `%%%s` not found%s." |
|
2073 | 2073 | extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, ' |
|
2074 | 2074 | 'did you mean that instead?)' % magic_name ) |
|
2075 | 2075 | error(etpl % (magic_name, extra)) |
|
2076 | 2076 | else: |
|
2077 | 2077 | # Note: this is the distance in the stack to the user's frame. |
|
2078 | 2078 | # This will need to be updated if the internal calling logic gets |
|
2079 | 2079 | # refactored, or else we'll be expanding the wrong variables. |
|
2080 | 2080 | stack_depth = 2 |
|
2081 | 2081 | magic_arg_s = self.var_expand(line, stack_depth) |
|
2082 | 2082 | # Put magic args in a list so we can call with f(*a) syntax |
|
2083 | 2083 | args = [magic_arg_s] |
|
2084 | 2084 | # Grab local namespace if we need it: |
|
2085 | 2085 | if getattr(fn, "needs_local_scope", False): |
|
2086 | 2086 | args.append(sys._getframe(stack_depth).f_locals) |
|
2087 | 2087 | with self.builtin_trap: |
|
2088 | 2088 | result = fn(*args) |
|
2089 | 2089 | return result |
|
2090 | 2090 | |
|
2091 | 2091 | def run_cell_magic(self, magic_name, line, cell): |
|
2092 | 2092 | """Execute the given cell magic. |
|
2093 | 2093 | |
|
2094 | 2094 | Parameters |
|
2095 | 2095 | ---------- |
|
2096 | 2096 | magic_name : str |
|
2097 | 2097 | Name of the desired magic function, without '%' prefix. |
|
2098 | 2098 | |
|
2099 | 2099 | line : str |
|
2100 | 2100 | The rest of the first input line as a single string. |
|
2101 | 2101 | |
|
2102 | 2102 | cell : str |
|
2103 | 2103 | The body of the cell as a (possibly multiline) string. |
|
2104 | 2104 | """ |
|
2105 | 2105 | fn = self.find_cell_magic(magic_name) |
|
2106 | 2106 | if fn is None: |
|
2107 | 2107 | lm = self.find_line_magic(magic_name) |
|
2108 | 2108 | etpl = "Cell magic function `%%%%%s` not found%s." |
|
2109 | 2109 | extra = '' if lm is None else (' (But line magic `%%%s` exists, ' |
|
2110 | 2110 | 'did you mean that instead?)' % magic_name ) |
|
2111 | 2111 | error(etpl % (magic_name, extra)) |
|
2112 | 2112 | else: |
|
2113 | 2113 | # Note: this is the distance in the stack to the user's frame. |
|
2114 | 2114 | # This will need to be updated if the internal calling logic gets |
|
2115 | 2115 | # refactored, or else we'll be expanding the wrong variables. |
|
2116 | 2116 | stack_depth = 2 |
|
2117 | 2117 | magic_arg_s = self.var_expand(line, stack_depth) |
|
2118 | 2118 | with self.builtin_trap: |
|
2119 | 2119 | result = fn(line, cell) |
|
2120 | 2120 | return result |
|
2121 | 2121 | |
|
2122 | 2122 | def find_line_magic(self, magic_name): |
|
2123 | 2123 | """Find and return a line magic by name. |
|
2124 | 2124 | |
|
2125 | 2125 | Returns None if the magic isn't found.""" |
|
2126 | 2126 | return self.magics_manager.magics['line'].get(magic_name) |
|
2127 | 2127 | |
|
2128 | 2128 | def find_cell_magic(self, magic_name): |
|
2129 | 2129 | """Find and return a cell magic by name. |
|
2130 | 2130 | |
|
2131 | 2131 | Returns None if the magic isn't found.""" |
|
2132 | 2132 | return self.magics_manager.magics['cell'].get(magic_name) |
|
2133 | 2133 | |
|
2134 | 2134 | def find_magic(self, magic_name, magic_kind='line'): |
|
2135 | 2135 | """Find and return a magic of the given type by name. |
|
2136 | 2136 | |
|
2137 | 2137 | Returns None if the magic isn't found.""" |
|
2138 | 2138 | return self.magics_manager.magics[magic_kind].get(magic_name) |
|
2139 | 2139 | |
|
2140 | 2140 | def magic(self, arg_s): |
|
2141 | 2141 | """DEPRECATED. Use run_line_magic() instead. |
|
2142 | 2142 | |
|
2143 | 2143 | Call a magic function by name. |
|
2144 | 2144 | |
|
2145 | 2145 | Input: a string containing the name of the magic function to call and |
|
2146 | 2146 | any additional arguments to be passed to the magic. |
|
2147 | 2147 | |
|
2148 | 2148 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
2149 | 2149 | prompt: |
|
2150 | 2150 | |
|
2151 | 2151 | In[1]: %name -opt foo bar |
|
2152 | 2152 | |
|
2153 | 2153 | To call a magic without arguments, simply use magic('name'). |
|
2154 | 2154 | |
|
2155 | 2155 | This provides a proper Python function to call IPython's magics in any |
|
2156 | 2156 | valid Python code you can type at the interpreter, including loops and |
|
2157 | 2157 | compound statements. |
|
2158 | 2158 | """ |
|
2159 | 2159 | # TODO: should we issue a loud deprecation warning here? |
|
2160 | 2160 | magic_name, _, magic_arg_s = arg_s.partition(' ') |
|
2161 | 2161 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
2162 | 2162 | return self.run_line_magic(magic_name, magic_arg_s) |
|
2163 | 2163 | |
|
2164 | 2164 | #------------------------------------------------------------------------- |
|
2165 | 2165 | # Things related to macros |
|
2166 | 2166 | #------------------------------------------------------------------------- |
|
2167 | 2167 | |
|
2168 | 2168 | def define_macro(self, name, themacro): |
|
2169 | 2169 | """Define a new macro |
|
2170 | 2170 | |
|
2171 | 2171 | Parameters |
|
2172 | 2172 | ---------- |
|
2173 | 2173 | name : str |
|
2174 | 2174 | The name of the macro. |
|
2175 | 2175 | themacro : str or Macro |
|
2176 | 2176 | The action to do upon invoking the macro. If a string, a new |
|
2177 | 2177 | Macro object is created by passing the string to it. |
|
2178 | 2178 | """ |
|
2179 | 2179 | |
|
2180 | 2180 | from IPython.core import macro |
|
2181 | 2181 | |
|
2182 | 2182 | if isinstance(themacro, basestring): |
|
2183 | 2183 | themacro = macro.Macro(themacro) |
|
2184 | 2184 | if not isinstance(themacro, macro.Macro): |
|
2185 | 2185 | raise ValueError('A macro must be a string or a Macro instance.') |
|
2186 | 2186 | self.user_ns[name] = themacro |
|
2187 | 2187 | |
|
2188 | 2188 | #------------------------------------------------------------------------- |
|
2189 | 2189 | # Things related to the running of system commands |
|
2190 | 2190 | #------------------------------------------------------------------------- |
|
2191 | 2191 | |
|
2192 | 2192 | def system_piped(self, cmd): |
|
2193 | 2193 | """Call the given cmd in a subprocess, piping stdout/err |
|
2194 | 2194 | |
|
2195 | 2195 | Parameters |
|
2196 | 2196 | ---------- |
|
2197 | 2197 | cmd : str |
|
2198 | 2198 | Command to execute (can not end in '&', as background processes are |
|
2199 | 2199 | not supported. Should not be a command that expects input |
|
2200 | 2200 | other than simple text. |
|
2201 | 2201 | """ |
|
2202 | 2202 | if cmd.rstrip().endswith('&'): |
|
2203 | 2203 | # this is *far* from a rigorous test |
|
2204 | 2204 | # We do not support backgrounding processes because we either use |
|
2205 | 2205 | # pexpect or pipes to read from. Users can always just call |
|
2206 | 2206 | # os.system() or use ip.system=ip.system_raw |
|
2207 | 2207 | # if they really want a background process. |
|
2208 | 2208 | raise OSError("Background processes not supported.") |
|
2209 | 2209 | |
|
2210 | 2210 | # we explicitly do NOT return the subprocess status code, because |
|
2211 | 2211 | # a non-None value would trigger :func:`sys.displayhook` calls. |
|
2212 | 2212 | # Instead, we store the exit_code in user_ns. |
|
2213 | 2213 | self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1)) |
|
2214 | 2214 | |
|
2215 | 2215 | def system_raw(self, cmd): |
|
2216 | 2216 | """Call the given cmd in a subprocess using os.system |
|
2217 | 2217 | |
|
2218 | 2218 | Parameters |
|
2219 | 2219 | ---------- |
|
2220 | 2220 | cmd : str |
|
2221 | 2221 | Command to execute. |
|
2222 | 2222 | """ |
|
2223 | 2223 | cmd = self.var_expand(cmd, depth=1) |
|
2224 | 2224 | # protect os.system from UNC paths on Windows, which it can't handle: |
|
2225 | 2225 | if sys.platform == 'win32': |
|
2226 | 2226 | from IPython.utils._process_win32 import AvoidUNCPath |
|
2227 | 2227 | with AvoidUNCPath() as path: |
|
2228 | 2228 | if path is not None: |
|
2229 | 2229 | cmd = '"pushd %s &&"%s' % (path, cmd) |
|
2230 | 2230 | cmd = py3compat.unicode_to_str(cmd) |
|
2231 | 2231 | ec = os.system(cmd) |
|
2232 | 2232 | else: |
|
2233 | 2233 | cmd = py3compat.unicode_to_str(cmd) |
|
2234 | 2234 | ec = os.system(cmd) |
|
2235 | 2235 | |
|
2236 | 2236 | # We explicitly do NOT return the subprocess status code, because |
|
2237 | 2237 | # a non-None value would trigger :func:`sys.displayhook` calls. |
|
2238 | 2238 | # Instead, we store the exit_code in user_ns. |
|
2239 | 2239 | self.user_ns['_exit_code'] = ec |
|
2240 | 2240 | |
|
2241 | 2241 | # use piped system by default, because it is better behaved |
|
2242 | 2242 | system = system_piped |
|
2243 | 2243 | |
|
2244 | 2244 | def getoutput(self, cmd, split=True, depth=0): |
|
2245 | 2245 | """Get output (possibly including stderr) from a subprocess. |
|
2246 | 2246 | |
|
2247 | 2247 | Parameters |
|
2248 | 2248 | ---------- |
|
2249 | 2249 | cmd : str |
|
2250 | 2250 | Command to execute (can not end in '&', as background processes are |
|
2251 | 2251 | not supported. |
|
2252 | 2252 | split : bool, optional |
|
2253 | 2253 | If True, split the output into an IPython SList. Otherwise, an |
|
2254 | 2254 | IPython LSString is returned. These are objects similar to normal |
|
2255 | 2255 | lists and strings, with a few convenience attributes for easier |
|
2256 | 2256 | manipulation of line-based output. You can use '?' on them for |
|
2257 | 2257 | details. |
|
2258 | 2258 | depth : int, optional |
|
2259 | 2259 | How many frames above the caller are the local variables which should |
|
2260 | 2260 | be expanded in the command string? The default (0) assumes that the |
|
2261 | 2261 | expansion variables are in the stack frame calling this function. |
|
2262 | 2262 | """ |
|
2263 | 2263 | if cmd.rstrip().endswith('&'): |
|
2264 | 2264 | # this is *far* from a rigorous test |
|
2265 | 2265 | raise OSError("Background processes not supported.") |
|
2266 | 2266 | out = getoutput(self.var_expand(cmd, depth=depth+1)) |
|
2267 | 2267 | if split: |
|
2268 | 2268 | out = SList(out.splitlines()) |
|
2269 | 2269 | else: |
|
2270 | 2270 | out = LSString(out) |
|
2271 | 2271 | return out |
|
2272 | 2272 | |
|
2273 | 2273 | #------------------------------------------------------------------------- |
|
2274 | 2274 | # Things related to aliases |
|
2275 | 2275 | #------------------------------------------------------------------------- |
|
2276 | 2276 | |
|
2277 | 2277 | def init_alias(self): |
|
2278 | 2278 | self.alias_manager = AliasManager(shell=self, config=self.config) |
|
2279 | 2279 | self.configurables.append(self.alias_manager) |
|
2280 | 2280 | self.ns_table['alias'] = self.alias_manager.alias_table, |
|
2281 | 2281 | |
|
2282 | 2282 | #------------------------------------------------------------------------- |
|
2283 | 2283 | # Things related to extensions and plugins |
|
2284 | 2284 | #------------------------------------------------------------------------- |
|
2285 | 2285 | |
|
2286 | 2286 | def init_extension_manager(self): |
|
2287 | 2287 | self.extension_manager = ExtensionManager(shell=self, config=self.config) |
|
2288 | 2288 | self.configurables.append(self.extension_manager) |
|
2289 | 2289 | |
|
2290 | 2290 | def init_plugin_manager(self): |
|
2291 | 2291 | self.plugin_manager = PluginManager(config=self.config) |
|
2292 | 2292 | self.configurables.append(self.plugin_manager) |
|
2293 | 2293 | |
|
2294 | 2294 | |
|
2295 | 2295 | #------------------------------------------------------------------------- |
|
2296 | 2296 | # Things related to payloads |
|
2297 | 2297 | #------------------------------------------------------------------------- |
|
2298 | 2298 | |
|
2299 | 2299 | def init_payload(self): |
|
2300 | 2300 | self.payload_manager = PayloadManager(config=self.config) |
|
2301 | 2301 | self.configurables.append(self.payload_manager) |
|
2302 | 2302 | |
|
2303 | 2303 | #------------------------------------------------------------------------- |
|
2304 | 2304 | # Things related to the prefilter |
|
2305 | 2305 | #------------------------------------------------------------------------- |
|
2306 | 2306 | |
|
2307 | 2307 | def init_prefilter(self): |
|
2308 | 2308 | self.prefilter_manager = PrefilterManager(shell=self, config=self.config) |
|
2309 | 2309 | self.configurables.append(self.prefilter_manager) |
|
2310 | 2310 | # Ultimately this will be refactored in the new interpreter code, but |
|
2311 | 2311 | # for now, we should expose the main prefilter method (there's legacy |
|
2312 | 2312 | # code out there that may rely on this). |
|
2313 | 2313 | self.prefilter = self.prefilter_manager.prefilter_lines |
|
2314 | 2314 | |
|
2315 | 2315 | def auto_rewrite_input(self, cmd): |
|
2316 | 2316 | """Print to the screen the rewritten form of the user's command. |
|
2317 | 2317 | |
|
2318 | 2318 | This shows visual feedback by rewriting input lines that cause |
|
2319 | 2319 | automatic calling to kick in, like:: |
|
2320 | 2320 | |
|
2321 | 2321 | /f x |
|
2322 | 2322 | |
|
2323 | 2323 | into:: |
|
2324 | 2324 | |
|
2325 | 2325 | ------> f(x) |
|
2326 | 2326 | |
|
2327 | 2327 | after the user's input prompt. This helps the user understand that the |
|
2328 | 2328 | input line was transformed automatically by IPython. |
|
2329 | 2329 | """ |
|
2330 | 2330 | if not self.show_rewritten_input: |
|
2331 | 2331 | return |
|
2332 | 2332 | |
|
2333 | 2333 | rw = self.prompt_manager.render('rewrite') + cmd |
|
2334 | 2334 | |
|
2335 | 2335 | try: |
|
2336 | 2336 | # plain ascii works better w/ pyreadline, on some machines, so |
|
2337 | 2337 | # we use it and only print uncolored rewrite if we have unicode |
|
2338 | 2338 | rw = str(rw) |
|
2339 | 2339 | print(rw, file=io.stdout) |
|
2340 | 2340 | except UnicodeEncodeError: |
|
2341 | 2341 | print("------> " + cmd) |
|
2342 | 2342 | |
|
2343 | 2343 | #------------------------------------------------------------------------- |
|
2344 | 2344 | # Things related to extracting values/expressions from kernel and user_ns |
|
2345 | 2345 | #------------------------------------------------------------------------- |
|
2346 | 2346 | |
|
2347 | 2347 | def _simple_error(self): |
|
2348 | 2348 | etype, value = sys.exc_info()[:2] |
|
2349 | 2349 | return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value) |
|
2350 | 2350 | |
|
2351 | 2351 | def user_variables(self, names): |
|
2352 | 2352 | """Get a list of variable names from the user's namespace. |
|
2353 | 2353 | |
|
2354 | 2354 | Parameters |
|
2355 | 2355 | ---------- |
|
2356 | 2356 | names : list of strings |
|
2357 | 2357 | A list of names of variables to be read from the user namespace. |
|
2358 | 2358 | |
|
2359 | 2359 | Returns |
|
2360 | 2360 | ------- |
|
2361 | 2361 | A dict, keyed by the input names and with the repr() of each value. |
|
2362 | 2362 | """ |
|
2363 | 2363 | out = {} |
|
2364 | 2364 | user_ns = self.user_ns |
|
2365 | 2365 | for varname in names: |
|
2366 | 2366 | try: |
|
2367 | 2367 | value = repr(user_ns[varname]) |
|
2368 | 2368 | except: |
|
2369 | 2369 | value = self._simple_error() |
|
2370 | 2370 | out[varname] = value |
|
2371 | 2371 | return out |
|
2372 | 2372 | |
|
2373 | 2373 | def user_expressions(self, expressions): |
|
2374 | 2374 | """Evaluate a dict of expressions in the user's namespace. |
|
2375 | 2375 | |
|
2376 | 2376 | Parameters |
|
2377 | 2377 | ---------- |
|
2378 | 2378 | expressions : dict |
|
2379 | 2379 | A dict with string keys and string values. The expression values |
|
2380 | 2380 | should be valid Python expressions, each of which will be evaluated |
|
2381 | 2381 | in the user namespace. |
|
2382 | 2382 | |
|
2383 | 2383 | Returns |
|
2384 | 2384 | ------- |
|
2385 | 2385 | A dict, keyed like the input expressions dict, with the repr() of each |
|
2386 | 2386 | value. |
|
2387 | 2387 | """ |
|
2388 | 2388 | out = {} |
|
2389 | 2389 | user_ns = self.user_ns |
|
2390 | 2390 | global_ns = self.user_global_ns |
|
2391 | 2391 | for key, expr in expressions.iteritems(): |
|
2392 | 2392 | try: |
|
2393 | 2393 | value = repr(eval(expr, global_ns, user_ns)) |
|
2394 | 2394 | except: |
|
2395 | 2395 | value = self._simple_error() |
|
2396 | 2396 | out[key] = value |
|
2397 | 2397 | return out |
|
2398 | 2398 | |
|
2399 | 2399 | #------------------------------------------------------------------------- |
|
2400 | 2400 | # Things related to the running of code |
|
2401 | 2401 | #------------------------------------------------------------------------- |
|
2402 | 2402 | |
|
2403 | 2403 | def ex(self, cmd): |
|
2404 | 2404 | """Execute a normal python statement in user namespace.""" |
|
2405 | 2405 | with self.builtin_trap: |
|
2406 | 2406 | exec cmd in self.user_global_ns, self.user_ns |
|
2407 | 2407 | |
|
2408 | 2408 | def ev(self, expr): |
|
2409 | 2409 | """Evaluate python expression expr in user namespace. |
|
2410 | 2410 | |
|
2411 | 2411 | Returns the result of evaluation |
|
2412 | 2412 | """ |
|
2413 | 2413 | with self.builtin_trap: |
|
2414 | 2414 | return eval(expr, self.user_global_ns, self.user_ns) |
|
2415 | 2415 | |
|
2416 | 2416 | def safe_execfile(self, fname, *where, **kw): |
|
2417 | 2417 | """A safe version of the builtin execfile(). |
|
2418 | 2418 | |
|
2419 | 2419 | This version will never throw an exception, but instead print |
|
2420 | 2420 | helpful error messages to the screen. This only works on pure |
|
2421 | 2421 | Python files with the .py extension. |
|
2422 | 2422 | |
|
2423 | 2423 | Parameters |
|
2424 | 2424 | ---------- |
|
2425 | 2425 | fname : string |
|
2426 | 2426 | The name of the file to be executed. |
|
2427 | 2427 | where : tuple |
|
2428 | 2428 | One or two namespaces, passed to execfile() as (globals,locals). |
|
2429 | 2429 | If only one is given, it is passed as both. |
|
2430 | 2430 | exit_ignore : bool (False) |
|
2431 | 2431 | If True, then silence SystemExit for non-zero status (it is always |
|
2432 | 2432 | silenced for zero status, as it is so common). |
|
2433 | 2433 | raise_exceptions : bool (False) |
|
2434 | 2434 | If True raise exceptions everywhere. Meant for testing. |
|
2435 | 2435 | |
|
2436 | 2436 | """ |
|
2437 | 2437 | kw.setdefault('exit_ignore', False) |
|
2438 | 2438 | kw.setdefault('raise_exceptions', False) |
|
2439 | 2439 | |
|
2440 | 2440 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2441 | 2441 | |
|
2442 | 2442 | # Make sure we can open the file |
|
2443 | 2443 | try: |
|
2444 | 2444 | with open(fname) as thefile: |
|
2445 | 2445 | pass |
|
2446 | 2446 | except: |
|
2447 | 2447 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2448 | 2448 | return |
|
2449 | 2449 | |
|
2450 | 2450 | # Find things also in current directory. This is needed to mimic the |
|
2451 | 2451 | # behavior of running a script from the system command line, where |
|
2452 | 2452 | # Python inserts the script's directory into sys.path |
|
2453 | 2453 | dname = os.path.dirname(fname) |
|
2454 | 2454 | |
|
2455 | 2455 | with prepended_to_syspath(dname): |
|
2456 | 2456 | try: |
|
2457 | 2457 | py3compat.execfile(fname,*where) |
|
2458 | 2458 | except SystemExit as status: |
|
2459 | 2459 | # If the call was made with 0 or None exit status (sys.exit(0) |
|
2460 | 2460 | # or sys.exit() ), don't bother showing a traceback, as both of |
|
2461 | 2461 | # these are considered normal by the OS: |
|
2462 | 2462 | # > python -c'import sys;sys.exit(0)'; echo $? |
|
2463 | 2463 | # 0 |
|
2464 | 2464 | # > python -c'import sys;sys.exit()'; echo $? |
|
2465 | 2465 | # 0 |
|
2466 | 2466 | # For other exit status, we show the exception unless |
|
2467 | 2467 | # explicitly silenced, but only in short form. |
|
2468 | 2468 | if kw['raise_exceptions']: |
|
2469 | 2469 | raise |
|
2470 | 2470 | if status.code not in (0, None) and not kw['exit_ignore']: |
|
2471 | 2471 | self.showtraceback(exception_only=True) |
|
2472 | 2472 | except: |
|
2473 | 2473 | if kw['raise_exceptions']: |
|
2474 | 2474 | raise |
|
2475 | 2475 | self.showtraceback() |
|
2476 | 2476 | |
|
2477 | 2477 | def safe_execfile_ipy(self, fname): |
|
2478 | 2478 | """Like safe_execfile, but for .ipy files with IPython syntax. |
|
2479 | 2479 | |
|
2480 | 2480 | Parameters |
|
2481 | 2481 | ---------- |
|
2482 | 2482 | fname : str |
|
2483 | 2483 | The name of the file to execute. The filename must have a |
|
2484 | 2484 | .ipy extension. |
|
2485 | 2485 | """ |
|
2486 | 2486 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2487 | 2487 | |
|
2488 | 2488 | # Make sure we can open the file |
|
2489 | 2489 | try: |
|
2490 | 2490 | with open(fname) as thefile: |
|
2491 | 2491 | pass |
|
2492 | 2492 | except: |
|
2493 | 2493 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2494 | 2494 | return |
|
2495 | 2495 | |
|
2496 | 2496 | # Find things also in current directory. This is needed to mimic the |
|
2497 | 2497 | # behavior of running a script from the system command line, where |
|
2498 | 2498 | # Python inserts the script's directory into sys.path |
|
2499 | 2499 | dname = os.path.dirname(fname) |
|
2500 | 2500 | |
|
2501 | 2501 | with prepended_to_syspath(dname): |
|
2502 | 2502 | try: |
|
2503 | 2503 | with open(fname) as thefile: |
|
2504 | 2504 | # self.run_cell currently captures all exceptions |
|
2505 | 2505 | # raised in user code. It would be nice if there were |
|
2506 | 2506 | # versions of runlines, execfile that did raise, so |
|
2507 | 2507 | # we could catch the errors. |
|
2508 | 2508 | self.run_cell(thefile.read(), store_history=False) |
|
2509 | 2509 | except: |
|
2510 | 2510 | self.showtraceback() |
|
2511 | 2511 | warn('Unknown failure executing file: <%s>' % fname) |
|
2512 | 2512 | |
|
2513 | 2513 | def safe_run_module(self, mod_name, where): |
|
2514 | 2514 | """A safe version of runpy.run_module(). |
|
2515 | 2515 | |
|
2516 | 2516 | This version will never throw an exception, but instead print |
|
2517 | 2517 | helpful error messages to the screen. |
|
2518 | 2518 | |
|
2519 | 2519 | Parameters |
|
2520 | 2520 | ---------- |
|
2521 | 2521 | mod_name : string |
|
2522 | 2522 | The name of the module to be executed. |
|
2523 | 2523 | where : dict |
|
2524 | 2524 | The globals namespace. |
|
2525 | 2525 | """ |
|
2526 | 2526 | try: |
|
2527 | 2527 | where.update( |
|
2528 | 2528 | runpy.run_module(str(mod_name), run_name="__main__", |
|
2529 | 2529 | alter_sys=True) |
|
2530 | 2530 | ) |
|
2531 | 2531 | except: |
|
2532 | 2532 | self.showtraceback() |
|
2533 | 2533 | warn('Unknown failure executing module: <%s>' % mod_name) |
|
2534 | 2534 | |
|
2535 | 2535 | def _run_cached_cell_magic(self, magic_name, line): |
|
2536 | 2536 | """Special method to call a cell magic with the data stored in self. |
|
2537 | 2537 | """ |
|
2538 | 2538 | cell = self._current_cell_magic_body |
|
2539 | 2539 | self._current_cell_magic_body = None |
|
2540 | 2540 | return self.run_cell_magic(magic_name, line, cell) |
|
2541 | 2541 | |
|
2542 | 2542 | def run_cell(self, raw_cell, store_history=False, silent=False): |
|
2543 | 2543 | """Run a complete IPython cell. |
|
2544 | 2544 | |
|
2545 | 2545 | Parameters |
|
2546 | 2546 | ---------- |
|
2547 | 2547 | raw_cell : str |
|
2548 | 2548 | The code (including IPython code such as %magic functions) to run. |
|
2549 | 2549 | store_history : bool |
|
2550 | 2550 | If True, the raw and translated cell will be stored in IPython's |
|
2551 | 2551 | history. For user code calling back into IPython's machinery, this |
|
2552 | 2552 | should be set to False. |
|
2553 | 2553 | silent : bool |
|
2554 | 2554 | If True, avoid side-effets, such as implicit displayhooks, history, |
|
2555 | 2555 | and logging. silent=True forces store_history=False. |
|
2556 | 2556 | """ |
|
2557 | 2557 | if (not raw_cell) or raw_cell.isspace(): |
|
2558 | 2558 | return |
|
2559 | 2559 | |
|
2560 | 2560 | if silent: |
|
2561 | 2561 | store_history = False |
|
2562 | 2562 | |
|
2563 | 2563 | self.input_splitter.push(raw_cell) |
|
2564 | 2564 | |
|
2565 | 2565 | # Check for cell magics, which leave state behind. This interface is |
|
2566 | 2566 | # ugly, we need to do something cleaner later... Now the logic is |
|
2567 | 2567 | # simply that the input_splitter remembers if there was a cell magic, |
|
2568 | 2568 | # and in that case we grab the cell body. |
|
2569 | 2569 | if self.input_splitter.cell_magic_parts: |
|
2570 | 2570 | self._current_cell_magic_body = \ |
|
2571 | 2571 | ''.join(self.input_splitter.cell_magic_parts) |
|
2572 | 2572 | cell = self.input_splitter.source_reset() |
|
2573 | 2573 | |
|
2574 | 2574 | with self.builtin_trap: |
|
2575 | 2575 | prefilter_failed = False |
|
2576 | 2576 | if len(cell.splitlines()) == 1: |
|
2577 | 2577 | try: |
|
2578 | 2578 | # use prefilter_lines to handle trailing newlines |
|
2579 | 2579 | # restore trailing newline for ast.parse |
|
2580 | 2580 | cell = self.prefilter_manager.prefilter_lines(cell) + '\n' |
|
2581 | 2581 | except AliasError as e: |
|
2582 | 2582 | error(e) |
|
2583 | 2583 | prefilter_failed = True |
|
2584 | 2584 | except Exception: |
|
2585 | 2585 | # don't allow prefilter errors to crash IPython |
|
2586 | 2586 | self.showtraceback() |
|
2587 | 2587 | prefilter_failed = True |
|
2588 | 2588 | |
|
2589 | 2589 | # Store raw and processed history |
|
2590 | 2590 | if store_history: |
|
2591 | 2591 | self.history_manager.store_inputs(self.execution_count, |
|
2592 | 2592 | cell, raw_cell) |
|
2593 | 2593 | if not silent: |
|
2594 | 2594 | self.logger.log(cell, raw_cell) |
|
2595 | 2595 | |
|
2596 | 2596 | if not prefilter_failed: |
|
2597 | 2597 | # don't run if prefilter failed |
|
2598 | 2598 | cell_name = self.compile.cache(cell, self.execution_count) |
|
2599 | 2599 | |
|
2600 | 2600 | with self.display_trap: |
|
2601 | 2601 | try: |
|
2602 | 2602 | code_ast = self.compile.ast_parse(cell, |
|
2603 | 2603 | filename=cell_name) |
|
2604 | 2604 | except IndentationError: |
|
2605 | 2605 | self.showindentationerror() |
|
2606 | 2606 | if store_history: |
|
2607 | 2607 | self.execution_count += 1 |
|
2608 | 2608 | return None |
|
2609 | 2609 | except (OverflowError, SyntaxError, ValueError, TypeError, |
|
2610 | 2610 | MemoryError): |
|
2611 | 2611 | self.showsyntaxerror() |
|
2612 | 2612 | if store_history: |
|
2613 | 2613 | self.execution_count += 1 |
|
2614 | 2614 | return None |
|
2615 | 2615 | |
|
2616 | 2616 | interactivity = "none" if silent else self.ast_node_interactivity |
|
2617 | 2617 | self.run_ast_nodes(code_ast.body, cell_name, |
|
2618 | 2618 | interactivity=interactivity) |
|
2619 | 2619 | |
|
2620 | 2620 | # Execute any registered post-execution functions. |
|
2621 | 2621 | # unless we are silent |
|
2622 | 2622 | post_exec = [] if silent else self._post_execute.iteritems() |
|
2623 | 2623 | |
|
2624 | 2624 | for func, status in post_exec: |
|
2625 | 2625 | if self.disable_failing_post_execute and not status: |
|
2626 | 2626 | continue |
|
2627 | 2627 | try: |
|
2628 | 2628 | func() |
|
2629 | 2629 | except KeyboardInterrupt: |
|
2630 | 2630 | print("\nKeyboardInterrupt", file=io.stderr) |
|
2631 | 2631 | except Exception: |
|
2632 | 2632 | # register as failing: |
|
2633 | 2633 | self._post_execute[func] = False |
|
2634 | 2634 | self.showtraceback() |
|
2635 | 2635 | print('\n'.join([ |
|
2636 | 2636 | "post-execution function %r produced an error." % func, |
|
2637 | 2637 | "If this problem persists, you can disable failing post-exec functions with:", |
|
2638 | 2638 | "", |
|
2639 | 2639 | " get_ipython().disable_failing_post_execute = True" |
|
2640 | 2640 | ]), file=io.stderr) |
|
2641 | 2641 | |
|
2642 | 2642 | if store_history: |
|
2643 | 2643 | # Write output to the database. Does nothing unless |
|
2644 | 2644 | # history output logging is enabled. |
|
2645 | 2645 | self.history_manager.store_output(self.execution_count) |
|
2646 | 2646 | # Each cell is a *single* input, regardless of how many lines it has |
|
2647 | 2647 | self.execution_count += 1 |
|
2648 | 2648 | |
|
2649 | 2649 | def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'): |
|
2650 | 2650 | """Run a sequence of AST nodes. The execution mode depends on the |
|
2651 | 2651 | interactivity parameter. |
|
2652 | 2652 | |
|
2653 | 2653 | Parameters |
|
2654 | 2654 | ---------- |
|
2655 | 2655 | nodelist : list |
|
2656 | 2656 | A sequence of AST nodes to run. |
|
2657 | 2657 | cell_name : str |
|
2658 | 2658 | Will be passed to the compiler as the filename of the cell. Typically |
|
2659 | 2659 | the value returned by ip.compile.cache(cell). |
|
2660 | 2660 | interactivity : str |
|
2661 | 2661 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be |
|
2662 | 2662 | run interactively (displaying output from expressions). 'last_expr' |
|
2663 | 2663 | will run the last node interactively only if it is an expression (i.e. |
|
2664 | 2664 | expressions in loops or other blocks are not displayed. Other values |
|
2665 | 2665 | for this parameter will raise a ValueError. |
|
2666 | 2666 | """ |
|
2667 | 2667 | if not nodelist: |
|
2668 | 2668 | return |
|
2669 | 2669 | |
|
2670 | 2670 | if interactivity == 'last_expr': |
|
2671 | 2671 | if isinstance(nodelist[-1], ast.Expr): |
|
2672 | 2672 | interactivity = "last" |
|
2673 | 2673 | else: |
|
2674 | 2674 | interactivity = "none" |
|
2675 | 2675 | |
|
2676 | 2676 | if interactivity == 'none': |
|
2677 | 2677 | to_run_exec, to_run_interactive = nodelist, [] |
|
2678 | 2678 | elif interactivity == 'last': |
|
2679 | 2679 | to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:] |
|
2680 | 2680 | elif interactivity == 'all': |
|
2681 | 2681 | to_run_exec, to_run_interactive = [], nodelist |
|
2682 | 2682 | else: |
|
2683 | 2683 | raise ValueError("Interactivity was %r" % interactivity) |
|
2684 | 2684 | |
|
2685 | 2685 | exec_count = self.execution_count |
|
2686 | 2686 | |
|
2687 | 2687 | try: |
|
2688 | 2688 | for i, node in enumerate(to_run_exec): |
|
2689 | 2689 | mod = ast.Module([node]) |
|
2690 | 2690 | code = self.compile(mod, cell_name, "exec") |
|
2691 | 2691 | if self.run_code(code): |
|
2692 | 2692 | return True |
|
2693 | 2693 | |
|
2694 | 2694 | for i, node in enumerate(to_run_interactive): |
|
2695 | 2695 | mod = ast.Interactive([node]) |
|
2696 | 2696 | code = self.compile(mod, cell_name, "single") |
|
2697 | 2697 | if self.run_code(code): |
|
2698 | 2698 | return True |
|
2699 | 2699 | |
|
2700 | 2700 | # Flush softspace |
|
2701 | 2701 | if softspace(sys.stdout, 0): |
|
2702 | 2702 | print() |
|
2703 | 2703 | |
|
2704 | 2704 | except: |
|
2705 | 2705 | # It's possible to have exceptions raised here, typically by |
|
2706 | 2706 | # compilation of odd code (such as a naked 'return' outside a |
|
2707 | 2707 | # function) that did parse but isn't valid. Typically the exception |
|
2708 | 2708 | # is a SyntaxError, but it's safest just to catch anything and show |
|
2709 | 2709 | # the user a traceback. |
|
2710 | 2710 | |
|
2711 | 2711 | # We do only one try/except outside the loop to minimize the impact |
|
2712 | 2712 | # on runtime, and also because if any node in the node list is |
|
2713 | 2713 | # broken, we should stop execution completely. |
|
2714 | 2714 | self.showtraceback() |
|
2715 | 2715 | |
|
2716 | 2716 | return False |
|
2717 | 2717 | |
|
2718 | 2718 | def run_code(self, code_obj): |
|
2719 | 2719 | """Execute a code object. |
|
2720 | 2720 | |
|
2721 | 2721 | When an exception occurs, self.showtraceback() is called to display a |
|
2722 | 2722 | traceback. |
|
2723 | 2723 | |
|
2724 | 2724 | Parameters |
|
2725 | 2725 | ---------- |
|
2726 | 2726 | code_obj : code object |
|
2727 | 2727 | A compiled code object, to be executed |
|
2728 | 2728 | |
|
2729 | 2729 | Returns |
|
2730 | 2730 | ------- |
|
2731 | 2731 | False : successful execution. |
|
2732 | 2732 | True : an error occurred. |
|
2733 | 2733 | """ |
|
2734 | 2734 | |
|
2735 | 2735 | # Set our own excepthook in case the user code tries to call it |
|
2736 | 2736 | # directly, so that the IPython crash handler doesn't get triggered |
|
2737 | 2737 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2738 | 2738 | |
|
2739 | 2739 | # we save the original sys.excepthook in the instance, in case config |
|
2740 | 2740 | # code (such as magics) needs access to it. |
|
2741 | 2741 | self.sys_excepthook = old_excepthook |
|
2742 | 2742 | outflag = 1 # happens in more places, so it's easier as default |
|
2743 | 2743 | try: |
|
2744 | 2744 | try: |
|
2745 | 2745 | self.hooks.pre_run_code_hook() |
|
2746 | 2746 | #rprint('Running code', repr(code_obj)) # dbg |
|
2747 | 2747 | exec code_obj in self.user_global_ns, self.user_ns |
|
2748 | 2748 | finally: |
|
2749 | 2749 | # Reset our crash handler in place |
|
2750 | 2750 | sys.excepthook = old_excepthook |
|
2751 | 2751 | except SystemExit: |
|
2752 | 2752 | self.showtraceback(exception_only=True) |
|
2753 | 2753 | warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1) |
|
2754 | 2754 | except self.custom_exceptions: |
|
2755 | 2755 | etype,value,tb = sys.exc_info() |
|
2756 | 2756 | self.CustomTB(etype,value,tb) |
|
2757 | 2757 | except: |
|
2758 | 2758 | self.showtraceback() |
|
2759 | 2759 | else: |
|
2760 | 2760 | outflag = 0 |
|
2761 | 2761 | return outflag |
|
2762 | 2762 | |
|
2763 | 2763 | # For backwards compatibility |
|
2764 | 2764 | runcode = run_code |
|
2765 | 2765 | |
|
2766 | 2766 | #------------------------------------------------------------------------- |
|
2767 | 2767 | # Things related to GUI support and pylab |
|
2768 | 2768 | #------------------------------------------------------------------------- |
|
2769 | 2769 | |
|
2770 | 2770 | def enable_gui(self, gui=None): |
|
2771 | 2771 | raise NotImplementedError('Implement enable_gui in a subclass') |
|
2772 | 2772 | |
|
2773 | 2773 | def enable_pylab(self, gui=None, import_all=True): |
|
2774 | 2774 | """Activate pylab support at runtime. |
|
2775 | 2775 | |
|
2776 | 2776 | This turns on support for matplotlib, preloads into the interactive |
|
2777 | 2777 | namespace all of numpy and pylab, and configures IPython to correctly |
|
2778 | 2778 | interact with the GUI event loop. The GUI backend to be used can be |
|
2779 | 2779 | optionally selected with the optional :param:`gui` argument. |
|
2780 | 2780 | |
|
2781 | 2781 | Parameters |
|
2782 | 2782 | ---------- |
|
2783 | 2783 | gui : optional, string |
|
2784 | 2784 | |
|
2785 | 2785 | If given, dictates the choice of matplotlib GUI backend to use |
|
2786 | 2786 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', |
|
2787 | 2787 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by |
|
2788 | 2788 | matplotlib (as dictated by the matplotlib build-time options plus the |
|
2789 | 2789 | user's matplotlibrc configuration file). Note that not all backends |
|
2790 | 2790 | make sense in all contexts, for example a terminal ipython can't |
|
2791 | 2791 | display figures inline. |
|
2792 | 2792 | """ |
|
2793 | 2793 | from IPython.core.pylabtools import mpl_runner |
|
2794 | 2794 | # We want to prevent the loading of pylab to pollute the user's |
|
2795 | 2795 | # namespace as shown by the %who* magics, so we execute the activation |
|
2796 | 2796 | # code in an empty namespace, and we update *both* user_ns and |
|
2797 | 2797 | # user_ns_hidden with this information. |
|
2798 | 2798 | ns = {} |
|
2799 | 2799 | try: |
|
2800 | 2800 | gui = pylab_activate(ns, gui, import_all, self) |
|
2801 | 2801 | except KeyError: |
|
2802 | 2802 | error("Backend %r not supported" % gui) |
|
2803 | 2803 | return |
|
2804 | 2804 | self.user_ns.update(ns) |
|
2805 | 2805 | self.user_ns_hidden.update(ns) |
|
2806 | 2806 | # Now we must activate the gui pylab wants to use, and fix %run to take |
|
2807 | 2807 | # plot updates into account |
|
2808 | 2808 | self.enable_gui(gui) |
|
2809 | 2809 | self.magics_manager.registry['ExecutionMagics'].default_runner = \ |
|
2810 | 2810 | mpl_runner(self.safe_execfile) |
|
2811 | 2811 | |
|
2812 | 2812 | #------------------------------------------------------------------------- |
|
2813 | 2813 | # Utilities |
|
2814 | 2814 | #------------------------------------------------------------------------- |
|
2815 | 2815 | |
|
2816 | 2816 | def var_expand(self, cmd, depth=0, formatter=DollarFormatter()): |
|
2817 | 2817 | """Expand python variables in a string. |
|
2818 | 2818 | |
|
2819 | 2819 | The depth argument indicates how many frames above the caller should |
|
2820 | 2820 | be walked to look for the local namespace where to expand variables. |
|
2821 | 2821 | |
|
2822 | 2822 | The global namespace for expansion is always the user's interactive |
|
2823 | 2823 | namespace. |
|
2824 | 2824 | """ |
|
2825 | 2825 | ns = self.user_ns.copy() |
|
2826 | 2826 | ns.update(sys._getframe(depth+1).f_locals) |
|
2827 | 2827 | ns.pop('self', None) |
|
2828 | 2828 | try: |
|
2829 | 2829 | cmd = formatter.format(cmd, **ns) |
|
2830 | 2830 | except Exception: |
|
2831 | 2831 | # if formatter couldn't format, just let it go untransformed |
|
2832 | 2832 | pass |
|
2833 | 2833 | return cmd |
|
2834 | 2834 | |
|
2835 | 2835 | def mktempfile(self, data=None, prefix='ipython_edit_'): |
|
2836 | 2836 | """Make a new tempfile and return its filename. |
|
2837 | 2837 | |
|
2838 | 2838 | This makes a call to tempfile.mktemp, but it registers the created |
|
2839 | 2839 | filename internally so ipython cleans it up at exit time. |
|
2840 | 2840 | |
|
2841 | 2841 | Optional inputs: |
|
2842 | 2842 | |
|
2843 | 2843 | - data(None): if data is given, it gets written out to the temp file |
|
2844 | 2844 | immediately, and the file is closed again.""" |
|
2845 | 2845 | |
|
2846 | 2846 | filename = tempfile.mktemp('.py', prefix) |
|
2847 | 2847 | self.tempfiles.append(filename) |
|
2848 | 2848 | |
|
2849 | 2849 | if data: |
|
2850 | 2850 | tmp_file = open(filename,'w') |
|
2851 | 2851 | tmp_file.write(data) |
|
2852 | 2852 | tmp_file.close() |
|
2853 | 2853 | return filename |
|
2854 | 2854 | |
|
2855 | 2855 | # TODO: This should be removed when Term is refactored. |
|
2856 | 2856 | def write(self,data): |
|
2857 | 2857 | """Write a string to the default output""" |
|
2858 | 2858 | io.stdout.write(data) |
|
2859 | 2859 | |
|
2860 | 2860 | # TODO: This should be removed when Term is refactored. |
|
2861 | 2861 | def write_err(self,data): |
|
2862 | 2862 | """Write a string to the default error output""" |
|
2863 | 2863 | io.stderr.write(data) |
|
2864 | 2864 | |
|
2865 | 2865 | def ask_yes_no(self, prompt, default=None): |
|
2866 | 2866 | if self.quiet: |
|
2867 | 2867 | return True |
|
2868 | 2868 | return ask_yes_no(prompt,default) |
|
2869 | 2869 | |
|
2870 | 2870 | def show_usage(self): |
|
2871 | 2871 | """Show a usage message""" |
|
2872 | 2872 | page.page(IPython.core.usage.interactive_usage) |
|
2873 | 2873 | |
|
2874 | 2874 | def extract_input_lines(self, range_str, raw=False): |
|
2875 | 2875 | """Return as a string a set of input history slices. |
|
2876 | 2876 | |
|
2877 | 2877 | Parameters |
|
2878 | 2878 | ---------- |
|
2879 | 2879 | range_str : string |
|
2880 | 2880 | The set of slices is given as a string, like "~5/6-~4/2 4:8 9", |
|
2881 | 2881 | since this function is for use by magic functions which get their |
|
2882 | 2882 | arguments as strings. The number before the / is the session |
|
2883 | 2883 | number: ~n goes n back from the current session. |
|
2884 | 2884 | |
|
2885 | 2885 | Optional Parameters: |
|
2886 | 2886 | - raw(False): by default, the processed input is used. If this is |
|
2887 | 2887 | true, the raw input history is used instead. |
|
2888 | 2888 | |
|
2889 | 2889 | Note that slices can be called with two notations: |
|
2890 | 2890 | |
|
2891 | 2891 | N:M -> standard python form, means including items N...(M-1). |
|
2892 | 2892 | |
|
2893 | 2893 | N-M -> include items N..M (closed endpoint).""" |
|
2894 | 2894 | lines = self.history_manager.get_range_by_str(range_str, raw=raw) |
|
2895 | 2895 | return "\n".join(x for _, _, x in lines) |
|
2896 | 2896 | |
|
2897 | 2897 | def find_user_code(self, target, raw=True, py_only=False): |
|
2898 | 2898 | """Get a code string from history, file, url, or a string or macro. |
|
2899 | 2899 | |
|
2900 | 2900 | This is mainly used by magic functions. |
|
2901 | 2901 | |
|
2902 | 2902 | Parameters |
|
2903 | 2903 | ---------- |
|
2904 | 2904 | |
|
2905 | 2905 | target : str |
|
2906 | 2906 | |
|
2907 | 2907 | A string specifying code to retrieve. This will be tried respectively |
|
2908 | 2908 | as: ranges of input history (see %history for syntax), url, |
|
2909 | 2909 | correspnding .py file, filename, or an expression evaluating to a |
|
2910 | 2910 | string or Macro in the user namespace. |
|
2911 | 2911 | |
|
2912 | 2912 | raw : bool |
|
2913 | 2913 | If true (default), retrieve raw history. Has no effect on the other |
|
2914 | 2914 | retrieval mechanisms. |
|
2915 | 2915 | |
|
2916 | 2916 | py_only : bool (default False) |
|
2917 | 2917 | Only try to fetch python code, do not try alternative methods to decode file |
|
2918 | 2918 | if unicode fails. |
|
2919 | 2919 | |
|
2920 | 2920 | Returns |
|
2921 | 2921 | ------- |
|
2922 | 2922 | A string of code. |
|
2923 | 2923 | |
|
2924 | 2924 | ValueError is raised if nothing is found, and TypeError if it evaluates |
|
2925 | 2925 | to an object of another type. In each case, .args[0] is a printable |
|
2926 | 2926 | message. |
|
2927 | 2927 | """ |
|
2928 | 2928 | code = self.extract_input_lines(target, raw=raw) # Grab history |
|
2929 | 2929 | if code: |
|
2930 | 2930 | return code |
|
2931 | 2931 | utarget = unquote_filename(target) |
|
2932 | 2932 | try: |
|
2933 | 2933 | if utarget.startswith(('http://', 'https://')): |
|
2934 | 2934 | return openpy.read_py_url(utarget, skip_encoding_cookie=True) |
|
2935 | 2935 | except UnicodeDecodeError: |
|
2936 | 2936 | if not py_only : |
|
2937 | 2937 | response = urllib.urlopen(target) |
|
2938 | 2938 | return response.read().decode('latin1') |
|
2939 | 2939 | raise ValueError(("'%s' seem to be unreadable.") % utarget) |
|
2940 | 2940 | |
|
2941 | 2941 | potential_target = [target] |
|
2942 | 2942 | try : |
|
2943 | 2943 | potential_target.insert(0,get_py_filename(target)) |
|
2944 | 2944 | except IOError: |
|
2945 | 2945 | pass |
|
2946 | 2946 | |
|
2947 | 2947 | for tgt in potential_target : |
|
2948 | 2948 | if os.path.isfile(tgt): # Read file |
|
2949 | 2949 | try : |
|
2950 | 2950 | return openpy.read_py_file(tgt, skip_encoding_cookie=True) |
|
2951 | 2951 | except UnicodeDecodeError : |
|
2952 | 2952 | if not py_only : |
|
2953 | 2953 | with io_open(tgt,'r', encoding='latin1') as f : |
|
2954 | 2954 | return f.read() |
|
2955 | 2955 | raise ValueError(("'%s' seem to be unreadable.") % target) |
|
2956 | 2956 | |
|
2957 | 2957 | try: # User namespace |
|
2958 | 2958 | codeobj = eval(target, self.user_ns) |
|
2959 | 2959 | except Exception: |
|
2960 | 2960 | raise ValueError(("'%s' was not found in history, as a file, url, " |
|
2961 | 2961 | "nor in the user namespace.") % target) |
|
2962 | 2962 | if isinstance(codeobj, basestring): |
|
2963 | 2963 | return codeobj |
|
2964 | 2964 | elif isinstance(codeobj, Macro): |
|
2965 | 2965 | return codeobj.value |
|
2966 | 2966 | |
|
2967 | 2967 | raise TypeError("%s is neither a string nor a macro." % target, |
|
2968 | 2968 | codeobj) |
|
2969 | 2969 | |
|
2970 | 2970 | #------------------------------------------------------------------------- |
|
2971 | 2971 | # Things related to IPython exiting |
|
2972 | 2972 | #------------------------------------------------------------------------- |
|
2973 | 2973 | def atexit_operations(self): |
|
2974 | 2974 | """This will be executed at the time of exit. |
|
2975 | 2975 | |
|
2976 | 2976 | Cleanup operations and saving of persistent data that is done |
|
2977 | 2977 | unconditionally by IPython should be performed here. |
|
2978 | 2978 | |
|
2979 | 2979 | For things that may depend on startup flags or platform specifics (such |
|
2980 | 2980 | as having readline or not), register a separate atexit function in the |
|
2981 | 2981 | code that has the appropriate information, rather than trying to |
|
2982 | 2982 | clutter |
|
2983 | 2983 | """ |
|
2984 | 2984 | # Close the history session (this stores the end time and line count) |
|
2985 | 2985 | # this must be *before* the tempfile cleanup, in case of temporary |
|
2986 | 2986 | # history db |
|
2987 | 2987 | self.history_manager.end_session() |
|
2988 | 2988 | |
|
2989 | 2989 | # Cleanup all tempfiles left around |
|
2990 | 2990 | for tfile in self.tempfiles: |
|
2991 | 2991 | try: |
|
2992 | 2992 | os.unlink(tfile) |
|
2993 | 2993 | except OSError: |
|
2994 | 2994 | pass |
|
2995 | 2995 | |
|
2996 | 2996 | # Clear all user namespaces to release all references cleanly. |
|
2997 | 2997 | self.reset(new_session=False) |
|
2998 | 2998 | |
|
2999 | 2999 | # Run user hooks |
|
3000 | 3000 | self.hooks.shutdown_hook() |
|
3001 | 3001 | |
|
3002 | 3002 | def cleanup(self): |
|
3003 | 3003 | self.restore_sys_module_state() |
|
3004 | 3004 | |
|
3005 | 3005 | |
|
3006 | 3006 | class InteractiveShellABC(object): |
|
3007 | 3007 | """An abstract base class for InteractiveShell.""" |
|
3008 | 3008 | __metaclass__ = abc.ABCMeta |
|
3009 | 3009 | |
|
3010 | 3010 | InteractiveShellABC.register(InteractiveShell) |
@@ -1,220 +1,220 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 | 21 | from IPython.utils.py3compat import str_to_unicode |
|
22 | 22 | |
|
23 | 23 | #**************************************************************************** |
|
24 | 24 | # FIXME: This class isn't a mixin anymore, but it still needs attributes from |
|
25 | 25 | # ipython and does input cache management. Finish cleanup later... |
|
26 | 26 | |
|
27 | 27 | class Logger(object): |
|
28 | 28 | """A Logfile class with different policies for file creation""" |
|
29 | 29 | |
|
30 | 30 | def __init__(self, home_dir, logfname='Logger.log', loghead=u'', |
|
31 | 31 | logmode='over'): |
|
32 | 32 | |
|
33 | 33 | # this is the full ipython instance, we need some attributes from it |
|
34 | 34 | # which won't exist until later. What a mess, clean up later... |
|
35 | 35 | self.home_dir = home_dir |
|
36 | 36 | |
|
37 | 37 | self.logfname = logfname |
|
38 | 38 | self.loghead = loghead |
|
39 | 39 | self.logmode = logmode |
|
40 | 40 | self.logfile = None |
|
41 | 41 | |
|
42 | 42 | # Whether to log raw or processed input |
|
43 | 43 | self.log_raw_input = False |
|
44 | 44 | |
|
45 | 45 | # whether to also log output |
|
46 | 46 | self.log_output = False |
|
47 | 47 | |
|
48 | 48 | # whether to put timestamps before each log entry |
|
49 | 49 | self.timestamp = False |
|
50 | 50 | |
|
51 | 51 | # activity control flags |
|
52 | 52 | self.log_active = False |
|
53 | 53 | |
|
54 | 54 | # logmode is a validated property |
|
55 | 55 | def _set_mode(self,mode): |
|
56 | 56 | if mode not in ['append','backup','global','over','rotate']: |
|
57 |
raise ValueError |
|
|
57 | raise ValueError('invalid log mode %s given' % mode) | |
|
58 | 58 | self._logmode = mode |
|
59 | 59 | |
|
60 | 60 | def _get_mode(self): |
|
61 | 61 | return self._logmode |
|
62 | 62 | |
|
63 | 63 | logmode = property(_get_mode,_set_mode) |
|
64 | 64 | |
|
65 | 65 | def logstart(self, logfname=None, loghead=None, logmode=None, |
|
66 | 66 | log_output=False, timestamp=False, log_raw_input=False): |
|
67 | 67 | """Generate a new log-file with a default header. |
|
68 | 68 | |
|
69 | 69 | Raises RuntimeError if the log has already been started""" |
|
70 | 70 | |
|
71 | 71 | if self.logfile is not None: |
|
72 | 72 | raise RuntimeError('Log file is already active: %s' % |
|
73 | 73 | self.logfname) |
|
74 | 74 | |
|
75 | 75 | # The parameters can override constructor defaults |
|
76 | 76 | if logfname is not None: self.logfname = logfname |
|
77 | 77 | if loghead is not None: self.loghead = loghead |
|
78 | 78 | if logmode is not None: self.logmode = logmode |
|
79 | 79 | |
|
80 | 80 | # Parameters not part of the constructor |
|
81 | 81 | self.timestamp = timestamp |
|
82 | 82 | self.log_output = log_output |
|
83 | 83 | self.log_raw_input = log_raw_input |
|
84 | 84 | |
|
85 | 85 | # init depending on the log mode requested |
|
86 | 86 | isfile = os.path.isfile |
|
87 | 87 | logmode = self.logmode |
|
88 | 88 | |
|
89 | 89 | if logmode == 'append': |
|
90 | 90 | self.logfile = io.open(self.logfname, 'a', encoding='utf-8') |
|
91 | 91 | |
|
92 | 92 | elif logmode == 'backup': |
|
93 | 93 | if isfile(self.logfname): |
|
94 | 94 | backup_logname = self.logfname+'~' |
|
95 | 95 | # Manually remove any old backup, since os.rename may fail |
|
96 | 96 | # under Windows. |
|
97 | 97 | if isfile(backup_logname): |
|
98 | 98 | os.remove(backup_logname) |
|
99 | 99 | os.rename(self.logfname,backup_logname) |
|
100 | 100 | self.logfile = io.open(self.logfname, 'w', encoding='utf-8') |
|
101 | 101 | |
|
102 | 102 | elif logmode == 'global': |
|
103 | 103 | self.logfname = os.path.join(self.home_dir,self.logfname) |
|
104 | 104 | self.logfile = io.open(self.logfname, 'a', encoding='utf-8') |
|
105 | 105 | |
|
106 | 106 | elif logmode == 'over': |
|
107 | 107 | if isfile(self.logfname): |
|
108 | 108 | os.remove(self.logfname) |
|
109 | 109 | self.logfile = io.open(self.logfname,'w', encoding='utf-8') |
|
110 | 110 | |
|
111 | 111 | elif logmode == 'rotate': |
|
112 | 112 | if isfile(self.logfname): |
|
113 | 113 | if isfile(self.logfname+'.001~'): |
|
114 | 114 | old = glob.glob(self.logfname+'.*~') |
|
115 | 115 | old.sort() |
|
116 | 116 | old.reverse() |
|
117 | 117 | for f in old: |
|
118 | 118 | root, ext = os.path.splitext(f) |
|
119 | 119 | num = int(ext[1:-1])+1 |
|
120 | 120 | os.rename(f, root+'.'+repr(num).zfill(3)+'~') |
|
121 | 121 | os.rename(self.logfname, self.logfname+'.001~') |
|
122 | 122 | self.logfile = io.open(self.logfname, 'w', encoding='utf-8') |
|
123 | 123 | |
|
124 | 124 | if logmode != 'append': |
|
125 | 125 | self.logfile.write(self.loghead) |
|
126 | 126 | |
|
127 | 127 | self.logfile.flush() |
|
128 | 128 | self.log_active = True |
|
129 | 129 | |
|
130 | 130 | def switch_log(self,val): |
|
131 | 131 | """Switch logging on/off. val should be ONLY a boolean.""" |
|
132 | 132 | |
|
133 | 133 | if val not in [False,True,0,1]: |
|
134 | raise ValueError, \ | |
|
135 | 'Call switch_log ONLY with a boolean argument, not with:',val | |
|
134 | raise ValueError('Call switch_log ONLY with a boolean argument, ' | |
|
135 | 'not with: %s' % val) | |
|
136 | 136 | |
|
137 | 137 | label = {0:'OFF',1:'ON',False:'OFF',True:'ON'} |
|
138 | 138 | |
|
139 | 139 | if self.logfile is None: |
|
140 | 140 | print """ |
|
141 | 141 | Logging hasn't been started yet (use logstart for that). |
|
142 | 142 | |
|
143 | 143 | %logon/%logoff are for temporarily starting and stopping logging for a logfile |
|
144 | 144 | which already exists. But you must first start the logging process with |
|
145 | 145 | %logstart (optionally giving a logfile name).""" |
|
146 | 146 | |
|
147 | 147 | else: |
|
148 | 148 | if self.log_active == val: |
|
149 | 149 | print 'Logging is already',label[val] |
|
150 | 150 | else: |
|
151 | 151 | print 'Switching logging',label[val] |
|
152 | 152 | self.log_active = not self.log_active |
|
153 | 153 | self.log_active_out = self.log_active |
|
154 | 154 | |
|
155 | 155 | def logstate(self): |
|
156 | 156 | """Print a status message about the logger.""" |
|
157 | 157 | if self.logfile is None: |
|
158 | 158 | print 'Logging has not been activated.' |
|
159 | 159 | else: |
|
160 | 160 | state = self.log_active and 'active' or 'temporarily suspended' |
|
161 | 161 | print 'Filename :',self.logfname |
|
162 | 162 | print 'Mode :',self.logmode |
|
163 | 163 | print 'Output logging :',self.log_output |
|
164 | 164 | print 'Raw input log :',self.log_raw_input |
|
165 | 165 | print 'Timestamping :',self.timestamp |
|
166 | 166 | print 'State :',state |
|
167 | 167 | |
|
168 | 168 | def log(self, line_mod, line_ori): |
|
169 | 169 | """Write the sources to a log. |
|
170 | 170 | |
|
171 | 171 | Inputs: |
|
172 | 172 | |
|
173 | 173 | - line_mod: possibly modified input, such as the transformations made |
|
174 | 174 | by input prefilters or input handlers of various kinds. This should |
|
175 | 175 | always be valid Python. |
|
176 | 176 | |
|
177 | 177 | - line_ori: unmodified input line from the user. This is not |
|
178 | 178 | necessarily valid Python. |
|
179 | 179 | """ |
|
180 | 180 | |
|
181 | 181 | # Write the log line, but decide which one according to the |
|
182 | 182 | # log_raw_input flag, set when the log is started. |
|
183 | 183 | if self.log_raw_input: |
|
184 | 184 | self.log_write(line_ori) |
|
185 | 185 | else: |
|
186 | 186 | self.log_write(line_mod) |
|
187 | 187 | |
|
188 | 188 | def log_write(self, data, kind='input'): |
|
189 | 189 | """Write data to the log file, if active""" |
|
190 | 190 | |
|
191 | 191 | #print 'data: %r' % data # dbg |
|
192 | 192 | if self.log_active and data: |
|
193 | 193 | write = self.logfile.write |
|
194 | 194 | if kind=='input': |
|
195 | 195 | if self.timestamp: |
|
196 | 196 | write(str_to_unicode(time.strftime('# %a, %d %b %Y %H:%M:%S\n', |
|
197 | 197 | time.localtime()))) |
|
198 | 198 | write(data) |
|
199 | 199 | elif kind=='output' and self.log_output: |
|
200 | 200 | odata = u'\n'.join([u'#[Out]# %s' % s |
|
201 | 201 | for s in data.splitlines()]) |
|
202 | 202 | write(u'%s\n' % odata) |
|
203 | 203 | self.logfile.flush() |
|
204 | 204 | |
|
205 | 205 | def logstop(self): |
|
206 | 206 | """Fully stop logging and close log file. |
|
207 | 207 | |
|
208 | 208 | In order to start logging again, a new logstart() call needs to be |
|
209 | 209 | made, possibly (though not necessarily) with a new filename, mode and |
|
210 | 210 | other options.""" |
|
211 | 211 | |
|
212 | 212 | if self.logfile is not None: |
|
213 | 213 | self.logfile.close() |
|
214 | 214 | self.logfile = None |
|
215 | 215 | else: |
|
216 | 216 | print "Logging hadn't been started." |
|
217 | 217 | self.log_active = False |
|
218 | 218 | |
|
219 | 219 | # For backwards compatibility, in case anyone was using this. |
|
220 | 220 | close_log = logstop |
@@ -1,617 +1,617 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 | #----------------------------------------------------------------------------- |
|
15 | 15 | # Imports |
|
16 | 16 | #----------------------------------------------------------------------------- |
|
17 | 17 | # Stdlib |
|
18 | 18 | import os |
|
19 | 19 | import re |
|
20 | 20 | import sys |
|
21 | 21 | import types |
|
22 | 22 | from getopt import getopt, GetoptError |
|
23 | 23 | |
|
24 | 24 | # Our own |
|
25 | 25 | from IPython.config.configurable import Configurable |
|
26 | 26 | from IPython.core import oinspect |
|
27 | 27 | from IPython.core.error import UsageError |
|
28 | 28 | from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2 |
|
29 | 29 | from IPython.external.decorator import decorator |
|
30 | 30 | from IPython.utils.ipstruct import Struct |
|
31 | 31 | from IPython.utils.process import arg_split |
|
32 | 32 | from IPython.utils.text import dedent |
|
33 | 33 | from IPython.utils.traitlets import Bool, Dict, Instance, MetaHasTraits |
|
34 | 34 | from IPython.utils.warn import error, warn |
|
35 | 35 | |
|
36 | 36 | #----------------------------------------------------------------------------- |
|
37 | 37 | # Globals |
|
38 | 38 | #----------------------------------------------------------------------------- |
|
39 | 39 | |
|
40 | 40 | # A dict we'll use for each class that has magics, used as temporary storage to |
|
41 | 41 | # pass information between the @line/cell_magic method decorators and the |
|
42 | 42 | # @magics_class class decorator, because the method decorators have no |
|
43 | 43 | # access to the class when they run. See for more details: |
|
44 | 44 | # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class |
|
45 | 45 | |
|
46 | 46 | magics = dict(line={}, cell={}) |
|
47 | 47 | |
|
48 | 48 | magic_kinds = ('line', 'cell') |
|
49 | 49 | magic_spec = ('line', 'cell', 'line_cell') |
|
50 | 50 | magic_escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC2) |
|
51 | 51 | |
|
52 | 52 | #----------------------------------------------------------------------------- |
|
53 | 53 | # Utility classes and functions |
|
54 | 54 | #----------------------------------------------------------------------------- |
|
55 | 55 | |
|
56 | 56 | class Bunch: pass |
|
57 | 57 | |
|
58 | 58 | |
|
59 | 59 | def on_off(tag): |
|
60 | 60 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
61 | 61 | return ['OFF','ON'][tag] |
|
62 | 62 | |
|
63 | 63 | |
|
64 | 64 | def compress_dhist(dh): |
|
65 | 65 | """Compress a directory history into a new one with at most 20 entries. |
|
66 | 66 | |
|
67 | 67 | Return a new list made from the first and last 10 elements of dhist after |
|
68 | 68 | removal of duplicates. |
|
69 | 69 | """ |
|
70 | 70 | head, tail = dh[:-10], dh[-10:] |
|
71 | 71 | |
|
72 | 72 | newhead = [] |
|
73 | 73 | done = set() |
|
74 | 74 | for h in head: |
|
75 | 75 | if h in done: |
|
76 | 76 | continue |
|
77 | 77 | newhead.append(h) |
|
78 | 78 | done.add(h) |
|
79 | 79 | |
|
80 | 80 | return newhead + tail |
|
81 | 81 | |
|
82 | 82 | |
|
83 | 83 | def needs_local_scope(func): |
|
84 | 84 | """Decorator to mark magic functions which need to local scope to run.""" |
|
85 | 85 | func.needs_local_scope = True |
|
86 | 86 | return func |
|
87 | 87 | |
|
88 | 88 | #----------------------------------------------------------------------------- |
|
89 | 89 | # Class and method decorators for registering magics |
|
90 | 90 | #----------------------------------------------------------------------------- |
|
91 | 91 | |
|
92 | 92 | def magics_class(cls): |
|
93 | 93 | """Class decorator for all subclasses of the main Magics class. |
|
94 | 94 | |
|
95 | 95 | Any class that subclasses Magics *must* also apply this decorator, to |
|
96 | 96 | ensure that all the methods that have been decorated as line/cell magics |
|
97 | 97 | get correctly registered in the class instance. This is necessary because |
|
98 | 98 | when method decorators run, the class does not exist yet, so they |
|
99 | 99 | temporarily store their information into a module global. Application of |
|
100 | 100 | this class decorator copies that global data to the class instance and |
|
101 | 101 | clears the global. |
|
102 | 102 | |
|
103 | 103 | Obviously, this mechanism is not thread-safe, which means that the |
|
104 | 104 | *creation* of subclasses of Magic should only be done in a single-thread |
|
105 | 105 | context. Instantiation of the classes has no restrictions. Given that |
|
106 | 106 | these classes are typically created at IPython startup time and before user |
|
107 | 107 | application code becomes active, in practice this should not pose any |
|
108 | 108 | problems. |
|
109 | 109 | """ |
|
110 | 110 | cls.registered = True |
|
111 | 111 | cls.magics = dict(line = magics['line'], |
|
112 | 112 | cell = magics['cell']) |
|
113 | 113 | magics['line'] = {} |
|
114 | 114 | magics['cell'] = {} |
|
115 | 115 | return cls |
|
116 | 116 | |
|
117 | 117 | |
|
118 | 118 | def record_magic(dct, magic_kind, magic_name, func): |
|
119 | 119 | """Utility function to store a function as a magic of a specific kind. |
|
120 | 120 | |
|
121 | 121 | Parameters |
|
122 | 122 | ---------- |
|
123 | 123 | dct : dict |
|
124 | 124 | A dictionary with 'line' and 'cell' subdicts. |
|
125 | 125 | |
|
126 | 126 | magic_kind : str |
|
127 | 127 | Kind of magic to be stored. |
|
128 | 128 | |
|
129 | 129 | magic_name : str |
|
130 | 130 | Key to store the magic as. |
|
131 | 131 | |
|
132 | 132 | func : function |
|
133 | 133 | Callable object to store. |
|
134 | 134 | """ |
|
135 | 135 | if magic_kind == 'line_cell': |
|
136 | 136 | dct['line'][magic_name] = dct['cell'][magic_name] = func |
|
137 | 137 | else: |
|
138 | 138 | dct[magic_kind][magic_name] = func |
|
139 | 139 | |
|
140 | 140 | |
|
141 | 141 | def validate_type(magic_kind): |
|
142 | 142 | """Ensure that the given magic_kind is valid. |
|
143 | 143 | |
|
144 | 144 | Check that the given magic_kind is one of the accepted spec types (stored |
|
145 | 145 | in the global `magic_spec`), raise ValueError otherwise. |
|
146 | 146 | """ |
|
147 | 147 | if magic_kind not in magic_spec: |
|
148 | 148 | raise ValueError('magic_kind must be one of %s, %s given' % |
|
149 | 149 | magic_kinds, magic_kind) |
|
150 | 150 | |
|
151 | 151 | |
|
152 | 152 | # The docstrings for the decorator below will be fairly similar for the two |
|
153 | 153 | # types (method and function), so we generate them here once and reuse the |
|
154 | 154 | # templates below. |
|
155 | 155 | _docstring_template = \ |
|
156 | 156 | """Decorate the given {0} as {1} magic. |
|
157 | 157 | |
|
158 | 158 | The decorator can be used with or without arguments, as follows. |
|
159 | 159 | |
|
160 | 160 | i) without arguments: it will create a {1} magic named as the {0} being |
|
161 | 161 | decorated:: |
|
162 | 162 | |
|
163 | 163 | @deco |
|
164 | 164 | def foo(...) |
|
165 | 165 | |
|
166 | 166 | will create a {1} magic named `foo`. |
|
167 | 167 | |
|
168 | 168 | ii) with one string argument: which will be used as the actual name of the |
|
169 | 169 | resulting magic:: |
|
170 | 170 | |
|
171 | 171 | @deco('bar') |
|
172 | 172 | def foo(...) |
|
173 | 173 | |
|
174 | 174 | will create a {1} magic named `bar`. |
|
175 | 175 | """ |
|
176 | 176 | |
|
177 | 177 | # These two are decorator factories. While they are conceptually very similar, |
|
178 | 178 | # there are enough differences in the details that it's simpler to have them |
|
179 | 179 | # written as completely standalone functions rather than trying to share code |
|
180 | 180 | # and make a single one with convoluted logic. |
|
181 | 181 | |
|
182 | 182 | def _method_magic_marker(magic_kind): |
|
183 | 183 | """Decorator factory for methods in Magics subclasses. |
|
184 | 184 | """ |
|
185 | 185 | |
|
186 | 186 | validate_type(magic_kind) |
|
187 | 187 | |
|
188 | 188 | # This is a closure to capture the magic_kind. We could also use a class, |
|
189 | 189 | # but it's overkill for just that one bit of state. |
|
190 | 190 | def magic_deco(arg): |
|
191 | 191 | call = lambda f, *a, **k: f(*a, **k) |
|
192 | 192 | |
|
193 | 193 | if callable(arg): |
|
194 | 194 | # "Naked" decorator call (just @foo, no args) |
|
195 | 195 | func = arg |
|
196 | 196 | name = func.func_name |
|
197 | 197 | retval = decorator(call, func) |
|
198 | 198 | record_magic(magics, magic_kind, name, name) |
|
199 | 199 | elif isinstance(arg, basestring): |
|
200 | 200 | # Decorator called with arguments (@foo('bar')) |
|
201 | 201 | name = arg |
|
202 | 202 | def mark(func, *a, **kw): |
|
203 | 203 | record_magic(magics, magic_kind, name, func.func_name) |
|
204 | 204 | return decorator(call, func) |
|
205 | 205 | retval = mark |
|
206 | 206 | else: |
|
207 | 207 | raise TypeError("Decorator can only be called with " |
|
208 | 208 | "string or function") |
|
209 | 209 | return retval |
|
210 | 210 | |
|
211 | 211 | # Ensure the resulting decorator has a usable docstring |
|
212 | 212 | magic_deco.__doc__ = _docstring_template.format('method', magic_kind) |
|
213 | 213 | return magic_deco |
|
214 | 214 | |
|
215 | 215 | |
|
216 | 216 | def _function_magic_marker(magic_kind): |
|
217 | 217 | """Decorator factory for standalone functions. |
|
218 | 218 | """ |
|
219 | 219 | validate_type(magic_kind) |
|
220 | 220 | |
|
221 | 221 | # This is a closure to capture the magic_kind. We could also use a class, |
|
222 | 222 | # but it's overkill for just that one bit of state. |
|
223 | 223 | def magic_deco(arg): |
|
224 | 224 | call = lambda f, *a, **k: f(*a, **k) |
|
225 | 225 | |
|
226 | 226 | # Find get_ipython() in the caller's namespace |
|
227 | 227 | caller = sys._getframe(1) |
|
228 | 228 | for ns in ['f_locals', 'f_globals', 'f_builtins']: |
|
229 | 229 | get_ipython = getattr(caller, ns).get('get_ipython') |
|
230 | 230 | if get_ipython is not None: |
|
231 | 231 | break |
|
232 | 232 | else: |
|
233 | 233 | raise NameError('Decorator can only run in context where ' |
|
234 | 234 | '`get_ipython` exists') |
|
235 | 235 | |
|
236 | 236 | ip = get_ipython() |
|
237 | 237 | |
|
238 | 238 | if callable(arg): |
|
239 | 239 | # "Naked" decorator call (just @foo, no args) |
|
240 | 240 | func = arg |
|
241 | 241 | name = func.func_name |
|
242 | 242 | ip.register_magic_function(func, magic_kind, name) |
|
243 | 243 | retval = decorator(call, func) |
|
244 | 244 | elif isinstance(arg, basestring): |
|
245 | 245 | # Decorator called with arguments (@foo('bar')) |
|
246 | 246 | name = arg |
|
247 | 247 | def mark(func, *a, **kw): |
|
248 | 248 | ip.register_magic_function(func, magic_kind, name) |
|
249 | 249 | return decorator(call, func) |
|
250 | 250 | retval = mark |
|
251 | 251 | else: |
|
252 | 252 | raise TypeError("Decorator can only be called with " |
|
253 | 253 | "string or function") |
|
254 | 254 | return retval |
|
255 | 255 | |
|
256 | 256 | # Ensure the resulting decorator has a usable docstring |
|
257 | 257 | ds = _docstring_template.format('function', magic_kind) |
|
258 | 258 | |
|
259 | 259 | ds += dedent(""" |
|
260 | 260 | Note: this decorator can only be used in a context where IPython is already |
|
261 | 261 | active, so that the `get_ipython()` call succeeds. You can therefore use |
|
262 | 262 | it in your startup files loaded after IPython initializes, but *not* in the |
|
263 | 263 | IPython configuration file itself, which is executed before IPython is |
|
264 | 264 | fully up and running. Any file located in the `startup` subdirectory of |
|
265 | 265 | your configuration profile will be OK in this sense. |
|
266 | 266 | """) |
|
267 | 267 | |
|
268 | 268 | magic_deco.__doc__ = ds |
|
269 | 269 | return magic_deco |
|
270 | 270 | |
|
271 | 271 | |
|
272 | 272 | # Create the actual decorators for public use |
|
273 | 273 | |
|
274 | 274 | # These three are used to decorate methods in class definitions |
|
275 | 275 | line_magic = _method_magic_marker('line') |
|
276 | 276 | cell_magic = _method_magic_marker('cell') |
|
277 | 277 | line_cell_magic = _method_magic_marker('line_cell') |
|
278 | 278 | |
|
279 | 279 | # These three decorate standalone functions and perform the decoration |
|
280 | 280 | # immediately. They can only run where get_ipython() works |
|
281 | 281 | register_line_magic = _function_magic_marker('line') |
|
282 | 282 | register_cell_magic = _function_magic_marker('cell') |
|
283 | 283 | register_line_cell_magic = _function_magic_marker('line_cell') |
|
284 | 284 | |
|
285 | 285 | #----------------------------------------------------------------------------- |
|
286 | 286 | # Core Magic classes |
|
287 | 287 | #----------------------------------------------------------------------------- |
|
288 | 288 | |
|
289 | 289 | class MagicsManager(Configurable): |
|
290 | 290 | """Object that handles all magic-related functionality for IPython. |
|
291 | 291 | """ |
|
292 | 292 | # Non-configurable class attributes |
|
293 | 293 | |
|
294 | 294 | # A two-level dict, first keyed by magic type, then by magic function, and |
|
295 | 295 | # holding the actual callable object as value. This is the dict used for |
|
296 | 296 | # magic function dispatch |
|
297 | 297 | magics = Dict |
|
298 | 298 | |
|
299 | 299 | # A registry of the original objects that we've been given holding magics. |
|
300 | 300 | registry = Dict |
|
301 | 301 | |
|
302 | 302 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
303 | 303 | |
|
304 | 304 | auto_magic = Bool(True, config=True, help= |
|
305 | 305 | "Automatically call line magics without requiring explicit % prefix") |
|
306 | 306 | |
|
307 | 307 | _auto_status = [ |
|
308 | 308 | 'Automagic is OFF, % prefix IS needed for line magics.', |
|
309 | 309 | 'Automagic is ON, % prefix IS NOT needed for line magics.'] |
|
310 | 310 | |
|
311 | 311 | user_magics = Instance('IPython.core.magics.UserMagics') |
|
312 | 312 | |
|
313 | 313 | def __init__(self, shell=None, config=None, user_magics=None, **traits): |
|
314 | 314 | |
|
315 | 315 | super(MagicsManager, self).__init__(shell=shell, config=config, |
|
316 | 316 | user_magics=user_magics, **traits) |
|
317 | 317 | self.magics = dict(line={}, cell={}) |
|
318 | 318 | # Let's add the user_magics to the registry for uniformity, so *all* |
|
319 | 319 | # registered magic containers can be found there. |
|
320 | 320 | self.registry[user_magics.__class__.__name__] = user_magics |
|
321 | 321 | |
|
322 | 322 | def auto_status(self): |
|
323 | 323 | """Return descriptive string with automagic status.""" |
|
324 | 324 | return self._auto_status[self.auto_magic] |
|
325 | 325 | |
|
326 | 326 | def lsmagic_info(self): |
|
327 | 327 | magic_list = [] |
|
328 | 328 | for m_type in self.magics : |
|
329 | 329 | for m_name,mgc in self.magics[m_type].items(): |
|
330 | 330 | try : |
|
331 | 331 | magic_list.append({'name':m_name,'type':m_type,'class':mgc.im_class.__name__}) |
|
332 | 332 | except AttributeError : |
|
333 | 333 | magic_list.append({'name':m_name,'type':m_type,'class':'Other'}) |
|
334 | 334 | return magic_list |
|
335 | 335 | |
|
336 | 336 | def lsmagic(self): |
|
337 | 337 | """Return a dict of currently available magic functions. |
|
338 | 338 | |
|
339 | 339 | The return dict has the keys 'line' and 'cell', corresponding to the |
|
340 | 340 | two types of magics we support. Each value is a list of names. |
|
341 | 341 | """ |
|
342 | 342 | return self.magics |
|
343 | 343 | |
|
344 | 344 | def lsmagic_docs(self, brief=False, missing=''): |
|
345 | 345 | """Return dict of documentation of magic functions. |
|
346 | 346 | |
|
347 | 347 | The return dict has the keys 'line' and 'cell', corresponding to the |
|
348 | 348 | two types of magics we support. Each value is a dict keyed by magic |
|
349 | 349 | name whose value is the function docstring. If a docstring is |
|
350 | 350 | unavailable, the value of `missing` is used instead. |
|
351 | 351 | |
|
352 | 352 | If brief is True, only the first line of each docstring will be returned. |
|
353 | 353 | """ |
|
354 | 354 | docs = {} |
|
355 | 355 | for m_type in self.magics: |
|
356 | 356 | m_docs = {} |
|
357 | 357 | for m_name, m_func in self.magics[m_type].iteritems(): |
|
358 | 358 | if m_func.__doc__: |
|
359 | 359 | if brief: |
|
360 | 360 | m_docs[m_name] = m_func.__doc__.split('\n', 1)[0] |
|
361 | 361 | else: |
|
362 | 362 | m_docs[m_name] = m_func.__doc__.rstrip() |
|
363 | 363 | else: |
|
364 | 364 | m_docs[m_name] = missing |
|
365 | 365 | docs[m_type] = m_docs |
|
366 | 366 | return docs |
|
367 | 367 | |
|
368 | 368 | def register(self, *magic_objects): |
|
369 | 369 | """Register one or more instances of Magics. |
|
370 | 370 | |
|
371 | 371 | Take one or more classes or instances of classes that subclass the main |
|
372 | 372 | `core.Magic` class, and register them with IPython to use the magic |
|
373 | 373 | functions they provide. The registration process will then ensure that |
|
374 | 374 | any methods that have decorated to provide line and/or cell magics will |
|
375 | 375 | be recognized with the `%x`/`%%x` syntax as a line/cell magic |
|
376 | 376 | respectively. |
|
377 | 377 | |
|
378 | 378 | If classes are given, they will be instantiated with the default |
|
379 | 379 | constructor. If your classes need a custom constructor, you should |
|
380 | 380 | instanitate them first and pass the instance. |
|
381 | 381 | |
|
382 | 382 | The provided arguments can be an arbitrary mix of classes and instances. |
|
383 | 383 | |
|
384 | 384 | Parameters |
|
385 | 385 | ---------- |
|
386 | 386 | magic_objects : one or more classes or instances |
|
387 | 387 | """ |
|
388 | 388 | # Start by validating them to ensure they have all had their magic |
|
389 | 389 | # methods registered at the instance level |
|
390 | 390 | for m in magic_objects: |
|
391 | 391 | if not m.registered: |
|
392 | 392 | raise ValueError("Class of magics %r was constructed without " |
|
393 | 393 | "the @register_magics class decorator") |
|
394 | 394 | if type(m) in (type, MetaHasTraits): |
|
395 | 395 | # If we're given an uninstantiated class |
|
396 | 396 | m = m(shell=self.shell) |
|
397 | 397 | |
|
398 | 398 | # Now that we have an instance, we can register it and update the |
|
399 | 399 | # table of callables |
|
400 | 400 | self.registry[m.__class__.__name__] = m |
|
401 | 401 | for mtype in magic_kinds: |
|
402 | 402 | self.magics[mtype].update(m.magics[mtype]) |
|
403 | 403 | |
|
404 | 404 | def register_function(self, func, magic_kind='line', magic_name=None): |
|
405 | 405 | """Expose a standalone function as magic function for IPython. |
|
406 | 406 | |
|
407 | 407 | This will create an IPython magic (line, cell or both) from a |
|
408 | 408 | standalone function. The functions should have the following |
|
409 | 409 | signatures: |
|
410 | 410 | |
|
411 | 411 | * For line magics: `def f(line)` |
|
412 | 412 | * For cell magics: `def f(line, cell)` |
|
413 | 413 | * For a function that does both: `def f(line, cell=None)` |
|
414 | 414 | |
|
415 | 415 | In the latter case, the function will be called with `cell==None` when |
|
416 | 416 | invoked as `%f`, and with cell as a string when invoked as `%%f`. |
|
417 | 417 | |
|
418 | 418 | Parameters |
|
419 | 419 | ---------- |
|
420 | 420 | func : callable |
|
421 | 421 | Function to be registered as a magic. |
|
422 | 422 | |
|
423 | 423 | magic_kind : str |
|
424 | 424 | Kind of magic, one of 'line', 'cell' or 'line_cell' |
|
425 | 425 | |
|
426 | 426 | magic_name : optional str |
|
427 | 427 | If given, the name the magic will have in the IPython namespace. By |
|
428 | 428 | default, the name of the function itself is used. |
|
429 | 429 | """ |
|
430 | 430 | |
|
431 | 431 | # Create the new method in the user_magics and register it in the |
|
432 | 432 | # global table |
|
433 | 433 | validate_type(magic_kind) |
|
434 | 434 | magic_name = func.func_name if magic_name is None else magic_name |
|
435 | 435 | setattr(self.user_magics, magic_name, func) |
|
436 | 436 | record_magic(self.magics, magic_kind, magic_name, func) |
|
437 | 437 | |
|
438 | 438 | def define_magic(self, name, func): |
|
439 | 439 | """[Deprecated] Expose own function as magic function for IPython. |
|
440 | 440 | |
|
441 | 441 | Example:: |
|
442 | 442 | |
|
443 | 443 | def foo_impl(self, parameter_s=''): |
|
444 | 444 | 'My very own magic!. (Use docstrings, IPython reads them).' |
|
445 | 445 | print 'Magic function. Passed parameter is between < >:' |
|
446 | 446 | print '<%s>' % parameter_s |
|
447 | 447 | print 'The self object is:', self |
|
448 | 448 | |
|
449 | 449 | ip.define_magic('foo',foo_impl) |
|
450 | 450 | """ |
|
451 | 451 | meth = types.MethodType(func, self.user_magics) |
|
452 | 452 | setattr(self.user_magics, name, meth) |
|
453 | 453 | record_magic(self.magics, 'line', name, meth) |
|
454 | 454 | |
|
455 | 455 | # Key base class that provides the central functionality for magics. |
|
456 | 456 | |
|
457 | 457 | class Magics(object): |
|
458 | 458 | """Base class for implementing magic functions. |
|
459 | 459 | |
|
460 | 460 | Shell functions which can be reached as %function_name. All magic |
|
461 | 461 | functions should accept a string, which they can parse for their own |
|
462 | 462 | needs. This can make some functions easier to type, eg `%cd ../` |
|
463 | 463 | vs. `%cd("../")` |
|
464 | 464 | |
|
465 | 465 | Classes providing magic functions need to subclass this class, and they |
|
466 | 466 | MUST: |
|
467 | 467 | |
|
468 | 468 | - Use the method decorators `@line_magic` and `@cell_magic` to decorate |
|
469 | 469 | individual methods as magic functions, AND |
|
470 | 470 | |
|
471 | 471 | - Use the class decorator `@magics_class` to ensure that the magic |
|
472 | 472 | methods are properly registered at the instance level upon instance |
|
473 | 473 | initialization. |
|
474 | 474 | |
|
475 | 475 | See :mod:`magic_functions` for examples of actual implementation classes. |
|
476 | 476 | """ |
|
477 | 477 | # Dict holding all command-line options for each magic. |
|
478 | 478 | options_table = None |
|
479 | 479 | # Dict for the mapping of magic names to methods, set by class decorator |
|
480 | 480 | magics = None |
|
481 | 481 | # Flag to check that the class decorator was properly applied |
|
482 | 482 | registered = False |
|
483 | 483 | # Instance of IPython shell |
|
484 | 484 | shell = None |
|
485 | 485 | |
|
486 | 486 | def __init__(self, shell): |
|
487 | 487 | if not(self.__class__.registered): |
|
488 | 488 | raise ValueError('Magics subclass without registration - ' |
|
489 | 489 | 'did you forget to apply @magics_class?') |
|
490 | 490 | self.shell = shell |
|
491 | 491 | self.options_table = {} |
|
492 | 492 | # The method decorators are run when the instance doesn't exist yet, so |
|
493 | 493 | # they can only record the names of the methods they are supposed to |
|
494 | 494 | # grab. Only now, that the instance exists, can we create the proper |
|
495 | 495 | # mapping to bound methods. So we read the info off the original names |
|
496 | 496 | # table and replace each method name by the actual bound method. |
|
497 | 497 | # But we mustn't clobber the *class* mapping, in case of multiple instances. |
|
498 | 498 | class_magics = self.magics |
|
499 | 499 | self.magics = {} |
|
500 | 500 | for mtype in magic_kinds: |
|
501 | 501 | tab = self.magics[mtype] = {} |
|
502 | 502 | cls_tab = class_magics[mtype] |
|
503 | 503 | for magic_name, meth_name in cls_tab.iteritems(): |
|
504 | 504 | if isinstance(meth_name, basestring): |
|
505 | 505 | # it's a method name, grab it |
|
506 | 506 | tab[magic_name] = getattr(self, meth_name) |
|
507 | 507 | else: |
|
508 | 508 | # it's the real thing |
|
509 | 509 | tab[magic_name] = meth_name |
|
510 | 510 | |
|
511 | 511 | def arg_err(self,func): |
|
512 | 512 | """Print docstring if incorrect arguments were passed""" |
|
513 | 513 | print 'Error in arguments:' |
|
514 | 514 | print oinspect.getdoc(func) |
|
515 | 515 | |
|
516 | 516 | def format_latex(self, strng): |
|
517 | 517 | """Format a string for latex inclusion.""" |
|
518 | 518 | |
|
519 | 519 | # Characters that need to be escaped for latex: |
|
520 | 520 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
521 | 521 | # Magic command names as headers: |
|
522 | 522 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, |
|
523 | 523 | re.MULTILINE) |
|
524 | 524 | # Magic commands |
|
525 | 525 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, |
|
526 | 526 | re.MULTILINE) |
|
527 | 527 | # Paragraph continue |
|
528 | 528 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
529 | 529 | |
|
530 | 530 | # The "\n" symbol |
|
531 | 531 | newline_re = re.compile(r'\\n') |
|
532 | 532 | |
|
533 | 533 | # Now build the string for output: |
|
534 | 534 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
535 | 535 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
536 | 536 | strng) |
|
537 | 537 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
538 | 538 | strng = par_re.sub(r'\\\\',strng) |
|
539 | 539 | strng = escape_re.sub(r'\\\1',strng) |
|
540 | 540 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
541 | 541 | return strng |
|
542 | 542 | |
|
543 | 543 | def parse_options(self, arg_str, opt_str, *long_opts, **kw): |
|
544 | 544 | """Parse options passed to an argument string. |
|
545 | 545 | |
|
546 | 546 | The interface is similar to that of getopt(), but it returns back a |
|
547 | 547 | Struct with the options as keys and the stripped argument string still |
|
548 | 548 | as a string. |
|
549 | 549 | |
|
550 | 550 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
551 | 551 | This allows us to easily expand variables, glob files, quote |
|
552 | 552 | arguments, etc. |
|
553 | 553 | |
|
554 | 554 | Options: |
|
555 | 555 | -mode: default 'string'. If given as 'list', the argument string is |
|
556 | 556 | returned as a list (split on whitespace) instead of a string. |
|
557 | 557 | |
|
558 | 558 | -list_all: put all option values in lists. Normally only options |
|
559 | 559 | appearing more than once are put in a list. |
|
560 | 560 | |
|
561 | 561 | -posix (True): whether to split the input line in POSIX mode or not, |
|
562 | 562 | as per the conventions outlined in the shlex module from the |
|
563 | 563 | standard library.""" |
|
564 | 564 | |
|
565 | 565 | # inject default options at the beginning of the input line |
|
566 | 566 | caller = sys._getframe(1).f_code.co_name |
|
567 | 567 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
568 | 568 | |
|
569 | 569 | mode = kw.get('mode','string') |
|
570 | 570 | if mode not in ['string','list']: |
|
571 |
raise ValueError |
|
|
571 | raise ValueError('incorrect mode given: %s' % mode) | |
|
572 | 572 | # Get options |
|
573 | 573 | list_all = kw.get('list_all',0) |
|
574 | 574 | posix = kw.get('posix', os.name == 'posix') |
|
575 | 575 | strict = kw.get('strict', True) |
|
576 | 576 | |
|
577 | 577 | # Check if we have more than one argument to warrant extra processing: |
|
578 | 578 | odict = {} # Dictionary with options |
|
579 | 579 | args = arg_str.split() |
|
580 | 580 | if len(args) >= 1: |
|
581 | 581 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
582 | 582 | # need to look for options |
|
583 | 583 | argv = arg_split(arg_str, posix, strict) |
|
584 | 584 | # Do regular option processing |
|
585 | 585 | try: |
|
586 | 586 | opts,args = getopt(argv, opt_str, long_opts) |
|
587 | 587 | except GetoptError as e: |
|
588 | 588 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
589 | 589 | " ".join(long_opts))) |
|
590 | 590 | for o,a in opts: |
|
591 | 591 | if o.startswith('--'): |
|
592 | 592 | o = o[2:] |
|
593 | 593 | else: |
|
594 | 594 | o = o[1:] |
|
595 | 595 | try: |
|
596 | 596 | odict[o].append(a) |
|
597 | 597 | except AttributeError: |
|
598 | 598 | odict[o] = [odict[o],a] |
|
599 | 599 | except KeyError: |
|
600 | 600 | if list_all: |
|
601 | 601 | odict[o] = [a] |
|
602 | 602 | else: |
|
603 | 603 | odict[o] = a |
|
604 | 604 | |
|
605 | 605 | # Prepare opts,args for return |
|
606 | 606 | opts = Struct(odict) |
|
607 | 607 | if mode == 'string': |
|
608 | 608 | args = ' '.join(args) |
|
609 | 609 | |
|
610 | 610 | return opts,args |
|
611 | 611 | |
|
612 | 612 | def default_option(self, fn, optstr): |
|
613 | 613 | """Make an entry in the options_table for fn, with value optstr""" |
|
614 | 614 | |
|
615 | 615 | if fn not in self.lsmagic(): |
|
616 | 616 | error("%s is not a magic function" % fn) |
|
617 | 617 | self.options_table[fn] = optstr |
@@ -1,1244 +1,1244 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | ultratb.py -- Spice up your tracebacks! |
|
4 | 4 | |
|
5 | 5 | * ColorTB |
|
6 | 6 | I've always found it a bit hard to visually parse tracebacks in Python. The |
|
7 | 7 | ColorTB class is a solution to that problem. It colors the different parts of a |
|
8 | 8 | traceback in a manner similar to what you would expect from a syntax-highlighting |
|
9 | 9 | text editor. |
|
10 | 10 | |
|
11 | 11 | Installation instructions for ColorTB: |
|
12 | 12 | import sys,ultratb |
|
13 | 13 | sys.excepthook = ultratb.ColorTB() |
|
14 | 14 | |
|
15 | 15 | * VerboseTB |
|
16 | 16 | I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds |
|
17 | 17 | of useful info when a traceback occurs. Ping originally had it spit out HTML |
|
18 | 18 | and intended it for CGI programmers, but why should they have all the fun? I |
|
19 | 19 | altered it to spit out colored text to the terminal. It's a bit overwhelming, |
|
20 | 20 | but kind of neat, and maybe useful for long-running programs that you believe |
|
21 | 21 | are bug-free. If a crash *does* occur in that type of program you want details. |
|
22 | 22 | Give it a shot--you'll love it or you'll hate it. |
|
23 | 23 | |
|
24 | 24 | Note: |
|
25 | 25 | |
|
26 | 26 | The Verbose mode prints the variables currently visible where the exception |
|
27 | 27 | happened (shortening their strings if too long). This can potentially be |
|
28 | 28 | very slow, if you happen to have a huge data structure whose string |
|
29 | 29 | representation is complex to compute. Your computer may appear to freeze for |
|
30 | 30 | a while with cpu usage at 100%. If this occurs, you can cancel the traceback |
|
31 | 31 | with Ctrl-C (maybe hitting it more than once). |
|
32 | 32 | |
|
33 | 33 | If you encounter this kind of situation often, you may want to use the |
|
34 | 34 | Verbose_novars mode instead of the regular Verbose, which avoids formatting |
|
35 | 35 | variables (but otherwise includes the information and context given by |
|
36 | 36 | Verbose). |
|
37 | 37 | |
|
38 | 38 | |
|
39 | 39 | Installation instructions for ColorTB: |
|
40 | 40 | import sys,ultratb |
|
41 | 41 | sys.excepthook = ultratb.VerboseTB() |
|
42 | 42 | |
|
43 | 43 | Note: Much of the code in this module was lifted verbatim from the standard |
|
44 | 44 | library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'. |
|
45 | 45 | |
|
46 | 46 | * Color schemes |
|
47 | 47 | The colors are defined in the class TBTools through the use of the |
|
48 | 48 | ColorSchemeTable class. Currently the following exist: |
|
49 | 49 | |
|
50 | 50 | - NoColor: allows all of this module to be used in any terminal (the color |
|
51 | 51 | escapes are just dummy blank strings). |
|
52 | 52 | |
|
53 | 53 | - Linux: is meant to look good in a terminal like the Linux console (black |
|
54 | 54 | or very dark background). |
|
55 | 55 | |
|
56 | 56 | - LightBG: similar to Linux but swaps dark/light colors to be more readable |
|
57 | 57 | in light background terminals. |
|
58 | 58 | |
|
59 | 59 | You can implement other color schemes easily, the syntax is fairly |
|
60 | 60 | self-explanatory. Please send back new schemes you develop to the author for |
|
61 | 61 | possible inclusion in future releases. |
|
62 | 62 | """ |
|
63 | 63 | |
|
64 | 64 | #***************************************************************************** |
|
65 | 65 | # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu> |
|
66 | 66 | # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu> |
|
67 | 67 | # |
|
68 | 68 | # Distributed under the terms of the BSD License. The full license is in |
|
69 | 69 | # the file COPYING, distributed as part of this software. |
|
70 | 70 | #***************************************************************************** |
|
71 | 71 | |
|
72 | 72 | from __future__ import with_statement |
|
73 | 73 | |
|
74 | 74 | import inspect |
|
75 | 75 | import keyword |
|
76 | 76 | import linecache |
|
77 | 77 | import os |
|
78 | 78 | import pydoc |
|
79 | 79 | import re |
|
80 | 80 | import sys |
|
81 | 81 | import time |
|
82 | 82 | import tokenize |
|
83 | 83 | import traceback |
|
84 | 84 | import types |
|
85 | 85 | |
|
86 | 86 | try: # Python 2 |
|
87 | 87 | generate_tokens = tokenize.generate_tokens |
|
88 | 88 | except AttributeError: # Python 3 |
|
89 | 89 | generate_tokens = tokenize.tokenize |
|
90 | 90 | |
|
91 | 91 | # For purposes of monkeypatching inspect to fix a bug in it. |
|
92 | 92 | from inspect import getsourcefile, getfile, getmodule,\ |
|
93 | 93 | ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode |
|
94 | 94 | |
|
95 | 95 | # IPython's own modules |
|
96 | 96 | # Modified pdb which doesn't damage IPython's readline handling |
|
97 | 97 | from IPython.core import debugger, ipapi |
|
98 | 98 | from IPython.core.display_trap import DisplayTrap |
|
99 | 99 | from IPython.core.excolors import exception_colors |
|
100 | 100 | from IPython.utils import PyColorize |
|
101 | 101 | from IPython.utils import io |
|
102 | 102 | from IPython.utils import py3compat |
|
103 | 103 | from IPython.utils import pyfile |
|
104 | 104 | from IPython.utils.data import uniq_stable |
|
105 | 105 | from IPython.utils.warn import info, error |
|
106 | 106 | |
|
107 | 107 | # Globals |
|
108 | 108 | # amount of space to put line numbers before verbose tracebacks |
|
109 | 109 | INDENT_SIZE = 8 |
|
110 | 110 | |
|
111 | 111 | # Default color scheme. This is used, for example, by the traceback |
|
112 | 112 | # formatter. When running in an actual IPython instance, the user's rc.colors |
|
113 | 113 | # value is used, but havinga module global makes this functionality available |
|
114 | 114 | # to users of ultratb who are NOT running inside ipython. |
|
115 | 115 | DEFAULT_SCHEME = 'NoColor' |
|
116 | 116 | |
|
117 | 117 | #--------------------------------------------------------------------------- |
|
118 | 118 | # Code begins |
|
119 | 119 | |
|
120 | 120 | # Utility functions |
|
121 | 121 | def inspect_error(): |
|
122 | 122 | """Print a message about internal inspect errors. |
|
123 | 123 | |
|
124 | 124 | These are unfortunately quite common.""" |
|
125 | 125 | |
|
126 | 126 | error('Internal Python error in the inspect module.\n' |
|
127 | 127 | 'Below is the traceback from this internal error.\n') |
|
128 | 128 | |
|
129 | 129 | |
|
130 | 130 | # N.B. This function is a monkeypatch we are currently not applying. |
|
131 | 131 | # It was written some time ago, to fix an apparent Python bug with |
|
132 | 132 | # codeobj.co_firstlineno . Unfortunately, we don't know under what conditions |
|
133 | 133 | # the bug occurred, so we can't tell if it has been fixed. If it reappears, we |
|
134 | 134 | # will apply the monkeypatch again. Also, note that findsource() is not called |
|
135 | 135 | # by our code at this time - we don't know if it was when the monkeypatch was |
|
136 | 136 | # written, or if the monkeypatch is needed for some other code (like a debugger). |
|
137 | 137 | # For the discussion about not applying it, see gh-1229. TK, Jan 2011. |
|
138 | 138 | def findsource(object): |
|
139 | 139 | """Return the entire source file and starting line number for an object. |
|
140 | 140 | |
|
141 | 141 | The argument may be a module, class, method, function, traceback, frame, |
|
142 | 142 | or code object. The source code is returned as a list of all the lines |
|
143 | 143 | in the file and the line number indexes a line in that list. An IOError |
|
144 | 144 | is raised if the source code cannot be retrieved. |
|
145 | 145 | |
|
146 | 146 | FIXED version with which we monkeypatch the stdlib to work around a bug.""" |
|
147 | 147 | |
|
148 | 148 | file = getsourcefile(object) or getfile(object) |
|
149 | 149 | # If the object is a frame, then trying to get the globals dict from its |
|
150 | 150 | # module won't work. Instead, the frame object itself has the globals |
|
151 | 151 | # dictionary. |
|
152 | 152 | globals_dict = None |
|
153 | 153 | if inspect.isframe(object): |
|
154 | 154 | # XXX: can this ever be false? |
|
155 | 155 | globals_dict = object.f_globals |
|
156 | 156 | else: |
|
157 | 157 | module = getmodule(object, file) |
|
158 | 158 | if module: |
|
159 | 159 | globals_dict = module.__dict__ |
|
160 | 160 | lines = linecache.getlines(file, globals_dict) |
|
161 | 161 | if not lines: |
|
162 | 162 | raise IOError('could not get source code') |
|
163 | 163 | |
|
164 | 164 | if ismodule(object): |
|
165 | 165 | return lines, 0 |
|
166 | 166 | |
|
167 | 167 | if isclass(object): |
|
168 | 168 | name = object.__name__ |
|
169 | 169 | pat = re.compile(r'^(\s*)class\s*' + name + r'\b') |
|
170 | 170 | # make some effort to find the best matching class definition: |
|
171 | 171 | # use the one with the least indentation, which is the one |
|
172 | 172 | # that's most probably not inside a function definition. |
|
173 | 173 | candidates = [] |
|
174 | 174 | for i in range(len(lines)): |
|
175 | 175 | match = pat.match(lines[i]) |
|
176 | 176 | if match: |
|
177 | 177 | # if it's at toplevel, it's already the best one |
|
178 | 178 | if lines[i][0] == 'c': |
|
179 | 179 | return lines, i |
|
180 | 180 | # else add whitespace to candidate list |
|
181 | 181 | candidates.append((match.group(1), i)) |
|
182 | 182 | if candidates: |
|
183 | 183 | # this will sort by whitespace, and by line number, |
|
184 | 184 | # less whitespace first |
|
185 | 185 | candidates.sort() |
|
186 | 186 | return lines, candidates[0][1] |
|
187 | 187 | else: |
|
188 | 188 | raise IOError('could not find class definition') |
|
189 | 189 | |
|
190 | 190 | if ismethod(object): |
|
191 | 191 | object = object.im_func |
|
192 | 192 | if isfunction(object): |
|
193 | 193 | object = object.func_code |
|
194 | 194 | if istraceback(object): |
|
195 | 195 | object = object.tb_frame |
|
196 | 196 | if isframe(object): |
|
197 | 197 | object = object.f_code |
|
198 | 198 | if iscode(object): |
|
199 | 199 | if not hasattr(object, 'co_firstlineno'): |
|
200 | 200 | raise IOError('could not find function definition') |
|
201 | 201 | pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)') |
|
202 | 202 | pmatch = pat.match |
|
203 | 203 | # fperez - fix: sometimes, co_firstlineno can give a number larger than |
|
204 | 204 | # the length of lines, which causes an error. Safeguard against that. |
|
205 | 205 | lnum = min(object.co_firstlineno,len(lines))-1 |
|
206 | 206 | while lnum > 0: |
|
207 | 207 | if pmatch(lines[lnum]): break |
|
208 | 208 | lnum -= 1 |
|
209 | 209 | |
|
210 | 210 | return lines, lnum |
|
211 | 211 | raise IOError('could not find code object') |
|
212 | 212 | |
|
213 | 213 | # Not applying the monkeypatch - see above the function for details. TK, Jan 2012 |
|
214 | 214 | # Monkeypatch inspect to apply our bugfix. This code only works with py25 |
|
215 | 215 | #if sys.version_info[:2] >= (2,5): |
|
216 | 216 | # inspect.findsource = findsource |
|
217 | 217 | |
|
218 | 218 | def fix_frame_records_filenames(records): |
|
219 | 219 | """Try to fix the filenames in each record from inspect.getinnerframes(). |
|
220 | 220 | |
|
221 | 221 | Particularly, modules loaded from within zip files have useless filenames |
|
222 | 222 | attached to their code object, and inspect.getinnerframes() just uses it. |
|
223 | 223 | """ |
|
224 | 224 | fixed_records = [] |
|
225 | 225 | for frame, filename, line_no, func_name, lines, index in records: |
|
226 | 226 | # Look inside the frame's globals dictionary for __file__, which should |
|
227 | 227 | # be better. |
|
228 | 228 | better_fn = frame.f_globals.get('__file__', None) |
|
229 | 229 | if isinstance(better_fn, str): |
|
230 | 230 | # Check the type just in case someone did something weird with |
|
231 | 231 | # __file__. It might also be None if the error occurred during |
|
232 | 232 | # import. |
|
233 | 233 | filename = better_fn |
|
234 | 234 | fixed_records.append((frame, filename, line_no, func_name, lines, index)) |
|
235 | 235 | return fixed_records |
|
236 | 236 | |
|
237 | 237 | |
|
238 | 238 | def _fixed_getinnerframes(etb, context=1,tb_offset=0): |
|
239 | 239 | import linecache |
|
240 | 240 | LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5 |
|
241 | 241 | |
|
242 | 242 | records = fix_frame_records_filenames(inspect.getinnerframes(etb, context)) |
|
243 | 243 | |
|
244 | 244 | # If the error is at the console, don't build any context, since it would |
|
245 | 245 | # otherwise produce 5 blank lines printed out (there is no file at the |
|
246 | 246 | # console) |
|
247 | 247 | rec_check = records[tb_offset:] |
|
248 | 248 | try: |
|
249 | 249 | rname = rec_check[0][1] |
|
250 | 250 | if rname == '<ipython console>' or rname.endswith('<string>'): |
|
251 | 251 | return rec_check |
|
252 | 252 | except IndexError: |
|
253 | 253 | pass |
|
254 | 254 | |
|
255 | 255 | aux = traceback.extract_tb(etb) |
|
256 | 256 | assert len(records) == len(aux) |
|
257 | 257 | for i, (file, lnum, _, _) in zip(range(len(records)), aux): |
|
258 | 258 | maybeStart = lnum-1 - context//2 |
|
259 | 259 | start = max(maybeStart, 0) |
|
260 | 260 | end = start + context |
|
261 | 261 | lines = linecache.getlines(file)[start:end] |
|
262 | 262 | buf = list(records[i]) |
|
263 | 263 | buf[LNUM_POS] = lnum |
|
264 | 264 | buf[INDEX_POS] = lnum - 1 - start |
|
265 | 265 | buf[LINES_POS] = lines |
|
266 | 266 | records[i] = tuple(buf) |
|
267 | 267 | return records[tb_offset:] |
|
268 | 268 | |
|
269 | 269 | # Helper function -- largely belongs to VerboseTB, but we need the same |
|
270 | 270 | # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they |
|
271 | 271 | # can be recognized properly by ipython.el's py-traceback-line-re |
|
272 | 272 | # (SyntaxErrors have to be treated specially because they have no traceback) |
|
273 | 273 | |
|
274 | 274 | _parser = PyColorize.Parser() |
|
275 | 275 | |
|
276 | 276 | def _format_traceback_lines(lnum, index, lines, Colors, lvals=None,scheme=None): |
|
277 | 277 | numbers_width = INDENT_SIZE - 1 |
|
278 | 278 | res = [] |
|
279 | 279 | i = lnum - index |
|
280 | 280 | |
|
281 | 281 | # This lets us get fully syntax-highlighted tracebacks. |
|
282 | 282 | if scheme is None: |
|
283 | 283 | ipinst = ipapi.get() |
|
284 | 284 | if ipinst is not None: |
|
285 | 285 | scheme = ipinst.colors |
|
286 | 286 | else: |
|
287 | 287 | scheme = DEFAULT_SCHEME |
|
288 | 288 | |
|
289 | 289 | _line_format = _parser.format2 |
|
290 | 290 | |
|
291 | 291 | for line in lines: |
|
292 | 292 | # FIXME: we need to ensure the source is a pure string at this point, |
|
293 | 293 | # else the coloring code makes a royal mess. This is in need of a |
|
294 | 294 | # serious refactoring, so that all of the ultratb and PyColorize code |
|
295 | 295 | # is unicode-safe. So for now this is rather an ugly hack, but |
|
296 | 296 | # necessary to at least have readable tracebacks. Improvements welcome! |
|
297 | 297 | line = py3compat.cast_bytes_py2(line, 'utf-8') |
|
298 | 298 | |
|
299 | 299 | new_line, err = _line_format(line, 'str', scheme) |
|
300 | 300 | if not err: line = new_line |
|
301 | 301 | |
|
302 | 302 | if i == lnum: |
|
303 | 303 | # This is the line with the error |
|
304 | 304 | pad = numbers_width - len(str(i)) |
|
305 | 305 | if pad >= 3: |
|
306 | 306 | marker = '-'*(pad-3) + '-> ' |
|
307 | 307 | elif pad == 2: |
|
308 | 308 | marker = '> ' |
|
309 | 309 | elif pad == 1: |
|
310 | 310 | marker = '>' |
|
311 | 311 | else: |
|
312 | 312 | marker = '' |
|
313 | 313 | num = marker + str(i) |
|
314 | 314 | line = '%s%s%s %s%s' %(Colors.linenoEm, num, |
|
315 | 315 | Colors.line, line, Colors.Normal) |
|
316 | 316 | else: |
|
317 | 317 | num = '%*s' % (numbers_width,i) |
|
318 | 318 | line = '%s%s%s %s' %(Colors.lineno, num, |
|
319 | 319 | Colors.Normal, line) |
|
320 | 320 | |
|
321 | 321 | res.append(line) |
|
322 | 322 | if lvals and i == lnum: |
|
323 | 323 | res.append(lvals + '\n') |
|
324 | 324 | i = i + 1 |
|
325 | 325 | return res |
|
326 | 326 | |
|
327 | 327 | |
|
328 | 328 | #--------------------------------------------------------------------------- |
|
329 | 329 | # Module classes |
|
330 | 330 | class TBTools(object): |
|
331 | 331 | """Basic tools used by all traceback printer classes.""" |
|
332 | 332 | |
|
333 | 333 | # Number of frames to skip when reporting tracebacks |
|
334 | 334 | tb_offset = 0 |
|
335 | 335 | |
|
336 | 336 | def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None): |
|
337 | 337 | # Whether to call the interactive pdb debugger after printing |
|
338 | 338 | # tracebacks or not |
|
339 | 339 | self.call_pdb = call_pdb |
|
340 | 340 | |
|
341 | 341 | # Output stream to write to. Note that we store the original value in |
|
342 | 342 | # a private attribute and then make the public ostream a property, so |
|
343 | 343 | # that we can delay accessing io.stdout until runtime. The way |
|
344 | 344 | # things are written now, the io.stdout object is dynamically managed |
|
345 | 345 | # so a reference to it should NEVER be stored statically. This |
|
346 | 346 | # property approach confines this detail to a single location, and all |
|
347 | 347 | # subclasses can simply access self.ostream for writing. |
|
348 | 348 | self._ostream = ostream |
|
349 | 349 | |
|
350 | 350 | # Create color table |
|
351 | 351 | self.color_scheme_table = exception_colors() |
|
352 | 352 | |
|
353 | 353 | self.set_colors(color_scheme) |
|
354 | 354 | self.old_scheme = color_scheme # save initial value for toggles |
|
355 | 355 | |
|
356 | 356 | if call_pdb: |
|
357 | 357 | self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name) |
|
358 | 358 | else: |
|
359 | 359 | self.pdb = None |
|
360 | 360 | |
|
361 | 361 | def _get_ostream(self): |
|
362 | 362 | """Output stream that exceptions are written to. |
|
363 | 363 | |
|
364 | 364 | Valid values are: |
|
365 | 365 | |
|
366 | 366 | - None: the default, which means that IPython will dynamically resolve |
|
367 | 367 | to io.stdout. This ensures compatibility with most tools, including |
|
368 | 368 | Windows (where plain stdout doesn't recognize ANSI escapes). |
|
369 | 369 | |
|
370 | 370 | - Any object with 'write' and 'flush' attributes. |
|
371 | 371 | """ |
|
372 | 372 | return io.stdout if self._ostream is None else self._ostream |
|
373 | 373 | |
|
374 | 374 | def _set_ostream(self, val): |
|
375 | 375 | assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush')) |
|
376 | 376 | self._ostream = val |
|
377 | 377 | |
|
378 | 378 | ostream = property(_get_ostream, _set_ostream) |
|
379 | 379 | |
|
380 | 380 | def set_colors(self,*args,**kw): |
|
381 | 381 | """Shorthand access to the color table scheme selector method.""" |
|
382 | 382 | |
|
383 | 383 | # Set own color table |
|
384 | 384 | self.color_scheme_table.set_active_scheme(*args,**kw) |
|
385 | 385 | # for convenience, set Colors to the active scheme |
|
386 | 386 | self.Colors = self.color_scheme_table.active_colors |
|
387 | 387 | # Also set colors of debugger |
|
388 | 388 | if hasattr(self,'pdb') and self.pdb is not None: |
|
389 | 389 | self.pdb.set_colors(*args,**kw) |
|
390 | 390 | |
|
391 | 391 | def color_toggle(self): |
|
392 | 392 | """Toggle between the currently active color scheme and NoColor.""" |
|
393 | 393 | |
|
394 | 394 | if self.color_scheme_table.active_scheme_name == 'NoColor': |
|
395 | 395 | self.color_scheme_table.set_active_scheme(self.old_scheme) |
|
396 | 396 | self.Colors = self.color_scheme_table.active_colors |
|
397 | 397 | else: |
|
398 | 398 | self.old_scheme = self.color_scheme_table.active_scheme_name |
|
399 | 399 | self.color_scheme_table.set_active_scheme('NoColor') |
|
400 | 400 | self.Colors = self.color_scheme_table.active_colors |
|
401 | 401 | |
|
402 | 402 | def stb2text(self, stb): |
|
403 | 403 | """Convert a structured traceback (a list) to a string.""" |
|
404 | 404 | return '\n'.join(stb) |
|
405 | 405 | |
|
406 | 406 | def text(self, etype, value, tb, tb_offset=None, context=5): |
|
407 | 407 | """Return formatted traceback. |
|
408 | 408 | |
|
409 | 409 | Subclasses may override this if they add extra arguments. |
|
410 | 410 | """ |
|
411 | 411 | tb_list = self.structured_traceback(etype, value, tb, |
|
412 | 412 | tb_offset, context) |
|
413 | 413 | return self.stb2text(tb_list) |
|
414 | 414 | |
|
415 | 415 | def structured_traceback(self, etype, evalue, tb, tb_offset=None, |
|
416 | 416 | context=5, mode=None): |
|
417 | 417 | """Return a list of traceback frames. |
|
418 | 418 | |
|
419 | 419 | Must be implemented by each class. |
|
420 | 420 | """ |
|
421 | 421 | raise NotImplementedError() |
|
422 | 422 | |
|
423 | 423 | |
|
424 | 424 | #--------------------------------------------------------------------------- |
|
425 | 425 | class ListTB(TBTools): |
|
426 | 426 | """Print traceback information from a traceback list, with optional color. |
|
427 | 427 | |
|
428 | 428 | Calling: requires 3 arguments: |
|
429 | 429 | (etype, evalue, elist) |
|
430 | 430 | as would be obtained by: |
|
431 | 431 | etype, evalue, tb = sys.exc_info() |
|
432 | 432 | if tb: |
|
433 | 433 | elist = traceback.extract_tb(tb) |
|
434 | 434 | else: |
|
435 | 435 | elist = None |
|
436 | 436 | |
|
437 | 437 | It can thus be used by programs which need to process the traceback before |
|
438 | 438 | printing (such as console replacements based on the code module from the |
|
439 | 439 | standard library). |
|
440 | 440 | |
|
441 | 441 | Because they are meant to be called without a full traceback (only a |
|
442 | 442 | list), instances of this class can't call the interactive pdb debugger.""" |
|
443 | 443 | |
|
444 | 444 | def __init__(self,color_scheme = 'NoColor', call_pdb=False, ostream=None): |
|
445 | 445 | TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, |
|
446 | 446 | ostream=ostream) |
|
447 | 447 | |
|
448 | 448 | def __call__(self, etype, value, elist): |
|
449 | 449 | self.ostream.flush() |
|
450 | 450 | self.ostream.write(self.text(etype, value, elist)) |
|
451 | 451 | self.ostream.write('\n') |
|
452 | 452 | |
|
453 | 453 | def structured_traceback(self, etype, value, elist, tb_offset=None, |
|
454 | 454 | context=5): |
|
455 | 455 | """Return a color formatted string with the traceback info. |
|
456 | 456 | |
|
457 | 457 | Parameters |
|
458 | 458 | ---------- |
|
459 | 459 | etype : exception type |
|
460 | 460 | Type of the exception raised. |
|
461 | 461 | |
|
462 | 462 | value : object |
|
463 | 463 | Data stored in the exception |
|
464 | 464 | |
|
465 | 465 | elist : list |
|
466 | 466 | List of frames, see class docstring for details. |
|
467 | 467 | |
|
468 | 468 | tb_offset : int, optional |
|
469 | 469 | Number of frames in the traceback to skip. If not given, the |
|
470 | 470 | instance value is used (set in constructor). |
|
471 | 471 | |
|
472 | 472 | context : int, optional |
|
473 | 473 | Number of lines of context information to print. |
|
474 | 474 | |
|
475 | 475 | Returns |
|
476 | 476 | ------- |
|
477 | 477 | String with formatted exception. |
|
478 | 478 | """ |
|
479 | 479 | tb_offset = self.tb_offset if tb_offset is None else tb_offset |
|
480 | 480 | Colors = self.Colors |
|
481 | 481 | out_list = [] |
|
482 | 482 | if elist: |
|
483 | 483 | |
|
484 | 484 | if tb_offset and len(elist) > tb_offset: |
|
485 | 485 | elist = elist[tb_offset:] |
|
486 | 486 | |
|
487 | 487 | out_list.append('Traceback %s(most recent call last)%s:' % |
|
488 | 488 | (Colors.normalEm, Colors.Normal) + '\n') |
|
489 | 489 | out_list.extend(self._format_list(elist)) |
|
490 | 490 | # The exception info should be a single entry in the list. |
|
491 | 491 | lines = ''.join(self._format_exception_only(etype, value)) |
|
492 | 492 | out_list.append(lines) |
|
493 | 493 | |
|
494 | 494 | # Note: this code originally read: |
|
495 | 495 | |
|
496 | 496 | ## for line in lines[:-1]: |
|
497 | 497 | ## out_list.append(" "+line) |
|
498 | 498 | ## out_list.append(lines[-1]) |
|
499 | 499 | |
|
500 | 500 | # This means it was indenting everything but the last line by a little |
|
501 | 501 | # bit. I've disabled this for now, but if we see ugliness somewhre we |
|
502 | 502 | # can restore it. |
|
503 | 503 | |
|
504 | 504 | return out_list |
|
505 | 505 | |
|
506 | 506 | def _format_list(self, extracted_list): |
|
507 | 507 | """Format a list of traceback entry tuples for printing. |
|
508 | 508 | |
|
509 | 509 | Given a list of tuples as returned by extract_tb() or |
|
510 | 510 | extract_stack(), return a list of strings ready for printing. |
|
511 | 511 | Each string in the resulting list corresponds to the item with the |
|
512 | 512 | same index in the argument list. Each string ends in a newline; |
|
513 | 513 | the strings may contain internal newlines as well, for those items |
|
514 | 514 | whose source text line is not None. |
|
515 | 515 | |
|
516 | 516 | Lifted almost verbatim from traceback.py |
|
517 | 517 | """ |
|
518 | 518 | |
|
519 | 519 | Colors = self.Colors |
|
520 | 520 | list = [] |
|
521 | 521 | for filename, lineno, name, line in extracted_list[:-1]: |
|
522 | 522 | item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \ |
|
523 | 523 | (Colors.filename, filename, Colors.Normal, |
|
524 | 524 | Colors.lineno, lineno, Colors.Normal, |
|
525 | 525 | Colors.name, name, Colors.Normal) |
|
526 | 526 | if line: |
|
527 | 527 | item += ' %s\n' % line.strip() |
|
528 | 528 | list.append(item) |
|
529 | 529 | # Emphasize the last entry |
|
530 | 530 | filename, lineno, name, line = extracted_list[-1] |
|
531 | 531 | item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \ |
|
532 | 532 | (Colors.normalEm, |
|
533 | 533 | Colors.filenameEm, filename, Colors.normalEm, |
|
534 | 534 | Colors.linenoEm, lineno, Colors.normalEm, |
|
535 | 535 | Colors.nameEm, name, Colors.normalEm, |
|
536 | 536 | Colors.Normal) |
|
537 | 537 | if line: |
|
538 | 538 | item += '%s %s%s\n' % (Colors.line, line.strip(), |
|
539 | 539 | Colors.Normal) |
|
540 | 540 | list.append(item) |
|
541 | 541 | #from pprint import pformat; print 'LISTTB', pformat(list) # dbg |
|
542 | 542 | return list |
|
543 | 543 | |
|
544 | 544 | def _format_exception_only(self, etype, value): |
|
545 | 545 | """Format the exception part of a traceback. |
|
546 | 546 | |
|
547 | 547 | The arguments are the exception type and value such as given by |
|
548 | 548 | sys.exc_info()[:2]. The return value is a list of strings, each ending |
|
549 | 549 | in a newline. Normally, the list contains a single string; however, |
|
550 | 550 | for SyntaxError exceptions, it contains several lines that (when |
|
551 | 551 | printed) display detailed information about where the syntax error |
|
552 | 552 | occurred. The message indicating which exception occurred is the |
|
553 | 553 | always last string in the list. |
|
554 | 554 | |
|
555 | 555 | Also lifted nearly verbatim from traceback.py |
|
556 | 556 | """ |
|
557 | 557 | |
|
558 | 558 | have_filedata = False |
|
559 | 559 | Colors = self.Colors |
|
560 | 560 | list = [] |
|
561 | 561 | stype = Colors.excName + etype.__name__ + Colors.Normal |
|
562 | 562 | if value is None: |
|
563 | 563 | # Not sure if this can still happen in Python 2.6 and above |
|
564 | 564 | list.append( str(stype) + '\n') |
|
565 | 565 | else: |
|
566 | 566 | if etype is SyntaxError: |
|
567 | 567 | have_filedata = True |
|
568 | 568 | #print 'filename is',filename # dbg |
|
569 | 569 | if not value.filename: value.filename = "<string>" |
|
570 | 570 | list.append('%s File %s"%s"%s, line %s%d%s\n' % \ |
|
571 | 571 | (Colors.normalEm, |
|
572 | 572 | Colors.filenameEm, value.filename, Colors.normalEm, |
|
573 | 573 | Colors.linenoEm, value.lineno, Colors.Normal )) |
|
574 | 574 | if value.text is not None: |
|
575 | 575 | i = 0 |
|
576 | 576 | while i < len(value.text) and value.text[i].isspace(): |
|
577 | 577 | i += 1 |
|
578 | 578 | list.append('%s %s%s\n' % (Colors.line, |
|
579 | 579 | value.text.strip(), |
|
580 | 580 | Colors.Normal)) |
|
581 | 581 | if value.offset is not None: |
|
582 | 582 | s = ' ' |
|
583 | 583 | for c in value.text[i:value.offset-1]: |
|
584 | 584 | if c.isspace(): |
|
585 | 585 | s += c |
|
586 | 586 | else: |
|
587 | 587 | s += ' ' |
|
588 | 588 | list.append('%s%s^%s\n' % (Colors.caret, s, |
|
589 | 589 | Colors.Normal) ) |
|
590 | 590 | |
|
591 | 591 | try: |
|
592 | 592 | s = value.msg |
|
593 | 593 | except Exception: |
|
594 | 594 | s = self._some_str(value) |
|
595 | 595 | if s: |
|
596 | 596 | list.append('%s%s:%s %s\n' % (str(stype), Colors.excName, |
|
597 | 597 | Colors.Normal, s)) |
|
598 | 598 | else: |
|
599 | 599 | list.append('%s\n' % str(stype)) |
|
600 | 600 | |
|
601 | 601 | # sync with user hooks |
|
602 | 602 | if have_filedata: |
|
603 | 603 | ipinst = ipapi.get() |
|
604 | 604 | if ipinst is not None: |
|
605 | 605 | ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0) |
|
606 | 606 | |
|
607 | 607 | return list |
|
608 | 608 | |
|
609 | 609 | def get_exception_only(self, etype, value): |
|
610 | 610 | """Only print the exception type and message, without a traceback. |
|
611 | 611 | |
|
612 | 612 | Parameters |
|
613 | 613 | ---------- |
|
614 | 614 | etype : exception type |
|
615 | 615 | value : exception value |
|
616 | 616 | """ |
|
617 | 617 | return ListTB.structured_traceback(self, etype, value, []) |
|
618 | 618 | |
|
619 | 619 | |
|
620 | 620 | def show_exception_only(self, etype, evalue): |
|
621 | 621 | """Only print the exception type and message, without a traceback. |
|
622 | 622 | |
|
623 | 623 | Parameters |
|
624 | 624 | ---------- |
|
625 | 625 | etype : exception type |
|
626 | 626 | value : exception value |
|
627 | 627 | """ |
|
628 | 628 | # This method needs to use __call__ from *this* class, not the one from |
|
629 | 629 | # a subclass whose signature or behavior may be different |
|
630 | 630 | ostream = self.ostream |
|
631 | 631 | ostream.flush() |
|
632 | 632 | ostream.write('\n'.join(self.get_exception_only(etype, evalue))) |
|
633 | 633 | ostream.flush() |
|
634 | 634 | |
|
635 | 635 | def _some_str(self, value): |
|
636 | 636 | # Lifted from traceback.py |
|
637 | 637 | try: |
|
638 | 638 | return str(value) |
|
639 | 639 | except: |
|
640 | 640 | return '<unprintable %s object>' % type(value).__name__ |
|
641 | 641 | |
|
642 | 642 | #---------------------------------------------------------------------------- |
|
643 | 643 | class VerboseTB(TBTools): |
|
644 | 644 | """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead |
|
645 | 645 | of HTML. Requires inspect and pydoc. Crazy, man. |
|
646 | 646 | |
|
647 | 647 | Modified version which optionally strips the topmost entries from the |
|
648 | 648 | traceback, to be used with alternate interpreters (because their own code |
|
649 | 649 | would appear in the traceback).""" |
|
650 | 650 | |
|
651 | 651 | def __init__(self,color_scheme = 'Linux', call_pdb=False, ostream=None, |
|
652 | 652 | tb_offset=0, long_header=False, include_vars=True, |
|
653 | 653 | check_cache=None): |
|
654 | 654 | """Specify traceback offset, headers and color scheme. |
|
655 | 655 | |
|
656 | 656 | Define how many frames to drop from the tracebacks. Calling it with |
|
657 | 657 | tb_offset=1 allows use of this handler in interpreters which will have |
|
658 | 658 | their own code at the top of the traceback (VerboseTB will first |
|
659 | 659 | remove that frame before printing the traceback info).""" |
|
660 | 660 | TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, |
|
661 | 661 | ostream=ostream) |
|
662 | 662 | self.tb_offset = tb_offset |
|
663 | 663 | self.long_header = long_header |
|
664 | 664 | self.include_vars = include_vars |
|
665 | 665 | # By default we use linecache.checkcache, but the user can provide a |
|
666 | 666 | # different check_cache implementation. This is used by the IPython |
|
667 | 667 | # kernel to provide tracebacks for interactive code that is cached, |
|
668 | 668 | # by a compiler instance that flushes the linecache but preserves its |
|
669 | 669 | # own code cache. |
|
670 | 670 | if check_cache is None: |
|
671 | 671 | check_cache = linecache.checkcache |
|
672 | 672 | self.check_cache = check_cache |
|
673 | 673 | |
|
674 | 674 | def structured_traceback(self, etype, evalue, etb, tb_offset=None, |
|
675 | 675 | context=5): |
|
676 | 676 | """Return a nice text document describing the traceback.""" |
|
677 | 677 | |
|
678 | 678 | tb_offset = self.tb_offset if tb_offset is None else tb_offset |
|
679 | 679 | |
|
680 | 680 | # some locals |
|
681 | 681 | try: |
|
682 | 682 | etype = etype.__name__ |
|
683 | 683 | except AttributeError: |
|
684 | 684 | pass |
|
685 | 685 | Colors = self.Colors # just a shorthand + quicker name lookup |
|
686 | 686 | ColorsNormal = Colors.Normal # used a lot |
|
687 | 687 | col_scheme = self.color_scheme_table.active_scheme_name |
|
688 | 688 | indent = ' '*INDENT_SIZE |
|
689 | 689 | em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal) |
|
690 | 690 | undefined = '%sundefined%s' % (Colors.em, ColorsNormal) |
|
691 | 691 | exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal) |
|
692 | 692 | |
|
693 | 693 | # some internal-use functions |
|
694 | 694 | def text_repr(value): |
|
695 | 695 | """Hopefully pretty robust repr equivalent.""" |
|
696 | 696 | # this is pretty horrible but should always return *something* |
|
697 | 697 | try: |
|
698 | 698 | return pydoc.text.repr(value) |
|
699 | 699 | except KeyboardInterrupt: |
|
700 | 700 | raise |
|
701 | 701 | except: |
|
702 | 702 | try: |
|
703 | 703 | return repr(value) |
|
704 | 704 | except KeyboardInterrupt: |
|
705 | 705 | raise |
|
706 | 706 | except: |
|
707 | 707 | try: |
|
708 | 708 | # all still in an except block so we catch |
|
709 | 709 | # getattr raising |
|
710 | 710 | name = getattr(value, '__name__', None) |
|
711 | 711 | if name: |
|
712 | 712 | # ick, recursion |
|
713 | 713 | return text_repr(name) |
|
714 | 714 | klass = getattr(value, '__class__', None) |
|
715 | 715 | if klass: |
|
716 | 716 | return '%s instance' % text_repr(klass) |
|
717 | 717 | except KeyboardInterrupt: |
|
718 | 718 | raise |
|
719 | 719 | except: |
|
720 | 720 | return 'UNRECOVERABLE REPR FAILURE' |
|
721 | 721 | def eqrepr(value, repr=text_repr): return '=%s' % repr(value) |
|
722 | 722 | def nullrepr(value, repr=text_repr): return '' |
|
723 | 723 | |
|
724 | 724 | # meat of the code begins |
|
725 | 725 | try: |
|
726 | 726 | etype = etype.__name__ |
|
727 | 727 | except AttributeError: |
|
728 | 728 | pass |
|
729 | 729 | |
|
730 | 730 | if self.long_header: |
|
731 | 731 | # Header with the exception type, python version, and date |
|
732 | 732 | pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable |
|
733 | 733 | date = time.ctime(time.time()) |
|
734 | 734 | |
|
735 | 735 | head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal, |
|
736 | 736 | exc, ' '*(75-len(str(etype))-len(pyver)), |
|
737 | 737 | pyver, date.rjust(75) ) |
|
738 | 738 | head += "\nA problem occured executing Python code. Here is the sequence of function"\ |
|
739 | 739 | "\ncalls leading up to the error, with the most recent (innermost) call last." |
|
740 | 740 | else: |
|
741 | 741 | # Simplified header |
|
742 | 742 | head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc, |
|
743 | 743 | 'Traceback (most recent call last)'.\ |
|
744 | 744 | rjust(75 - len(str(etype)) ) ) |
|
745 | 745 | frames = [] |
|
746 | 746 | # Flush cache before calling inspect. This helps alleviate some of the |
|
747 | 747 | # problems with python 2.3's inspect.py. |
|
748 | 748 | ##self.check_cache() |
|
749 | 749 | # Drop topmost frames if requested |
|
750 | 750 | try: |
|
751 | 751 | # Try the default getinnerframes and Alex's: Alex's fixes some |
|
752 | 752 | # problems, but it generates empty tracebacks for console errors |
|
753 | 753 | # (5 blanks lines) where none should be returned. |
|
754 | 754 | #records = inspect.getinnerframes(etb, context)[tb_offset:] |
|
755 | 755 | #print 'python records:', records # dbg |
|
756 | 756 | records = _fixed_getinnerframes(etb, context, tb_offset) |
|
757 | 757 | #print 'alex records:', records # dbg |
|
758 | 758 | except: |
|
759 | 759 | |
|
760 | 760 | # FIXME: I've been getting many crash reports from python 2.3 |
|
761 | 761 | # users, traceable to inspect.py. If I can find a small test-case |
|
762 | 762 | # to reproduce this, I should either write a better workaround or |
|
763 | 763 | # file a bug report against inspect (if that's the real problem). |
|
764 | 764 | # So far, I haven't been able to find an isolated example to |
|
765 | 765 | # reproduce the problem. |
|
766 | 766 | inspect_error() |
|
767 | 767 | traceback.print_exc(file=self.ostream) |
|
768 | 768 | info('\nUnfortunately, your original traceback can not be constructed.\n') |
|
769 | 769 | return '' |
|
770 | 770 | |
|
771 | 771 | # build some color string templates outside these nested loops |
|
772 | 772 | tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal) |
|
773 | 773 | tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm, |
|
774 | 774 | ColorsNormal) |
|
775 | 775 | tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \ |
|
776 | 776 | (Colors.vName, Colors.valEm, ColorsNormal) |
|
777 | 777 | tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal) |
|
778 | 778 | tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal, |
|
779 | 779 | Colors.vName, ColorsNormal) |
|
780 | 780 | tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal) |
|
781 | 781 | tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal) |
|
782 | 782 | tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line, |
|
783 | 783 | ColorsNormal) |
|
784 | 784 | |
|
785 | 785 | # now, loop over all records printing context and info |
|
786 | 786 | abspath = os.path.abspath |
|
787 | 787 | for frame, file, lnum, func, lines, index in records: |
|
788 | 788 | #print '*** record:',file,lnum,func,lines,index # dbg |
|
789 | 789 | |
|
790 | 790 | if not file: |
|
791 | 791 | file = '?' |
|
792 | 792 | elif not(file.startswith("<") and file.endswith(">")): |
|
793 | 793 | # Guess that filenames like <string> aren't real filenames, so |
|
794 | 794 | # don't call abspath on them. |
|
795 | 795 | try: |
|
796 | 796 | file = abspath(file) |
|
797 | 797 | except OSError: |
|
798 | 798 | # Not sure if this can still happen: abspath now works with |
|
799 | 799 | # file names like <string> |
|
800 | 800 | pass |
|
801 | 801 | |
|
802 | 802 | link = tpl_link % file |
|
803 | 803 | args, varargs, varkw, locals = inspect.getargvalues(frame) |
|
804 | 804 | |
|
805 | 805 | if func == '?': |
|
806 | 806 | call = '' |
|
807 | 807 | else: |
|
808 | 808 | # Decide whether to include variable details or not |
|
809 | 809 | var_repr = self.include_vars and eqrepr or nullrepr |
|
810 | 810 | try: |
|
811 | 811 | call = tpl_call % (func,inspect.formatargvalues(args, |
|
812 | 812 | varargs, varkw, |
|
813 | 813 | locals,formatvalue=var_repr)) |
|
814 | 814 | except KeyError: |
|
815 | 815 | # This happens in situations like errors inside generator |
|
816 | 816 | # expressions, where local variables are listed in the |
|
817 | 817 | # line, but can't be extracted from the frame. I'm not |
|
818 | 818 | # 100% sure this isn't actually a bug in inspect itself, |
|
819 | 819 | # but since there's no info for us to compute with, the |
|
820 | 820 | # best we can do is report the failure and move on. Here |
|
821 | 821 | # we must *not* call any traceback construction again, |
|
822 | 822 | # because that would mess up use of %debug later on. So we |
|
823 | 823 | # simply report the failure and move on. The only |
|
824 | 824 | # limitation will be that this frame won't have locals |
|
825 | 825 | # listed in the call signature. Quite subtle problem... |
|
826 | 826 | # I can't think of a good way to validate this in a unit |
|
827 | 827 | # test, but running a script consisting of: |
|
828 | 828 | # dict( (k,v.strip()) for (k,v) in range(10) ) |
|
829 | 829 | # will illustrate the error, if this exception catch is |
|
830 | 830 | # disabled. |
|
831 | 831 | call = tpl_call_fail % func |
|
832 | 832 | |
|
833 | 833 | # Don't attempt to tokenize binary files. |
|
834 | 834 | if file.endswith(('.so', '.pyd', '.dll')): |
|
835 | 835 | frames.append('%s %s\n' % (link,call)) |
|
836 | 836 | continue |
|
837 | 837 | elif file.endswith(('.pyc','.pyo')): |
|
838 | 838 | # Look up the corresponding source file. |
|
839 | 839 | file = pyfile.source_from_cache(file) |
|
840 | 840 | |
|
841 | 841 | def linereader(file=file, lnum=[lnum], getline=linecache.getline): |
|
842 | 842 | line = getline(file, lnum[0]) |
|
843 | 843 | lnum[0] += 1 |
|
844 | 844 | return line |
|
845 | 845 | |
|
846 | 846 | # Build the list of names on this line of code where the exception |
|
847 | 847 | # occurred. |
|
848 | 848 | try: |
|
849 | 849 | names = [] |
|
850 | 850 | name_cont = False |
|
851 | 851 | |
|
852 | 852 | for token_type, token, start, end, line in generate_tokens(linereader): |
|
853 | 853 | # build composite names |
|
854 | 854 | if token_type == tokenize.NAME and token not in keyword.kwlist: |
|
855 | 855 | if name_cont: |
|
856 | 856 | # Continuation of a dotted name |
|
857 | 857 | try: |
|
858 | 858 | names[-1].append(token) |
|
859 | 859 | except IndexError: |
|
860 | 860 | names.append([token]) |
|
861 | 861 | name_cont = False |
|
862 | 862 | else: |
|
863 | 863 | # Regular new names. We append everything, the caller |
|
864 | 864 | # will be responsible for pruning the list later. It's |
|
865 | 865 | # very tricky to try to prune as we go, b/c composite |
|
866 | 866 | # names can fool us. The pruning at the end is easy |
|
867 | 867 | # to do (or the caller can print a list with repeated |
|
868 | 868 | # names if so desired. |
|
869 | 869 | names.append([token]) |
|
870 | 870 | elif token == '.': |
|
871 | 871 | name_cont = True |
|
872 | 872 | elif token_type == tokenize.NEWLINE: |
|
873 | 873 | break |
|
874 | 874 | |
|
875 | 875 | except (IndexError, UnicodeDecodeError): |
|
876 | 876 | # signals exit of tokenizer |
|
877 | 877 | pass |
|
878 | 878 | except tokenize.TokenError as msg: |
|
879 | 879 | _m = ("An unexpected error occurred while tokenizing input\n" |
|
880 | 880 | "The following traceback may be corrupted or invalid\n" |
|
881 | 881 | "The error message is: %s\n" % msg) |
|
882 | 882 | error(_m) |
|
883 | 883 | |
|
884 | 884 | # Join composite names (e.g. "dict.fromkeys") |
|
885 | 885 | names = ['.'.join(n) for n in names] |
|
886 | 886 | # prune names list of duplicates, but keep the right order |
|
887 | 887 | unique_names = uniq_stable(names) |
|
888 | 888 | |
|
889 | 889 | # Start loop over vars |
|
890 | 890 | lvals = [] |
|
891 | 891 | if self.include_vars: |
|
892 | 892 | for name_full in unique_names: |
|
893 | 893 | name_base = name_full.split('.',1)[0] |
|
894 | 894 | if name_base in frame.f_code.co_varnames: |
|
895 | 895 | if locals.has_key(name_base): |
|
896 | 896 | try: |
|
897 | 897 | value = repr(eval(name_full,locals)) |
|
898 | 898 | except: |
|
899 | 899 | value = undefined |
|
900 | 900 | else: |
|
901 | 901 | value = undefined |
|
902 | 902 | name = tpl_local_var % name_full |
|
903 | 903 | else: |
|
904 | 904 | if frame.f_globals.has_key(name_base): |
|
905 | 905 | try: |
|
906 | 906 | value = repr(eval(name_full,frame.f_globals)) |
|
907 | 907 | except: |
|
908 | 908 | value = undefined |
|
909 | 909 | else: |
|
910 | 910 | value = undefined |
|
911 | 911 | name = tpl_global_var % name_full |
|
912 | 912 | lvals.append(tpl_name_val % (name,value)) |
|
913 | 913 | if lvals: |
|
914 | 914 | lvals = '%s%s' % (indent,em_normal.join(lvals)) |
|
915 | 915 | else: |
|
916 | 916 | lvals = '' |
|
917 | 917 | |
|
918 | 918 | level = '%s %s\n' % (link,call) |
|
919 | 919 | |
|
920 | 920 | if index is None: |
|
921 | 921 | frames.append(level) |
|
922 | 922 | else: |
|
923 | 923 | frames.append('%s%s' % (level,''.join( |
|
924 | 924 | _format_traceback_lines(lnum,index,lines,Colors,lvals, |
|
925 | 925 | col_scheme)))) |
|
926 | 926 | |
|
927 | 927 | # Get (safely) a string form of the exception info |
|
928 | 928 | try: |
|
929 | 929 | etype_str,evalue_str = map(str,(etype,evalue)) |
|
930 | 930 | except: |
|
931 | 931 | # User exception is improperly defined. |
|
932 | 932 | etype,evalue = str,sys.exc_info()[:2] |
|
933 | 933 | etype_str,evalue_str = map(str,(etype,evalue)) |
|
934 | 934 | # ... and format it |
|
935 | 935 | exception = ['%s%s%s: %s' % (Colors.excName, etype_str, |
|
936 | 936 | ColorsNormal, evalue_str)] |
|
937 | 937 | if (not py3compat.PY3) and type(evalue) is types.InstanceType: |
|
938 | 938 | try: |
|
939 | 939 | names = [w for w in dir(evalue) if isinstance(w, basestring)] |
|
940 | 940 | except: |
|
941 | 941 | # Every now and then, an object with funny inernals blows up |
|
942 | 942 | # when dir() is called on it. We do the best we can to report |
|
943 | 943 | # the problem and continue |
|
944 | 944 | _m = '%sException reporting error (object with broken dir())%s:' |
|
945 | 945 | exception.append(_m % (Colors.excName,ColorsNormal)) |
|
946 | 946 | etype_str,evalue_str = map(str,sys.exc_info()[:2]) |
|
947 | 947 | exception.append('%s%s%s: %s' % (Colors.excName,etype_str, |
|
948 | 948 | ColorsNormal, evalue_str)) |
|
949 | 949 | names = [] |
|
950 | 950 | for name in names: |
|
951 | 951 | value = text_repr(getattr(evalue, name)) |
|
952 | 952 | exception.append('\n%s%s = %s' % (indent, name, value)) |
|
953 | 953 | |
|
954 | 954 | # vds: >> |
|
955 | 955 | if records: |
|
956 | 956 | filepath, lnum = records[-1][1:3] |
|
957 | 957 | #print "file:", str(file), "linenb", str(lnum) # dbg |
|
958 | 958 | filepath = os.path.abspath(filepath) |
|
959 | 959 | ipinst = ipapi.get() |
|
960 | 960 | if ipinst is not None: |
|
961 | 961 | ipinst.hooks.synchronize_with_editor(filepath, lnum, 0) |
|
962 | 962 | # vds: << |
|
963 | 963 | |
|
964 | 964 | # return all our info assembled as a single string |
|
965 | 965 | # return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) ) |
|
966 | 966 | return [head] + frames + [''.join(exception[0])] |
|
967 | 967 | |
|
968 | 968 | def debugger(self,force=False): |
|
969 | 969 | """Call up the pdb debugger if desired, always clean up the tb |
|
970 | 970 | reference. |
|
971 | 971 | |
|
972 | 972 | Keywords: |
|
973 | 973 | |
|
974 | 974 | - force(False): by default, this routine checks the instance call_pdb |
|
975 | 975 | flag and does not actually invoke the debugger if the flag is false. |
|
976 | 976 | The 'force' option forces the debugger to activate even if the flag |
|
977 | 977 | is false. |
|
978 | 978 | |
|
979 | 979 | If the call_pdb flag is set, the pdb interactive debugger is |
|
980 | 980 | invoked. In all cases, the self.tb reference to the current traceback |
|
981 | 981 | is deleted to prevent lingering references which hamper memory |
|
982 | 982 | management. |
|
983 | 983 | |
|
984 | 984 | Note that each call to pdb() does an 'import readline', so if your app |
|
985 | 985 | requires a special setup for the readline completers, you'll have to |
|
986 | 986 | fix that by hand after invoking the exception handler.""" |
|
987 | 987 | |
|
988 | 988 | if force or self.call_pdb: |
|
989 | 989 | if self.pdb is None: |
|
990 | 990 | self.pdb = debugger.Pdb( |
|
991 | 991 | self.color_scheme_table.active_scheme_name) |
|
992 | 992 | # the system displayhook may have changed, restore the original |
|
993 | 993 | # for pdb |
|
994 | 994 | display_trap = DisplayTrap(hook=sys.__displayhook__) |
|
995 | 995 | with display_trap: |
|
996 | 996 | self.pdb.reset() |
|
997 | 997 | # Find the right frame so we don't pop up inside ipython itself |
|
998 | 998 | if hasattr(self,'tb') and self.tb is not None: |
|
999 | 999 | etb = self.tb |
|
1000 | 1000 | else: |
|
1001 | 1001 | etb = self.tb = sys.last_traceback |
|
1002 | 1002 | while self.tb is not None and self.tb.tb_next is not None: |
|
1003 | 1003 | self.tb = self.tb.tb_next |
|
1004 | 1004 | if etb and etb.tb_next: |
|
1005 | 1005 | etb = etb.tb_next |
|
1006 | 1006 | self.pdb.botframe = etb.tb_frame |
|
1007 | 1007 | self.pdb.interaction(self.tb.tb_frame, self.tb) |
|
1008 | 1008 | |
|
1009 | 1009 | if hasattr(self,'tb'): |
|
1010 | 1010 | del self.tb |
|
1011 | 1011 | |
|
1012 | 1012 | def handler(self, info=None): |
|
1013 | 1013 | (etype, evalue, etb) = info or sys.exc_info() |
|
1014 | 1014 | self.tb = etb |
|
1015 | 1015 | ostream = self.ostream |
|
1016 | 1016 | ostream.flush() |
|
1017 | 1017 | ostream.write(self.text(etype, evalue, etb)) |
|
1018 | 1018 | ostream.write('\n') |
|
1019 | 1019 | ostream.flush() |
|
1020 | 1020 | |
|
1021 | 1021 | # Changed so an instance can just be called as VerboseTB_inst() and print |
|
1022 | 1022 | # out the right info on its own. |
|
1023 | 1023 | def __call__(self, etype=None, evalue=None, etb=None): |
|
1024 | 1024 | """This hook can replace sys.excepthook (for Python 2.1 or higher).""" |
|
1025 | 1025 | if etb is None: |
|
1026 | 1026 | self.handler() |
|
1027 | 1027 | else: |
|
1028 | 1028 | self.handler((etype, evalue, etb)) |
|
1029 | 1029 | try: |
|
1030 | 1030 | self.debugger() |
|
1031 | 1031 | except KeyboardInterrupt: |
|
1032 | 1032 | print "\nKeyboardInterrupt" |
|
1033 | 1033 | |
|
1034 | 1034 | #---------------------------------------------------------------------------- |
|
1035 | 1035 | class FormattedTB(VerboseTB, ListTB): |
|
1036 | 1036 | """Subclass ListTB but allow calling with a traceback. |
|
1037 | 1037 | |
|
1038 | 1038 | It can thus be used as a sys.excepthook for Python > 2.1. |
|
1039 | 1039 | |
|
1040 | 1040 | Also adds 'Context' and 'Verbose' modes, not available in ListTB. |
|
1041 | 1041 | |
|
1042 | 1042 | Allows a tb_offset to be specified. This is useful for situations where |
|
1043 | 1043 | one needs to remove a number of topmost frames from the traceback (such as |
|
1044 | 1044 | occurs with python programs that themselves execute other python code, |
|
1045 | 1045 | like Python shells). """ |
|
1046 | 1046 | |
|
1047 | 1047 | def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False, |
|
1048 | 1048 | ostream=None, |
|
1049 | 1049 | tb_offset=0, long_header=False, include_vars=False, |
|
1050 | 1050 | check_cache=None): |
|
1051 | 1051 | |
|
1052 | 1052 | # NEVER change the order of this list. Put new modes at the end: |
|
1053 | 1053 | self.valid_modes = ['Plain','Context','Verbose'] |
|
1054 | 1054 | self.verbose_modes = self.valid_modes[1:3] |
|
1055 | 1055 | |
|
1056 | 1056 | VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, |
|
1057 | 1057 | ostream=ostream, tb_offset=tb_offset, |
|
1058 | 1058 | long_header=long_header, include_vars=include_vars, |
|
1059 | 1059 | check_cache=check_cache) |
|
1060 | 1060 | |
|
1061 | 1061 | # Different types of tracebacks are joined with different separators to |
|
1062 | 1062 | # form a single string. They are taken from this dict |
|
1063 | 1063 | self._join_chars = dict(Plain='', Context='\n', Verbose='\n') |
|
1064 | 1064 | # set_mode also sets the tb_join_char attribute |
|
1065 | 1065 | self.set_mode(mode) |
|
1066 | 1066 | |
|
1067 | 1067 | def _extract_tb(self,tb): |
|
1068 | 1068 | if tb: |
|
1069 | 1069 | return traceback.extract_tb(tb) |
|
1070 | 1070 | else: |
|
1071 | 1071 | return None |
|
1072 | 1072 | |
|
1073 | 1073 | def structured_traceback(self, etype, value, tb, tb_offset=None, context=5): |
|
1074 | 1074 | tb_offset = self.tb_offset if tb_offset is None else tb_offset |
|
1075 | 1075 | mode = self.mode |
|
1076 | 1076 | if mode in self.verbose_modes: |
|
1077 | 1077 | # Verbose modes need a full traceback |
|
1078 | 1078 | return VerboseTB.structured_traceback( |
|
1079 | 1079 | self, etype, value, tb, tb_offset, context |
|
1080 | 1080 | ) |
|
1081 | 1081 | else: |
|
1082 | 1082 | # We must check the source cache because otherwise we can print |
|
1083 | 1083 | # out-of-date source code. |
|
1084 | 1084 | self.check_cache() |
|
1085 | 1085 | # Now we can extract and format the exception |
|
1086 | 1086 | elist = self._extract_tb(tb) |
|
1087 | 1087 | return ListTB.structured_traceback( |
|
1088 | 1088 | self, etype, value, elist, tb_offset, context |
|
1089 | 1089 | ) |
|
1090 | 1090 | |
|
1091 | 1091 | def stb2text(self, stb): |
|
1092 | 1092 | """Convert a structured traceback (a list) to a string.""" |
|
1093 | 1093 | return self.tb_join_char.join(stb) |
|
1094 | 1094 | |
|
1095 | 1095 | |
|
1096 | 1096 | def set_mode(self,mode=None): |
|
1097 | 1097 | """Switch to the desired mode. |
|
1098 | 1098 | |
|
1099 | 1099 | If mode is not specified, cycles through the available modes.""" |
|
1100 | 1100 | |
|
1101 | 1101 | if not mode: |
|
1102 | 1102 | new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \ |
|
1103 | 1103 | len(self.valid_modes) |
|
1104 | 1104 | self.mode = self.valid_modes[new_idx] |
|
1105 | 1105 | elif mode not in self.valid_modes: |
|
1106 |
raise ValueError |
|
|
1107 | 'Valid modes: '+str(self.valid_modes) | |
|
1106 | raise ValueError('Unrecognized mode in FormattedTB: <'+mode+'>\n' | |
|
1107 | 'Valid modes: '+str(self.valid_modes)) | |
|
1108 | 1108 | else: |
|
1109 | 1109 | self.mode = mode |
|
1110 | 1110 | # include variable details only in 'Verbose' mode |
|
1111 | 1111 | self.include_vars = (self.mode == self.valid_modes[2]) |
|
1112 | 1112 | # Set the join character for generating text tracebacks |
|
1113 | 1113 | self.tb_join_char = self._join_chars[self.mode] |
|
1114 | 1114 | |
|
1115 | 1115 | # some convenient shorcuts |
|
1116 | 1116 | def plain(self): |
|
1117 | 1117 | self.set_mode(self.valid_modes[0]) |
|
1118 | 1118 | |
|
1119 | 1119 | def context(self): |
|
1120 | 1120 | self.set_mode(self.valid_modes[1]) |
|
1121 | 1121 | |
|
1122 | 1122 | def verbose(self): |
|
1123 | 1123 | self.set_mode(self.valid_modes[2]) |
|
1124 | 1124 | |
|
1125 | 1125 | #---------------------------------------------------------------------------- |
|
1126 | 1126 | class AutoFormattedTB(FormattedTB): |
|
1127 | 1127 | """A traceback printer which can be called on the fly. |
|
1128 | 1128 | |
|
1129 | 1129 | It will find out about exceptions by itself. |
|
1130 | 1130 | |
|
1131 | 1131 | A brief example: |
|
1132 | 1132 | |
|
1133 | 1133 | AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux') |
|
1134 | 1134 | try: |
|
1135 | 1135 | ... |
|
1136 | 1136 | except: |
|
1137 | 1137 | AutoTB() # or AutoTB(out=logfile) where logfile is an open file object |
|
1138 | 1138 | """ |
|
1139 | 1139 | |
|
1140 | 1140 | def __call__(self,etype=None,evalue=None,etb=None, |
|
1141 | 1141 | out=None,tb_offset=None): |
|
1142 | 1142 | """Print out a formatted exception traceback. |
|
1143 | 1143 | |
|
1144 | 1144 | Optional arguments: |
|
1145 | 1145 | - out: an open file-like object to direct output to. |
|
1146 | 1146 | |
|
1147 | 1147 | - tb_offset: the number of frames to skip over in the stack, on a |
|
1148 | 1148 | per-call basis (this overrides temporarily the instance's tb_offset |
|
1149 | 1149 | given at initialization time. """ |
|
1150 | 1150 | |
|
1151 | 1151 | |
|
1152 | 1152 | if out is None: |
|
1153 | 1153 | out = self.ostream |
|
1154 | 1154 | out.flush() |
|
1155 | 1155 | out.write(self.text(etype, evalue, etb, tb_offset)) |
|
1156 | 1156 | out.write('\n') |
|
1157 | 1157 | out.flush() |
|
1158 | 1158 | # FIXME: we should remove the auto pdb behavior from here and leave |
|
1159 | 1159 | # that to the clients. |
|
1160 | 1160 | try: |
|
1161 | 1161 | self.debugger() |
|
1162 | 1162 | except KeyboardInterrupt: |
|
1163 | 1163 | print "\nKeyboardInterrupt" |
|
1164 | 1164 | |
|
1165 | 1165 | def structured_traceback(self, etype=None, value=None, tb=None, |
|
1166 | 1166 | tb_offset=None, context=5): |
|
1167 | 1167 | if etype is None: |
|
1168 | 1168 | etype,value,tb = sys.exc_info() |
|
1169 | 1169 | self.tb = tb |
|
1170 | 1170 | return FormattedTB.structured_traceback( |
|
1171 | 1171 | self, etype, value, tb, tb_offset, context) |
|
1172 | 1172 | |
|
1173 | 1173 | #--------------------------------------------------------------------------- |
|
1174 | 1174 | |
|
1175 | 1175 | # A simple class to preserve Nathan's original functionality. |
|
1176 | 1176 | class ColorTB(FormattedTB): |
|
1177 | 1177 | """Shorthand to initialize a FormattedTB in Linux colors mode.""" |
|
1178 | 1178 | def __init__(self,color_scheme='Linux',call_pdb=0): |
|
1179 | 1179 | FormattedTB.__init__(self,color_scheme=color_scheme, |
|
1180 | 1180 | call_pdb=call_pdb) |
|
1181 | 1181 | |
|
1182 | 1182 | |
|
1183 | 1183 | class SyntaxTB(ListTB): |
|
1184 | 1184 | """Extension which holds some state: the last exception value""" |
|
1185 | 1185 | |
|
1186 | 1186 | def __init__(self,color_scheme = 'NoColor'): |
|
1187 | 1187 | ListTB.__init__(self,color_scheme) |
|
1188 | 1188 | self.last_syntax_error = None |
|
1189 | 1189 | |
|
1190 | 1190 | def __call__(self, etype, value, elist): |
|
1191 | 1191 | self.last_syntax_error = value |
|
1192 | 1192 | ListTB.__call__(self,etype,value,elist) |
|
1193 | 1193 | |
|
1194 | 1194 | def clear_err_state(self): |
|
1195 | 1195 | """Return the current error state and clear it""" |
|
1196 | 1196 | e = self.last_syntax_error |
|
1197 | 1197 | self.last_syntax_error = None |
|
1198 | 1198 | return e |
|
1199 | 1199 | |
|
1200 | 1200 | def stb2text(self, stb): |
|
1201 | 1201 | """Convert a structured traceback (a list) to a string.""" |
|
1202 | 1202 | return ''.join(stb) |
|
1203 | 1203 | |
|
1204 | 1204 | |
|
1205 | 1205 | #---------------------------------------------------------------------------- |
|
1206 | 1206 | # module testing (minimal) |
|
1207 | 1207 | if __name__ == "__main__": |
|
1208 | 1208 | def spam(c, (d, e)): |
|
1209 | 1209 | x = c + d |
|
1210 | 1210 | y = c * d |
|
1211 | 1211 | foo(x, y) |
|
1212 | 1212 | |
|
1213 | 1213 | def foo(a, b, bar=1): |
|
1214 | 1214 | eggs(a, b + bar) |
|
1215 | 1215 | |
|
1216 | 1216 | def eggs(f, g, z=globals()): |
|
1217 | 1217 | h = f + g |
|
1218 | 1218 | i = f - g |
|
1219 | 1219 | return h / i |
|
1220 | 1220 | |
|
1221 | 1221 | print '' |
|
1222 | 1222 | print '*** Before ***' |
|
1223 | 1223 | try: |
|
1224 | 1224 | print spam(1, (2, 3)) |
|
1225 | 1225 | except: |
|
1226 | 1226 | traceback.print_exc() |
|
1227 | 1227 | print '' |
|
1228 | 1228 | |
|
1229 | 1229 | handler = ColorTB() |
|
1230 | 1230 | print '*** ColorTB ***' |
|
1231 | 1231 | try: |
|
1232 | 1232 | print spam(1, (2, 3)) |
|
1233 | 1233 | except: |
|
1234 | 1234 | handler(*sys.exc_info()) |
|
1235 | 1235 | print '' |
|
1236 | 1236 | |
|
1237 | 1237 | handler = VerboseTB() |
|
1238 | 1238 | print '*** VerboseTB ***' |
|
1239 | 1239 | try: |
|
1240 | 1240 | print spam(1, (2, 3)) |
|
1241 | 1241 | except: |
|
1242 | 1242 | handler(*sys.exc_info()) |
|
1243 | 1243 | print '' |
|
1244 | 1244 |
@@ -1,281 +1,281 b'' | |||
|
1 | 1 | """ |
|
2 | 2 | Decorators for labeling and modifying behavior of test objects. |
|
3 | 3 | |
|
4 | 4 | Decorators that merely return a modified version of the original |
|
5 | 5 | function object are straightforward. Decorators that return a new |
|
6 | 6 | function object need to use |
|
7 | 7 | :: |
|
8 | 8 | |
|
9 | 9 | nose.tools.make_decorator(original_function)(decorator) |
|
10 | 10 | |
|
11 | 11 | in returning the decorator, in order to preserve meta-data such as |
|
12 | 12 | function name, setup and teardown functions and so on - see |
|
13 | 13 | ``nose.tools`` for more information. |
|
14 | 14 | |
|
15 | 15 | """ |
|
16 | 16 | import warnings |
|
17 | 17 | |
|
18 | 18 | # IPython changes: make this work if numpy not available |
|
19 | 19 | # Original code: |
|
20 | 20 | #from numpy.testing.utils import \ |
|
21 | 21 | # WarningManager, WarningMessage |
|
22 | 22 | # Our version: |
|
23 | 23 | from _numpy_testing_utils import WarningManager |
|
24 | 24 | try: |
|
25 | 25 | from _numpy_testing_noseclasses import KnownFailureTest |
|
26 | 26 | except: |
|
27 | 27 | pass |
|
28 | 28 | |
|
29 | 29 | # End IPython changes |
|
30 | 30 | |
|
31 | 31 | def slow(t): |
|
32 | 32 | """ |
|
33 | 33 | Label a test as 'slow'. |
|
34 | 34 | |
|
35 | 35 | The exact definition of a slow test is obviously both subjective and |
|
36 | 36 | hardware-dependent, but in general any individual test that requires more |
|
37 | 37 | than a second or two should be labeled as slow (the whole suite consists of |
|
38 | 38 | thousands of tests, so even a second is significant). |
|
39 | 39 | |
|
40 | 40 | Parameters |
|
41 | 41 | ---------- |
|
42 | 42 | t : callable |
|
43 | 43 | The test to label as slow. |
|
44 | 44 | |
|
45 | 45 | Returns |
|
46 | 46 | ------- |
|
47 | 47 | t : callable |
|
48 | 48 | The decorated test `t`. |
|
49 | 49 | |
|
50 | 50 | Examples |
|
51 | 51 | -------- |
|
52 | 52 | The `numpy.testing` module includes ``import decorators as dec``. |
|
53 | 53 | A test can be decorated as slow like this:: |
|
54 | 54 | |
|
55 | 55 | from numpy.testing import * |
|
56 | 56 | |
|
57 | 57 | @dec.slow |
|
58 | 58 | def test_big(self): |
|
59 | 59 | print 'Big, slow test' |
|
60 | 60 | |
|
61 | 61 | """ |
|
62 | 62 | |
|
63 | 63 | t.slow = True |
|
64 | 64 | return t |
|
65 | 65 | |
|
66 | 66 | def setastest(tf=True): |
|
67 | 67 | """ |
|
68 | 68 | Signals to nose that this function is or is not a test. |
|
69 | 69 | |
|
70 | 70 | Parameters |
|
71 | 71 | ---------- |
|
72 | 72 | tf : bool |
|
73 | 73 | If True, specifies that the decorated callable is a test. |
|
74 | 74 | If False, specifies that the decorated callable is not a test. |
|
75 | 75 | Default is True. |
|
76 | 76 | |
|
77 | 77 | Notes |
|
78 | 78 | ----- |
|
79 | 79 | This decorator can't use the nose namespace, because it can be |
|
80 | 80 | called from a non-test module. See also ``istest`` and ``nottest`` in |
|
81 | 81 | ``nose.tools``. |
|
82 | 82 | |
|
83 | 83 | Examples |
|
84 | 84 | -------- |
|
85 | 85 | `setastest` can be used in the following way:: |
|
86 | 86 | |
|
87 | 87 | from numpy.testing.decorators import setastest |
|
88 | 88 | |
|
89 | 89 | @setastest(False) |
|
90 | 90 | def func_with_test_in_name(arg1, arg2): |
|
91 | 91 | pass |
|
92 | 92 | |
|
93 | 93 | """ |
|
94 | 94 | def set_test(t): |
|
95 | 95 | t.__test__ = tf |
|
96 | 96 | return t |
|
97 | 97 | return set_test |
|
98 | 98 | |
|
99 | 99 | def skipif(skip_condition, msg=None): |
|
100 | 100 | """ |
|
101 | 101 | Make function raise SkipTest exception if a given condition is true. |
|
102 | 102 | |
|
103 | 103 | If the condition is a callable, it is used at runtime to dynamically |
|
104 | 104 | make the decision. This is useful for tests that may require costly |
|
105 | 105 | imports, to delay the cost until the test suite is actually executed. |
|
106 | 106 | |
|
107 | 107 | Parameters |
|
108 | 108 | ---------- |
|
109 | 109 | skip_condition : bool or callable |
|
110 | 110 | Flag to determine whether to skip the decorated test. |
|
111 | 111 | msg : str, optional |
|
112 | 112 | Message to give on raising a SkipTest exception. Default is None. |
|
113 | 113 | |
|
114 | 114 | Returns |
|
115 | 115 | ------- |
|
116 | 116 | decorator : function |
|
117 | 117 | Decorator which, when applied to a function, causes SkipTest |
|
118 | 118 | to be raised when `skip_condition` is True, and the function |
|
119 | 119 | to be called normally otherwise. |
|
120 | 120 | |
|
121 | 121 | Notes |
|
122 | 122 | ----- |
|
123 | 123 | The decorator itself is decorated with the ``nose.tools.make_decorator`` |
|
124 | 124 | function in order to transmit function name, and various other metadata. |
|
125 | 125 | |
|
126 | 126 | """ |
|
127 | 127 | |
|
128 | 128 | def skip_decorator(f): |
|
129 | 129 | # Local import to avoid a hard nose dependency and only incur the |
|
130 | 130 | # import time overhead at actual test-time. |
|
131 | 131 | import nose |
|
132 | 132 | |
|
133 | 133 | # Allow for both boolean or callable skip conditions. |
|
134 | 134 | if callable(skip_condition): |
|
135 | 135 | skip_val = lambda : skip_condition() |
|
136 | 136 | else: |
|
137 | 137 | skip_val = lambda : skip_condition |
|
138 | 138 | |
|
139 | 139 | def get_msg(func,msg=None): |
|
140 | 140 | """Skip message with information about function being skipped.""" |
|
141 | 141 | if msg is None: |
|
142 | 142 | out = 'Test skipped due to test condition' |
|
143 | 143 | else: |
|
144 | 144 | out = '\n'+msg |
|
145 | 145 | |
|
146 | 146 | return "Skipping test: %s%s" % (func.__name__,out) |
|
147 | 147 | |
|
148 | 148 | # We need to define *two* skippers because Python doesn't allow both |
|
149 | 149 | # return with value and yield inside the same function. |
|
150 | 150 | def skipper_func(*args, **kwargs): |
|
151 | 151 | """Skipper for normal test functions.""" |
|
152 | 152 | if skip_val(): |
|
153 | 153 | raise nose.SkipTest(get_msg(f,msg)) |
|
154 | 154 | else: |
|
155 | 155 | return f(*args, **kwargs) |
|
156 | 156 | |
|
157 | 157 | def skipper_gen(*args, **kwargs): |
|
158 | 158 | """Skipper for test generators.""" |
|
159 | 159 | if skip_val(): |
|
160 | 160 | raise nose.SkipTest(get_msg(f,msg)) |
|
161 | 161 | else: |
|
162 | 162 | for x in f(*args, **kwargs): |
|
163 | 163 | yield x |
|
164 | 164 | |
|
165 | 165 | # Choose the right skipper to use when building the actual decorator. |
|
166 | 166 | if nose.util.isgenerator(f): |
|
167 | 167 | skipper = skipper_gen |
|
168 | 168 | else: |
|
169 | 169 | skipper = skipper_func |
|
170 | 170 | |
|
171 | 171 | return nose.tools.make_decorator(f)(skipper) |
|
172 | 172 | |
|
173 | 173 | return skip_decorator |
|
174 | 174 | |
|
175 | 175 | def knownfailureif(fail_condition, msg=None): |
|
176 | 176 | """ |
|
177 | 177 | Make function raise KnownFailureTest exception if given condition is true. |
|
178 | 178 | |
|
179 | 179 | If the condition is a callable, it is used at runtime to dynamically |
|
180 | 180 | make the decision. This is useful for tests that may require costly |
|
181 | 181 | imports, to delay the cost until the test suite is actually executed. |
|
182 | 182 | |
|
183 | 183 | Parameters |
|
184 | 184 | ---------- |
|
185 | 185 | fail_condition : bool or callable |
|
186 | 186 | Flag to determine whether to mark the decorated test as a known |
|
187 | 187 | failure (if True) or not (if False). |
|
188 | 188 | msg : str, optional |
|
189 | 189 | Message to give on raising a KnownFailureTest exception. |
|
190 | 190 | Default is None. |
|
191 | 191 | |
|
192 | 192 | Returns |
|
193 | 193 | ------- |
|
194 | 194 | decorator : function |
|
195 | 195 | Decorator, which, when applied to a function, causes SkipTest |
|
196 | 196 | to be raised when `skip_condition` is True, and the function |
|
197 | 197 | to be called normally otherwise. |
|
198 | 198 | |
|
199 | 199 | Notes |
|
200 | 200 | ----- |
|
201 | 201 | The decorator itself is decorated with the ``nose.tools.make_decorator`` |
|
202 | 202 | function in order to transmit function name, and various other metadata. |
|
203 | 203 | |
|
204 | 204 | """ |
|
205 | 205 | if msg is None: |
|
206 | 206 | msg = 'Test skipped due to known failure' |
|
207 | 207 | |
|
208 | 208 | # Allow for both boolean or callable known failure conditions. |
|
209 | 209 | if callable(fail_condition): |
|
210 | 210 | fail_val = lambda : fail_condition() |
|
211 | 211 | else: |
|
212 | 212 | fail_val = lambda : fail_condition |
|
213 | 213 | |
|
214 | 214 | def knownfail_decorator(f): |
|
215 | 215 | # Local import to avoid a hard nose dependency and only incur the |
|
216 | 216 | # import time overhead at actual test-time. |
|
217 | 217 | import nose |
|
218 | 218 | def knownfailer(*args, **kwargs): |
|
219 | 219 | if fail_val(): |
|
220 |
raise KnownFailureTest |
|
|
220 | raise KnownFailureTest(msg) | |
|
221 | 221 | else: |
|
222 | 222 | return f(*args, **kwargs) |
|
223 | 223 | return nose.tools.make_decorator(f)(knownfailer) |
|
224 | 224 | |
|
225 | 225 | return knownfail_decorator |
|
226 | 226 | |
|
227 | 227 | def deprecated(conditional=True): |
|
228 | 228 | """ |
|
229 | 229 | Filter deprecation warnings while running the test suite. |
|
230 | 230 | |
|
231 | 231 | This decorator can be used to filter DeprecationWarning's, to avoid |
|
232 | 232 | printing them during the test suite run, while checking that the test |
|
233 | 233 | actually raises a DeprecationWarning. |
|
234 | 234 | |
|
235 | 235 | Parameters |
|
236 | 236 | ---------- |
|
237 | 237 | conditional : bool or callable, optional |
|
238 | 238 | Flag to determine whether to mark test as deprecated or not. If the |
|
239 | 239 | condition is a callable, it is used at runtime to dynamically make the |
|
240 | 240 | decision. Default is True. |
|
241 | 241 | |
|
242 | 242 | Returns |
|
243 | 243 | ------- |
|
244 | 244 | decorator : function |
|
245 | 245 | The `deprecated` decorator itself. |
|
246 | 246 | |
|
247 | 247 | Notes |
|
248 | 248 | ----- |
|
249 | 249 | .. versionadded:: 1.4.0 |
|
250 | 250 | |
|
251 | 251 | """ |
|
252 | 252 | def deprecate_decorator(f): |
|
253 | 253 | # Local import to avoid a hard nose dependency and only incur the |
|
254 | 254 | # import time overhead at actual test-time. |
|
255 | 255 | import nose |
|
256 | 256 | |
|
257 | 257 | def _deprecated_imp(*args, **kwargs): |
|
258 | 258 | # Poor man's replacement for the with statement |
|
259 | 259 | ctx = WarningManager(record=True) |
|
260 | 260 | l = ctx.__enter__() |
|
261 | 261 | warnings.simplefilter('always') |
|
262 | 262 | try: |
|
263 | 263 | f(*args, **kwargs) |
|
264 | 264 | if not len(l) > 0: |
|
265 | 265 | raise AssertionError("No warning raised when calling %s" |
|
266 | 266 | % f.__name__) |
|
267 | 267 | if not l[0].category is DeprecationWarning: |
|
268 | 268 | raise AssertionError("First warning for %s is not a " \ |
|
269 | 269 | "DeprecationWarning( is %s)" % (f.__name__, l[0])) |
|
270 | 270 | finally: |
|
271 | 271 | ctx.__exit__() |
|
272 | 272 | |
|
273 | 273 | if callable(conditional): |
|
274 | 274 | cond = conditional() |
|
275 | 275 | else: |
|
276 | 276 | cond = conditional |
|
277 | 277 | if cond: |
|
278 | 278 | return nose.tools.make_decorator(f)(_deprecated_imp) |
|
279 | 279 | else: |
|
280 | 280 | return f |
|
281 | 281 | return deprecate_decorator |
@@ -1,1900 +1,1900 b'' | |||
|
1 | 1 | """Pexpect is a Python module for spawning child applications and controlling |
|
2 | 2 | them automatically. Pexpect can be used for automating interactive applications |
|
3 | 3 | such as ssh, ftp, passwd, telnet, etc. It can be used to a automate setup |
|
4 | 4 | scripts for duplicating software package installations on different servers. It |
|
5 | 5 | can be used for automated software testing. Pexpect is in the spirit of Don |
|
6 | 6 | Libes' Expect, but Pexpect is pure Python. Other Expect-like modules for Python |
|
7 | 7 | require TCL and Expect or require C extensions to be compiled. Pexpect does not |
|
8 | 8 | use C, Expect, or TCL extensions. It should work on any platform that supports |
|
9 | 9 | the standard Python pty module. The Pexpect interface focuses on ease of use so |
|
10 | 10 | that simple tasks are easy. |
|
11 | 11 | |
|
12 | 12 | There are two main interfaces to the Pexpect system; these are the function, |
|
13 | 13 | run() and the class, spawn. The spawn class is more powerful. The run() |
|
14 | 14 | function is simpler than spawn, and is good for quickly calling program. When |
|
15 | 15 | you call the run() function it executes a given program and then returns the |
|
16 | 16 | output. This is a handy replacement for os.system(). |
|
17 | 17 | |
|
18 | 18 | For example:: |
|
19 | 19 | |
|
20 | 20 | pexpect.run('ls -la') |
|
21 | 21 | |
|
22 | 22 | The spawn class is the more powerful interface to the Pexpect system. You can |
|
23 | 23 | use this to spawn a child program then interact with it by sending input and |
|
24 | 24 | expecting responses (waiting for patterns in the child's output). |
|
25 | 25 | |
|
26 | 26 | For example:: |
|
27 | 27 | |
|
28 | 28 | child = pexpect.spawn('scp foo myname@host.example.com:.') |
|
29 | 29 | child.expect ('Password:') |
|
30 | 30 | child.sendline (mypassword) |
|
31 | 31 | |
|
32 | 32 | This works even for commands that ask for passwords or other input outside of |
|
33 | 33 | the normal stdio streams. For example, ssh reads input directly from the TTY |
|
34 | 34 | device which bypasses stdin. |
|
35 | 35 | |
|
36 | 36 | Credits: Noah Spurrier, Richard Holden, Marco Molteni, Kimberley Burchett, |
|
37 | 37 | Robert Stone, Hartmut Goebel, Chad Schroeder, Erick Tryzelaar, Dave Kirby, Ids |
|
38 | 38 | vander Molen, George Todd, Noel Taylor, Nicolas D. Cesar, Alexander Gattin, |
|
39 | 39 | Jacques-Etienne Baudoux, Geoffrey Marshall, Francisco Lourenco, Glen Mabey, |
|
40 | 40 | Karthik Gurusamy, Fernando Perez, Corey Minyard, Jon Cohen, Guillaume |
|
41 | 41 | Chazarain, Andrew Ryan, Nick Craig-Wood, Andrew Stone, Jorgen Grahn, John |
|
42 | 42 | Spiegel, Jan Grant, Shane Kerr and Thomas Kluyver. Let me know if I forgot anyone. |
|
43 | 43 | |
|
44 | 44 | Pexpect is free, open source, and all that good stuff. |
|
45 | 45 | |
|
46 | 46 | Permission is hereby granted, free of charge, to any person obtaining a copy of |
|
47 | 47 | this software and associated documentation files (the "Software"), to deal in |
|
48 | 48 | the Software without restriction, including without limitation the rights to |
|
49 | 49 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies |
|
50 | 50 | of the Software, and to permit persons to whom the Software is furnished to do |
|
51 | 51 | so, subject to the following conditions: |
|
52 | 52 | |
|
53 | 53 | The above copyright notice and this permission notice shall be included in all |
|
54 | 54 | copies or substantial portions of the Software. |
|
55 | 55 | |
|
56 | 56 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
|
57 | 57 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
|
58 | 58 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
|
59 | 59 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
|
60 | 60 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
|
61 | 61 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
|
62 | 62 | SOFTWARE. |
|
63 | 63 | |
|
64 | 64 | Pexpect Copyright (c) 2008-2011 Noah Spurrier |
|
65 | 65 | http://pexpect.sourceforge.net/ |
|
66 | 66 | """ |
|
67 | 67 | |
|
68 | 68 | try: |
|
69 | 69 | import os, sys, time |
|
70 | 70 | import select |
|
71 | 71 | import re |
|
72 | 72 | import struct |
|
73 | 73 | import resource |
|
74 | 74 | import types |
|
75 | 75 | import pty |
|
76 | 76 | import tty |
|
77 | 77 | import termios |
|
78 | 78 | import fcntl |
|
79 | 79 | import errno |
|
80 | 80 | import traceback |
|
81 | 81 | import signal |
|
82 | 82 | except ImportError as e: |
|
83 | 83 | raise ImportError (str(e) + """ |
|
84 | 84 | |
|
85 | 85 | A critical module was not found. Probably this operating system does not |
|
86 | 86 | support it. Pexpect is intended for UNIX-like operating systems.""") |
|
87 | 87 | |
|
88 | 88 | __version__ = '2.6.dev' |
|
89 | 89 | version = __version__ |
|
90 | 90 | version_info = (2,6,'dev') |
|
91 | 91 | __all__ = ['ExceptionPexpect', 'EOF', 'TIMEOUT', 'spawn', 'spawnb', 'run', 'which', |
|
92 | 92 | 'split_command_line', '__version__'] |
|
93 | 93 | |
|
94 | 94 | # Exception classes used by this module. |
|
95 | 95 | class ExceptionPexpect(Exception): |
|
96 | 96 | |
|
97 | 97 | """Base class for all exceptions raised by this module. |
|
98 | 98 | """ |
|
99 | 99 | |
|
100 | 100 | def __init__(self, value): |
|
101 | 101 | |
|
102 | 102 | self.value = value |
|
103 | 103 | |
|
104 | 104 | def __str__(self): |
|
105 | 105 | |
|
106 | 106 | return str(self.value) |
|
107 | 107 | |
|
108 | 108 | def get_trace(self): |
|
109 | 109 | |
|
110 | 110 | """This returns an abbreviated stack trace with lines that only concern |
|
111 | 111 | the caller. In other words, the stack trace inside the Pexpect module |
|
112 | 112 | is not included. """ |
|
113 | 113 | |
|
114 | 114 | tblist = traceback.extract_tb(sys.exc_info()[2]) |
|
115 | 115 | #tblist = filter(self.__filter_not_pexpect, tblist) |
|
116 | 116 | tblist = [item for item in tblist if self.__filter_not_pexpect(item)] |
|
117 | 117 | tblist = traceback.format_list(tblist) |
|
118 | 118 | return ''.join(tblist) |
|
119 | 119 | |
|
120 | 120 | def __filter_not_pexpect(self, trace_list_item): |
|
121 | 121 | |
|
122 | 122 | """This returns True if list item 0 the string 'pexpect.py' in it. """ |
|
123 | 123 | |
|
124 | 124 | if trace_list_item[0].find('pexpect.py') == -1: |
|
125 | 125 | return True |
|
126 | 126 | else: |
|
127 | 127 | return False |
|
128 | 128 | |
|
129 | 129 | class EOF(ExceptionPexpect): |
|
130 | 130 | |
|
131 | 131 | """Raised when EOF is read from a child. This usually means the child has exited.""" |
|
132 | 132 | |
|
133 | 133 | class TIMEOUT(ExceptionPexpect): |
|
134 | 134 | |
|
135 | 135 | """Raised when a read time exceeds the timeout. """ |
|
136 | 136 | |
|
137 | 137 | ##class TIMEOUT_PATTERN(TIMEOUT): |
|
138 | 138 | ## """Raised when the pattern match time exceeds the timeout. |
|
139 | 139 | ## This is different than a read TIMEOUT because the child process may |
|
140 | 140 | ## give output, thus never give a TIMEOUT, but the output |
|
141 | 141 | ## may never match a pattern. |
|
142 | 142 | ## """ |
|
143 | 143 | ##class MAXBUFFER(ExceptionPexpect): |
|
144 | 144 | ## """Raised when a scan buffer fills before matching an expected pattern.""" |
|
145 | 145 | |
|
146 | 146 | PY3 = (sys.version_info[0] >= 3) |
|
147 | 147 | |
|
148 | 148 | def _cast_bytes(s, enc): |
|
149 | 149 | if isinstance(s, unicode): |
|
150 | 150 | return s.encode(enc) |
|
151 | 151 | return s |
|
152 | 152 | |
|
153 | 153 | def _cast_unicode(s, enc): |
|
154 | 154 | if isinstance(s, bytes): |
|
155 | 155 | return s.decode(enc) |
|
156 | 156 | return s |
|
157 | 157 | |
|
158 | 158 | re_type = type(re.compile('')) |
|
159 | 159 | |
|
160 | 160 | def run (command, timeout=-1, withexitstatus=False, events=None, extra_args=None, |
|
161 | 161 | logfile=None, cwd=None, env=None, encoding='utf-8'): |
|
162 | 162 | |
|
163 | 163 | """ |
|
164 | 164 | This function runs the given command; waits for it to finish; then |
|
165 | 165 | returns all output as a string. STDERR is included in output. If the full |
|
166 | 166 | path to the command is not given then the path is searched. |
|
167 | 167 | |
|
168 | 168 | Note that lines are terminated by CR/LF (\\r\\n) combination even on |
|
169 | 169 | UNIX-like systems because this is the standard for pseudo ttys. If you set |
|
170 | 170 | 'withexitstatus' to true, then run will return a tuple of (command_output, |
|
171 | 171 | exitstatus). If 'withexitstatus' is false then this returns just |
|
172 | 172 | command_output. |
|
173 | 173 | |
|
174 | 174 | The run() function can often be used instead of creating a spawn instance. |
|
175 | 175 | For example, the following code uses spawn:: |
|
176 | 176 | |
|
177 | 177 | from pexpect import * |
|
178 | 178 | child = spawn('scp foo myname@host.example.com:.') |
|
179 | 179 | child.expect ('(?i)password') |
|
180 | 180 | child.sendline (mypassword) |
|
181 | 181 | |
|
182 | 182 | The previous code can be replace with the following:: |
|
183 | 183 | |
|
184 | 184 | from pexpect import * |
|
185 | 185 | run ('scp foo myname@host.example.com:.', events={'(?i)password': mypassword}) |
|
186 | 186 | |
|
187 | 187 | Examples |
|
188 | 188 | ======== |
|
189 | 189 | |
|
190 | 190 | Start the apache daemon on the local machine:: |
|
191 | 191 | |
|
192 | 192 | from pexpect import * |
|
193 | 193 | run ("/usr/local/apache/bin/apachectl start") |
|
194 | 194 | |
|
195 | 195 | Check in a file using SVN:: |
|
196 | 196 | |
|
197 | 197 | from pexpect import * |
|
198 | 198 | run ("svn ci -m 'automatic commit' my_file.py") |
|
199 | 199 | |
|
200 | 200 | Run a command and capture exit status:: |
|
201 | 201 | |
|
202 | 202 | from pexpect import * |
|
203 | 203 | (command_output, exitstatus) = run ('ls -l /bin', withexitstatus=1) |
|
204 | 204 | |
|
205 | 205 | Tricky Examples |
|
206 | 206 | =============== |
|
207 | 207 | |
|
208 | 208 | The following will run SSH and execute 'ls -l' on the remote machine. The |
|
209 | 209 | password 'secret' will be sent if the '(?i)password' pattern is ever seen:: |
|
210 | 210 | |
|
211 | 211 | run ("ssh username@machine.example.com 'ls -l'", events={'(?i)password':'secret\\n'}) |
|
212 | 212 | |
|
213 | 213 | This will start mencoder to rip a video from DVD. This will also display |
|
214 | 214 | progress ticks every 5 seconds as it runs. For example:: |
|
215 | 215 | |
|
216 | 216 | from pexpect import * |
|
217 | 217 | def print_ticks(d): |
|
218 | 218 | print d['event_count'], |
|
219 | 219 | run ("mencoder dvd://1 -o video.avi -oac copy -ovc copy", events={TIMEOUT:print_ticks}, timeout=5) |
|
220 | 220 | |
|
221 | 221 | The 'events' argument should be a dictionary of patterns and responses. |
|
222 | 222 | Whenever one of the patterns is seen in the command out run() will send the |
|
223 | 223 | associated response string. Note that you should put newlines in your |
|
224 | 224 | string if Enter is necessary. The responses may also contain callback |
|
225 | 225 | functions. Any callback is function that takes a dictionary as an argument. |
|
226 | 226 | The dictionary contains all the locals from the run() function, so you can |
|
227 | 227 | access the child spawn object or any other variable defined in run() |
|
228 | 228 | (event_count, child, and extra_args are the most useful). A callback may |
|
229 | 229 | return True to stop the current run process otherwise run() continues until |
|
230 | 230 | the next event. A callback may also return a string which will be sent to |
|
231 | 231 | the child. 'extra_args' is not used by directly run(). It provides a way to |
|
232 | 232 | pass data to a callback function through run() through the locals |
|
233 | 233 | dictionary passed to a callback.""" |
|
234 | 234 | |
|
235 | 235 | if timeout == -1: |
|
236 | 236 | child = spawn(command, maxread=2000, logfile=logfile, cwd=cwd, env=env, |
|
237 | 237 | encoding=encoding) |
|
238 | 238 | else: |
|
239 | 239 | child = spawn(command, timeout=timeout, maxread=2000, logfile=logfile, |
|
240 | 240 | cwd=cwd, env=env, encoding=encoding) |
|
241 | 241 | if events is not None: |
|
242 | 242 | patterns = events.keys() |
|
243 | 243 | responses = events.values() |
|
244 | 244 | else: |
|
245 | 245 | patterns=None # We assume that EOF or TIMEOUT will save us. |
|
246 | 246 | responses=None |
|
247 | 247 | child_result_list = [] |
|
248 | 248 | event_count = 0 |
|
249 | 249 | while 1: |
|
250 | 250 | try: |
|
251 | 251 | index = child.expect (patterns) |
|
252 | 252 | if isinstance(child.after, basestring): |
|
253 | 253 | child_result_list.append(child.before + child.after) |
|
254 | 254 | else: # child.after may have been a TIMEOUT or EOF, so don't cat those. |
|
255 | 255 | child_result_list.append(child.before) |
|
256 | 256 | if isinstance(responses[index], basestring): |
|
257 | 257 | child.send(responses[index]) |
|
258 | 258 | elif type(responses[index]) is types.FunctionType: |
|
259 | 259 | callback_result = responses[index](locals()) |
|
260 | 260 | sys.stdout.flush() |
|
261 | 261 | if isinstance(callback_result, basestring): |
|
262 | 262 | child.send(callback_result) |
|
263 | 263 | elif callback_result: |
|
264 | 264 | break |
|
265 | 265 | else: |
|
266 | 266 | raise TypeError ('The callback must be a string or function type.') |
|
267 | 267 | event_count = event_count + 1 |
|
268 | 268 | except TIMEOUT as e: |
|
269 | 269 | child_result_list.append(child.before) |
|
270 | 270 | break |
|
271 | 271 | except EOF as e: |
|
272 | 272 | child_result_list.append(child.before) |
|
273 | 273 | break |
|
274 | 274 | child_result = child._empty_buffer.join(child_result_list) |
|
275 | 275 | if withexitstatus: |
|
276 | 276 | child.close() |
|
277 | 277 | return (child_result, child.exitstatus) |
|
278 | 278 | else: |
|
279 | 279 | return child_result |
|
280 | 280 | |
|
281 | 281 | class spawnb(object): |
|
282 | 282 | """Use this class to start and control child applications with a pure-bytes |
|
283 | 283 | interface.""" |
|
284 | 284 | |
|
285 | 285 | _buffer_type = bytes |
|
286 | 286 | def _cast_buffer_type(self, s): |
|
287 | 287 | return _cast_bytes(s, self.encoding) |
|
288 | 288 | _empty_buffer = b'' |
|
289 | 289 | _pty_newline = b'\r\n' |
|
290 | 290 | |
|
291 | 291 | # Some code needs this to exist, but it's mainly for the spawn subclass. |
|
292 | 292 | encoding = 'utf-8' |
|
293 | 293 | |
|
294 | 294 | def __init__(self, command, args=[], timeout=30, maxread=2000, searchwindowsize=None, |
|
295 | 295 | logfile=None, cwd=None, env=None): |
|
296 | 296 | |
|
297 | 297 | """This is the constructor. The command parameter may be a string that |
|
298 | 298 | includes a command and any arguments to the command. For example:: |
|
299 | 299 | |
|
300 | 300 | child = pexpect.spawn ('/usr/bin/ftp') |
|
301 | 301 | child = pexpect.spawn ('/usr/bin/ssh user@example.com') |
|
302 | 302 | child = pexpect.spawn ('ls -latr /tmp') |
|
303 | 303 | |
|
304 | 304 | You may also construct it with a list of arguments like so:: |
|
305 | 305 | |
|
306 | 306 | child = pexpect.spawn ('/usr/bin/ftp', []) |
|
307 | 307 | child = pexpect.spawn ('/usr/bin/ssh', ['user@example.com']) |
|
308 | 308 | child = pexpect.spawn ('ls', ['-latr', '/tmp']) |
|
309 | 309 | |
|
310 | 310 | After this the child application will be created and will be ready to |
|
311 | 311 | talk to. For normal use, see expect() and send() and sendline(). |
|
312 | 312 | |
|
313 | 313 | Remember that Pexpect does NOT interpret shell meta characters such as |
|
314 | 314 | redirect, pipe, or wild cards (>, |, or *). This is a common mistake. |
|
315 | 315 | If you want to run a command and pipe it through another command then |
|
316 | 316 | you must also start a shell. For example:: |
|
317 | 317 | |
|
318 | 318 | child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > log_list.txt"') |
|
319 | 319 | child.expect(pexpect.EOF) |
|
320 | 320 | |
|
321 | 321 | The second form of spawn (where you pass a list of arguments) is useful |
|
322 | 322 | in situations where you wish to spawn a command and pass it its own |
|
323 | 323 | argument list. This can make syntax more clear. For example, the |
|
324 | 324 | following is equivalent to the previous example:: |
|
325 | 325 | |
|
326 | 326 | shell_cmd = 'ls -l | grep LOG > log_list.txt' |
|
327 | 327 | child = pexpect.spawn('/bin/bash', ['-c', shell_cmd]) |
|
328 | 328 | child.expect(pexpect.EOF) |
|
329 | 329 | |
|
330 | 330 | The maxread attribute sets the read buffer size. This is maximum number |
|
331 | 331 | of bytes that Pexpect will try to read from a TTY at one time. Setting |
|
332 | 332 | the maxread size to 1 will turn off buffering. Setting the maxread |
|
333 | 333 | value higher may help performance in cases where large amounts of |
|
334 | 334 | output are read back from the child. This feature is useful in |
|
335 | 335 | conjunction with searchwindowsize. |
|
336 | 336 | |
|
337 | 337 | The searchwindowsize attribute sets the how far back in the incomming |
|
338 | 338 | seach buffer Pexpect will search for pattern matches. Every time |
|
339 | 339 | Pexpect reads some data from the child it will append the data to the |
|
340 | 340 | incomming buffer. The default is to search from the beginning of the |
|
341 | 341 | imcomming buffer each time new data is read from the child. But this is |
|
342 | 342 | very inefficient if you are running a command that generates a large |
|
343 | 343 | amount of data where you want to match The searchwindowsize does not |
|
344 | 344 | effect the size of the incomming data buffer. You will still have |
|
345 | 345 | access to the full buffer after expect() returns. |
|
346 | 346 | |
|
347 | 347 | The logfile member turns on or off logging. All input and output will |
|
348 | 348 | be copied to the given file object. Set logfile to None to stop |
|
349 | 349 | logging. This is the default. Set logfile to sys.stdout to echo |
|
350 | 350 | everything to standard output. The logfile is flushed after each write. |
|
351 | 351 | |
|
352 | 352 | Example log input and output to a file:: |
|
353 | 353 | |
|
354 | 354 | child = pexpect.spawn('some_command') |
|
355 | 355 | fout = open('mylog.txt','w') |
|
356 | 356 | child.logfile = fout |
|
357 | 357 | |
|
358 | 358 | Example log to stdout:: |
|
359 | 359 | |
|
360 | 360 | child = pexpect.spawn('some_command') |
|
361 | 361 | child.logfile = sys.stdout |
|
362 | 362 | |
|
363 | 363 | The logfile_read and logfile_send members can be used to separately log |
|
364 | 364 | the input from the child and output sent to the child. Sometimes you |
|
365 | 365 | don't want to see everything you write to the child. You only want to |
|
366 | 366 | log what the child sends back. For example:: |
|
367 | 367 | |
|
368 | 368 | child = pexpect.spawn('some_command') |
|
369 | 369 | child.logfile_read = sys.stdout |
|
370 | 370 | |
|
371 | 371 | To separately log output sent to the child use logfile_send:: |
|
372 | 372 | |
|
373 | 373 | self.logfile_send = fout |
|
374 | 374 | |
|
375 | 375 | The delaybeforesend helps overcome a weird behavior that many users |
|
376 | 376 | were experiencing. The typical problem was that a user would expect() a |
|
377 | 377 | "Password:" prompt and then immediately call sendline() to send the |
|
378 | 378 | password. The user would then see that their password was echoed back |
|
379 | 379 | to them. Passwords don't normally echo. The problem is caused by the |
|
380 | 380 | fact that most applications print out the "Password" prompt and then |
|
381 | 381 | turn off stdin echo, but if you send your password before the |
|
382 | 382 | application turned off echo, then you get your password echoed. |
|
383 | 383 | Normally this wouldn't be a problem when interacting with a human at a |
|
384 | 384 | real keyboard. If you introduce a slight delay just before writing then |
|
385 | 385 | this seems to clear up the problem. This was such a common problem for |
|
386 | 386 | many users that I decided that the default pexpect behavior should be |
|
387 | 387 | to sleep just before writing to the child application. 1/20th of a |
|
388 | 388 | second (50 ms) seems to be enough to clear up the problem. You can set |
|
389 | 389 | delaybeforesend to 0 to return to the old behavior. Most Linux machines |
|
390 | 390 | don't like this to be below 0.03. I don't know why. |
|
391 | 391 | |
|
392 | 392 | Note that spawn is clever about finding commands on your path. |
|
393 | 393 | It uses the same logic that "which" uses to find executables. |
|
394 | 394 | |
|
395 | 395 | If you wish to get the exit status of the child you must call the |
|
396 | 396 | close() method. The exit or signal status of the child will be stored |
|
397 | 397 | in self.exitstatus or self.signalstatus. If the child exited normally |
|
398 | 398 | then exitstatus will store the exit return code and signalstatus will |
|
399 | 399 | be None. If the child was terminated abnormally with a signal then |
|
400 | 400 | signalstatus will store the signal value and exitstatus will be None. |
|
401 | 401 | If you need more detail you can also read the self.status member which |
|
402 | 402 | stores the status returned by os.waitpid. You can interpret this using |
|
403 | 403 | os.WIFEXITED/os.WEXITSTATUS or os.WIFSIGNALED/os.TERMSIG. """ |
|
404 | 404 | |
|
405 | 405 | self.STDIN_FILENO = pty.STDIN_FILENO |
|
406 | 406 | self.STDOUT_FILENO = pty.STDOUT_FILENO |
|
407 | 407 | self.STDERR_FILENO = pty.STDERR_FILENO |
|
408 | 408 | self.stdin = sys.stdin |
|
409 | 409 | self.stdout = sys.stdout |
|
410 | 410 | self.stderr = sys.stderr |
|
411 | 411 | |
|
412 | 412 | self.searcher = None |
|
413 | 413 | self.ignorecase = False |
|
414 | 414 | self.before = None |
|
415 | 415 | self.after = None |
|
416 | 416 | self.match = None |
|
417 | 417 | self.match_index = None |
|
418 | 418 | self.terminated = True |
|
419 | 419 | self.exitstatus = None |
|
420 | 420 | self.signalstatus = None |
|
421 | 421 | self.status = None # status returned by os.waitpid |
|
422 | 422 | self.flag_eof = False |
|
423 | 423 | self.pid = None |
|
424 | 424 | self.child_fd = -1 # initially closed |
|
425 | 425 | self.timeout = timeout |
|
426 | 426 | self.delimiter = EOF |
|
427 | 427 | self.logfile = logfile |
|
428 | 428 | self.logfile_read = None # input from child (read_nonblocking) |
|
429 | 429 | self.logfile_send = None # output to send (send, sendline) |
|
430 | 430 | self.maxread = maxread # max bytes to read at one time into buffer |
|
431 | 431 | self.buffer = self._empty_buffer # This is the read buffer. See maxread. |
|
432 | 432 | self.searchwindowsize = searchwindowsize # Anything before searchwindowsize point is preserved, but not searched. |
|
433 | 433 | # Most Linux machines don't like delaybeforesend to be below 0.03 (30 ms). |
|
434 | 434 | self.delaybeforesend = 0.05 # Sets sleep time used just before sending data to child. Time in seconds. |
|
435 | 435 | self.delayafterclose = 0.1 # Sets delay in close() method to allow kernel time to update process status. Time in seconds. |
|
436 | 436 | self.delayafterterminate = 0.1 # Sets delay in terminate() method to allow kernel time to update process status. Time in seconds. |
|
437 | 437 | self.softspace = False # File-like object. |
|
438 | 438 | self.name = '<' + repr(self) + '>' # File-like object. |
|
439 | 439 | self.closed = True # File-like object. |
|
440 | 440 | self.cwd = cwd |
|
441 | 441 | self.env = env |
|
442 | 442 | self.__irix_hack = (sys.platform.lower().find('irix')>=0) # This flags if we are running on irix |
|
443 | 443 | # Solaris uses internal __fork_pty(). All others use pty.fork(). |
|
444 | 444 | if 'solaris' in sys.platform.lower() or 'sunos5' in sys.platform.lower(): |
|
445 | 445 | self.use_native_pty_fork = False |
|
446 | 446 | else: |
|
447 | 447 | self.use_native_pty_fork = True |
|
448 | 448 | |
|
449 | 449 | |
|
450 | 450 | # allow dummy instances for subclasses that may not use command or args. |
|
451 | 451 | if command is None: |
|
452 | 452 | self.command = None |
|
453 | 453 | self.args = None |
|
454 | 454 | self.name = '<pexpect factory incomplete>' |
|
455 | 455 | else: |
|
456 | 456 | self._spawn (command, args) |
|
457 | 457 | |
|
458 | 458 | def __del__(self): |
|
459 | 459 | |
|
460 | 460 | """This makes sure that no system resources are left open. Python only |
|
461 | 461 | garbage collects Python objects. OS file descriptors are not Python |
|
462 | 462 | objects, so they must be handled explicitly. If the child file |
|
463 | 463 | descriptor was opened outside of this class (passed to the constructor) |
|
464 | 464 | then this does not close it. """ |
|
465 | 465 | |
|
466 | 466 | if not self.closed: |
|
467 | 467 | # It is possible for __del__ methods to execute during the |
|
468 | 468 | # teardown of the Python VM itself. Thus self.close() may |
|
469 | 469 | # trigger an exception because os.close may be None. |
|
470 | 470 | # -- Fernando Perez |
|
471 | 471 | try: |
|
472 | 472 | self.close() |
|
473 | 473 | except: |
|
474 | 474 | pass |
|
475 | 475 | |
|
476 | 476 | def __str__(self): |
|
477 | 477 | |
|
478 | 478 | """This returns a human-readable string that represents the state of |
|
479 | 479 | the object. """ |
|
480 | 480 | |
|
481 | 481 | s = [] |
|
482 | 482 | s.append(repr(self)) |
|
483 | 483 | s.append('version: ' + __version__) |
|
484 | 484 | s.append('command: ' + str(self.command)) |
|
485 | 485 | s.append('args: ' + str(self.args)) |
|
486 | 486 | s.append('searcher: ' + str(self.searcher)) |
|
487 | 487 | s.append('buffer (last 100 chars): ' + str(self.buffer)[-100:]) |
|
488 | 488 | s.append('before (last 100 chars): ' + str(self.before)[-100:]) |
|
489 | 489 | s.append('after: ' + str(self.after)) |
|
490 | 490 | s.append('match: ' + str(self.match)) |
|
491 | 491 | s.append('match_index: ' + str(self.match_index)) |
|
492 | 492 | s.append('exitstatus: ' + str(self.exitstatus)) |
|
493 | 493 | s.append('flag_eof: ' + str(self.flag_eof)) |
|
494 | 494 | s.append('pid: ' + str(self.pid)) |
|
495 | 495 | s.append('child_fd: ' + str(self.child_fd)) |
|
496 | 496 | s.append('closed: ' + str(self.closed)) |
|
497 | 497 | s.append('timeout: ' + str(self.timeout)) |
|
498 | 498 | s.append('delimiter: ' + str(self.delimiter)) |
|
499 | 499 | s.append('logfile: ' + str(self.logfile)) |
|
500 | 500 | s.append('logfile_read: ' + str(self.logfile_read)) |
|
501 | 501 | s.append('logfile_send: ' + str(self.logfile_send)) |
|
502 | 502 | s.append('maxread: ' + str(self.maxread)) |
|
503 | 503 | s.append('ignorecase: ' + str(self.ignorecase)) |
|
504 | 504 | s.append('searchwindowsize: ' + str(self.searchwindowsize)) |
|
505 | 505 | s.append('delaybeforesend: ' + str(self.delaybeforesend)) |
|
506 | 506 | s.append('delayafterclose: ' + str(self.delayafterclose)) |
|
507 | 507 | s.append('delayafterterminate: ' + str(self.delayafterterminate)) |
|
508 | 508 | return '\n'.join(s) |
|
509 | 509 | |
|
510 | 510 | def _spawn(self,command,args=[]): |
|
511 | 511 | |
|
512 | 512 | """This starts the given command in a child process. This does all the |
|
513 | 513 | fork/exec type of stuff for a pty. This is called by __init__. If args |
|
514 | 514 | is empty then command will be parsed (split on spaces) and args will be |
|
515 | 515 | set to parsed arguments. """ |
|
516 | 516 | |
|
517 | 517 | # The pid and child_fd of this object get set by this method. |
|
518 | 518 | # Note that it is difficult for this method to fail. |
|
519 | 519 | # You cannot detect if the child process cannot start. |
|
520 | 520 | # So the only way you can tell if the child process started |
|
521 | 521 | # or not is to try to read from the file descriptor. If you get |
|
522 | 522 | # EOF immediately then it means that the child is already dead. |
|
523 | 523 | # That may not necessarily be bad because you may haved spawned a child |
|
524 | 524 | # that performs some task; creates no stdout output; and then dies. |
|
525 | 525 | |
|
526 | 526 | # If command is an int type then it may represent a file descriptor. |
|
527 | 527 | if type(command) == type(0): |
|
528 | 528 | raise ExceptionPexpect ('Command is an int type. If this is a file descriptor then maybe you want to use fdpexpect.fdspawn which takes an existing file descriptor instead of a command string.') |
|
529 | 529 | |
|
530 | 530 | if type (args) != type([]): |
|
531 | 531 | raise TypeError ('The argument, args, must be a list.') |
|
532 | 532 | |
|
533 | 533 | if args == []: |
|
534 | 534 | self.args = split_command_line(command) |
|
535 | 535 | self.command = self.args[0] |
|
536 | 536 | else: |
|
537 | 537 | self.args = args[:] # work with a copy |
|
538 | 538 | self.args.insert (0, command) |
|
539 | 539 | self.command = command |
|
540 | 540 | |
|
541 | 541 | command_with_path = which(self.command) |
|
542 | 542 | if command_with_path is None: |
|
543 | 543 | raise ExceptionPexpect ('The command was not found or was not executable: %s.' % self.command) |
|
544 | 544 | self.command = command_with_path |
|
545 | 545 | self.args[0] = self.command |
|
546 | 546 | |
|
547 | 547 | self.name = '<' + ' '.join (self.args) + '>' |
|
548 | 548 | |
|
549 | 549 | assert self.pid is None, 'The pid member should be None.' |
|
550 | 550 | assert self.command is not None, 'The command member should not be None.' |
|
551 | 551 | |
|
552 | 552 | if self.use_native_pty_fork: |
|
553 | 553 | try: |
|
554 | 554 | self.pid, self.child_fd = pty.fork() |
|
555 | 555 | except OSError as e: |
|
556 | 556 | raise ExceptionPexpect('Error! pty.fork() failed: ' + str(e)) |
|
557 | 557 | else: # Use internal __fork_pty |
|
558 | 558 | self.pid, self.child_fd = self.__fork_pty() |
|
559 | 559 | |
|
560 | 560 | if self.pid == 0: # Child |
|
561 | 561 | try: |
|
562 | 562 | self.child_fd = sys.stdout.fileno() # used by setwinsize() |
|
563 | 563 | self.setwinsize(24, 80) |
|
564 | 564 | except: |
|
565 | 565 | # Some platforms do not like setwinsize (Cygwin). |
|
566 | 566 | # This will cause problem when running applications that |
|
567 | 567 | # are very picky about window size. |
|
568 | 568 | # This is a serious limitation, but not a show stopper. |
|
569 | 569 | pass |
|
570 | 570 | # Do not allow child to inherit open file descriptors from parent. |
|
571 | 571 | max_fd = resource.getrlimit(resource.RLIMIT_NOFILE)[0] |
|
572 | 572 | for i in range (3, max_fd): |
|
573 | 573 | try: |
|
574 | 574 | os.close (i) |
|
575 | 575 | except OSError: |
|
576 | 576 | pass |
|
577 | 577 | |
|
578 | 578 | # I don't know why this works, but ignoring SIGHUP fixes a |
|
579 | 579 | # problem when trying to start a Java daemon with sudo |
|
580 | 580 | # (specifically, Tomcat). |
|
581 | 581 | signal.signal(signal.SIGHUP, signal.SIG_IGN) |
|
582 | 582 | |
|
583 | 583 | if self.cwd is not None: |
|
584 | 584 | os.chdir(self.cwd) |
|
585 | 585 | if self.env is None: |
|
586 | 586 | os.execv(self.command, self.args) |
|
587 | 587 | else: |
|
588 | 588 | os.execvpe(self.command, self.args, self.env) |
|
589 | 589 | |
|
590 | 590 | # Parent |
|
591 | 591 | self.terminated = False |
|
592 | 592 | self.closed = False |
|
593 | 593 | |
|
594 | 594 | def __fork_pty(self): |
|
595 | 595 | |
|
596 | 596 | """This implements a substitute for the forkpty system call. This |
|
597 | 597 | should be more portable than the pty.fork() function. Specifically, |
|
598 | 598 | this should work on Solaris. |
|
599 | 599 | |
|
600 | 600 | Modified 10.06.05 by Geoff Marshall: Implemented __fork_pty() method to |
|
601 | 601 | resolve the issue with Python's pty.fork() not supporting Solaris, |
|
602 | 602 | particularly ssh. Based on patch to posixmodule.c authored by Noah |
|
603 | 603 | Spurrier:: |
|
604 | 604 | |
|
605 | 605 | http://mail.python.org/pipermail/python-dev/2003-May/035281.html |
|
606 | 606 | |
|
607 | 607 | """ |
|
608 | 608 | |
|
609 | 609 | parent_fd, child_fd = os.openpty() |
|
610 | 610 | if parent_fd < 0 or child_fd < 0: |
|
611 |
raise ExceptionPexpect |
|
|
611 | raise ExceptionPexpect("Error! Could not open pty with os.openpty().") | |
|
612 | 612 | |
|
613 | 613 | pid = os.fork() |
|
614 | 614 | if pid < 0: |
|
615 |
raise ExceptionPexpect |
|
|
615 | raise ExceptionPexpect("Error! Failed os.fork().") | |
|
616 | 616 | elif pid == 0: |
|
617 | 617 | # Child. |
|
618 | 618 | os.close(parent_fd) |
|
619 | 619 | self.__pty_make_controlling_tty(child_fd) |
|
620 | 620 | |
|
621 | 621 | os.dup2(child_fd, 0) |
|
622 | 622 | os.dup2(child_fd, 1) |
|
623 | 623 | os.dup2(child_fd, 2) |
|
624 | 624 | |
|
625 | 625 | if child_fd > 2: |
|
626 | 626 | os.close(child_fd) |
|
627 | 627 | else: |
|
628 | 628 | # Parent. |
|
629 | 629 | os.close(child_fd) |
|
630 | 630 | |
|
631 | 631 | return pid, parent_fd |
|
632 | 632 | |
|
633 | 633 | def __pty_make_controlling_tty(self, tty_fd): |
|
634 | 634 | |
|
635 | 635 | """This makes the pseudo-terminal the controlling tty. This should be |
|
636 | 636 | more portable than the pty.fork() function. Specifically, this should |
|
637 | 637 | work on Solaris. """ |
|
638 | 638 | |
|
639 | 639 | child_name = os.ttyname(tty_fd) |
|
640 | 640 | |
|
641 | 641 | # Disconnect from controlling tty. Harmless if not already connected. |
|
642 | 642 | try: |
|
643 | 643 | fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY); |
|
644 | 644 | if fd >= 0: |
|
645 | 645 | os.close(fd) |
|
646 | 646 | except: |
|
647 | 647 | # Already disconnected. This happens if running inside cron. |
|
648 | 648 | pass |
|
649 | 649 | |
|
650 | 650 | os.setsid() |
|
651 | 651 | |
|
652 | 652 | # Verify we are disconnected from controlling tty |
|
653 | 653 | # by attempting to open it again. |
|
654 | 654 | try: |
|
655 | 655 | fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY); |
|
656 | 656 | if fd >= 0: |
|
657 | 657 | os.close(fd) |
|
658 |
raise ExceptionPexpect |
|
|
658 | raise ExceptionPexpect("Error! Failed to disconnect from controlling tty. It is still possible to open /dev/tty.") | |
|
659 | 659 | except: |
|
660 | 660 | # Good! We are disconnected from a controlling tty. |
|
661 | 661 | pass |
|
662 | 662 | |
|
663 | 663 | # Verify we can open child pty. |
|
664 | 664 | fd = os.open(child_name, os.O_RDWR); |
|
665 | 665 | if fd < 0: |
|
666 |
raise ExceptionPexpect |
|
|
666 | raise ExceptionPexpect("Error! Could not open child pty, " + child_name) | |
|
667 | 667 | else: |
|
668 | 668 | os.close(fd) |
|
669 | 669 | |
|
670 | 670 | # Verify we now have a controlling tty. |
|
671 | 671 | fd = os.open("/dev/tty", os.O_WRONLY) |
|
672 | 672 | if fd < 0: |
|
673 |
raise ExceptionPexpect |
|
|
673 | raise ExceptionPexpect("Error! Could not open controlling tty, /dev/tty") | |
|
674 | 674 | else: |
|
675 | 675 | os.close(fd) |
|
676 | 676 | |
|
677 | 677 | def fileno (self): # File-like object. |
|
678 | 678 | |
|
679 | 679 | """This returns the file descriptor of the pty for the child. |
|
680 | 680 | """ |
|
681 | 681 | |
|
682 | 682 | return self.child_fd |
|
683 | 683 | |
|
684 | 684 | def close (self, force=True): # File-like object. |
|
685 | 685 | |
|
686 | 686 | """This closes the connection with the child application. Note that |
|
687 | 687 | calling close() more than once is valid. This emulates standard Python |
|
688 | 688 | behavior with files. Set force to True if you want to make sure that |
|
689 | 689 | the child is terminated (SIGKILL is sent if the child ignores SIGHUP |
|
690 | 690 | and SIGINT). """ |
|
691 | 691 | |
|
692 | 692 | if not self.closed: |
|
693 | 693 | self.flush() |
|
694 | 694 | os.close (self.child_fd) |
|
695 | 695 | time.sleep(self.delayafterclose) # Give kernel time to update process status. |
|
696 | 696 | if self.isalive(): |
|
697 | 697 | if not self.terminate(force): |
|
698 | 698 | raise ExceptionPexpect ('close() could not terminate the child using terminate()') |
|
699 | 699 | self.child_fd = -1 |
|
700 | 700 | self.closed = True |
|
701 | 701 | #self.pid = None |
|
702 | 702 | |
|
703 | 703 | def flush (self): # File-like object. |
|
704 | 704 | |
|
705 | 705 | """This does nothing. It is here to support the interface for a |
|
706 | 706 | File-like object. """ |
|
707 | 707 | |
|
708 | 708 | pass |
|
709 | 709 | |
|
710 | 710 | def isatty (self): # File-like object. |
|
711 | 711 | |
|
712 | 712 | """This returns True if the file descriptor is open and connected to a |
|
713 | 713 | tty(-like) device, else False. """ |
|
714 | 714 | |
|
715 | 715 | return os.isatty(self.child_fd) |
|
716 | 716 | |
|
717 | 717 | def waitnoecho (self, timeout=-1): |
|
718 | 718 | |
|
719 | 719 | """This waits until the terminal ECHO flag is set False. This returns |
|
720 | 720 | True if the echo mode is off. This returns False if the ECHO flag was |
|
721 | 721 | not set False before the timeout. This can be used to detect when the |
|
722 | 722 | child is waiting for a password. Usually a child application will turn |
|
723 | 723 | off echo mode when it is waiting for the user to enter a password. For |
|
724 | 724 | example, instead of expecting the "password:" prompt you can wait for |
|
725 | 725 | the child to set ECHO off:: |
|
726 | 726 | |
|
727 | 727 | p = pexpect.spawn ('ssh user@example.com') |
|
728 | 728 | p.waitnoecho() |
|
729 | 729 | p.sendline(mypassword) |
|
730 | 730 | |
|
731 | 731 | If timeout==-1 then this method will use the value in self.timeout. |
|
732 | 732 | If timeout==None then this method to block until ECHO flag is False. |
|
733 | 733 | """ |
|
734 | 734 | |
|
735 | 735 | if timeout == -1: |
|
736 | 736 | timeout = self.timeout |
|
737 | 737 | if timeout is not None: |
|
738 | 738 | end_time = time.time() + timeout |
|
739 | 739 | while True: |
|
740 | 740 | if not self.getecho(): |
|
741 | 741 | return True |
|
742 | 742 | if timeout < 0 and timeout is not None: |
|
743 | 743 | return False |
|
744 | 744 | if timeout is not None: |
|
745 | 745 | timeout = end_time - time.time() |
|
746 | 746 | time.sleep(0.1) |
|
747 | 747 | |
|
748 | 748 | def getecho (self): |
|
749 | 749 | |
|
750 | 750 | """This returns the terminal echo mode. This returns True if echo is |
|
751 | 751 | on or False if echo is off. Child applications that are expecting you |
|
752 | 752 | to enter a password often set ECHO False. See waitnoecho(). """ |
|
753 | 753 | |
|
754 | 754 | attr = termios.tcgetattr(self.child_fd) |
|
755 | 755 | if attr[3] & termios.ECHO: |
|
756 | 756 | return True |
|
757 | 757 | return False |
|
758 | 758 | |
|
759 | 759 | def setecho (self, state): |
|
760 | 760 | |
|
761 | 761 | """This sets the terminal echo mode on or off. Note that anything the |
|
762 | 762 | child sent before the echo will be lost, so you should be sure that |
|
763 | 763 | your input buffer is empty before you call setecho(). For example, the |
|
764 | 764 | following will work as expected:: |
|
765 | 765 | |
|
766 | 766 | p = pexpect.spawn('cat') |
|
767 | 767 | p.sendline ('1234') # We will see this twice (once from tty echo and again from cat). |
|
768 | 768 | p.expect (['1234']) |
|
769 | 769 | p.expect (['1234']) |
|
770 | 770 | p.setecho(False) # Turn off tty echo |
|
771 | 771 | p.sendline ('abcd') # We will set this only once (echoed by cat). |
|
772 | 772 | p.sendline ('wxyz') # We will set this only once (echoed by cat) |
|
773 | 773 | p.expect (['abcd']) |
|
774 | 774 | p.expect (['wxyz']) |
|
775 | 775 | |
|
776 | 776 | The following WILL NOT WORK because the lines sent before the setecho |
|
777 | 777 | will be lost:: |
|
778 | 778 | |
|
779 | 779 | p = pexpect.spawn('cat') |
|
780 | 780 | p.sendline ('1234') # We will see this twice (once from tty echo and again from cat). |
|
781 | 781 | p.setecho(False) # Turn off tty echo |
|
782 | 782 | p.sendline ('abcd') # We will set this only once (echoed by cat). |
|
783 | 783 | p.sendline ('wxyz') # We will set this only once (echoed by cat) |
|
784 | 784 | p.expect (['1234']) |
|
785 | 785 | p.expect (['1234']) |
|
786 | 786 | p.expect (['abcd']) |
|
787 | 787 | p.expect (['wxyz']) |
|
788 | 788 | """ |
|
789 | 789 | |
|
790 | 790 | self.child_fd |
|
791 | 791 | attr = termios.tcgetattr(self.child_fd) |
|
792 | 792 | if state: |
|
793 | 793 | attr[3] = attr[3] | termios.ECHO |
|
794 | 794 | else: |
|
795 | 795 | attr[3] = attr[3] & ~termios.ECHO |
|
796 | 796 | # I tried TCSADRAIN and TCSAFLUSH, but these were inconsistent |
|
797 | 797 | # and blocked on some platforms. TCSADRAIN is probably ideal if it worked. |
|
798 | 798 | termios.tcsetattr(self.child_fd, termios.TCSANOW, attr) |
|
799 | 799 | |
|
800 | 800 | def read_nonblocking (self, size = 1, timeout = -1): |
|
801 | 801 | |
|
802 | 802 | """This reads at most size bytes from the child application. It |
|
803 | 803 | includes a timeout. If the read does not complete within the timeout |
|
804 | 804 | period then a TIMEOUT exception is raised. If the end of file is read |
|
805 | 805 | then an EOF exception will be raised. If a log file was set using |
|
806 | 806 | setlog() then all data will also be written to the log file. |
|
807 | 807 | |
|
808 | 808 | If timeout is None then the read may block indefinitely. If timeout is -1 |
|
809 | 809 | then the self.timeout value is used. If timeout is 0 then the child is |
|
810 | 810 | polled and if there was no data immediately ready then this will raise |
|
811 | 811 | a TIMEOUT exception. |
|
812 | 812 | |
|
813 | 813 | The timeout refers only to the amount of time to read at least one |
|
814 | 814 | character. This is not effected by the 'size' parameter, so if you call |
|
815 | 815 | read_nonblocking(size=100, timeout=30) and only one character is |
|
816 | 816 | available right away then one character will be returned immediately. |
|
817 | 817 | It will not wait for 30 seconds for another 99 characters to come in. |
|
818 | 818 | |
|
819 | 819 | This is a wrapper around os.read(). It uses select.select() to |
|
820 | 820 | implement the timeout. """ |
|
821 | 821 | |
|
822 | 822 | if self.closed: |
|
823 | 823 | raise ValueError ('I/O operation on closed file in read_nonblocking().') |
|
824 | 824 | |
|
825 | 825 | if timeout == -1: |
|
826 | 826 | timeout = self.timeout |
|
827 | 827 | |
|
828 | 828 | # Note that some systems such as Solaris do not give an EOF when |
|
829 | 829 | # the child dies. In fact, you can still try to read |
|
830 | 830 | # from the child_fd -- it will block forever or until TIMEOUT. |
|
831 | 831 | # For this case, I test isalive() before doing any reading. |
|
832 | 832 | # If isalive() is false, then I pretend that this is the same as EOF. |
|
833 | 833 | if not self.isalive(): |
|
834 | 834 | r,w,e = self.__select([self.child_fd], [], [], 0) # timeout of 0 means "poll" |
|
835 | 835 | if not r: |
|
836 | 836 | self.flag_eof = True |
|
837 | 837 | raise EOF ('End Of File (EOF) in read_nonblocking(). Braindead platform.') |
|
838 | 838 | elif self.__irix_hack: |
|
839 | 839 | # This is a hack for Irix. It seems that Irix requires a long delay before checking isalive. |
|
840 | 840 | # This adds a 2 second delay, but only when the child is terminated. |
|
841 | 841 | r, w, e = self.__select([self.child_fd], [], [], 2) |
|
842 | 842 | if not r and not self.isalive(): |
|
843 | 843 | self.flag_eof = True |
|
844 | 844 | raise EOF ('End Of File (EOF) in read_nonblocking(). Pokey platform.') |
|
845 | 845 | |
|
846 | 846 | r,w,e = self.__select([self.child_fd], [], [], timeout) |
|
847 | 847 | |
|
848 | 848 | if not r: |
|
849 | 849 | if not self.isalive(): |
|
850 | 850 | # Some platforms, such as Irix, will claim that their processes are alive; |
|
851 | 851 | # then timeout on the select; and then finally admit that they are not alive. |
|
852 | 852 | self.flag_eof = True |
|
853 | 853 | raise EOF ('End of File (EOF) in read_nonblocking(). Very pokey platform.') |
|
854 | 854 | else: |
|
855 | 855 | raise TIMEOUT ('Timeout exceeded in read_nonblocking().') |
|
856 | 856 | |
|
857 | 857 | if self.child_fd in r: |
|
858 | 858 | try: |
|
859 | 859 | s = os.read(self.child_fd, size) |
|
860 | 860 | except OSError as e: # Linux does this |
|
861 | 861 | self.flag_eof = True |
|
862 | 862 | raise EOF ('End Of File (EOF) in read_nonblocking(). Exception style platform.') |
|
863 | 863 | if s == b'': # BSD style |
|
864 | 864 | self.flag_eof = True |
|
865 | 865 | raise EOF ('End Of File (EOF) in read_nonblocking(). Empty string style platform.') |
|
866 | 866 | |
|
867 | 867 | s2 = self._cast_buffer_type(s) |
|
868 | 868 | if self.logfile is not None: |
|
869 | 869 | self.logfile.write(s2) |
|
870 | 870 | self.logfile.flush() |
|
871 | 871 | if self.logfile_read is not None: |
|
872 | 872 | self.logfile_read.write(s2) |
|
873 | 873 | self.logfile_read.flush() |
|
874 | 874 | |
|
875 | 875 | return s |
|
876 | 876 | |
|
877 | 877 | raise ExceptionPexpect ('Reached an unexpected state in read_nonblocking().') |
|
878 | 878 | |
|
879 | 879 | def read (self, size = -1): # File-like object. |
|
880 | 880 | """This reads at most "size" bytes from the file (less if the read hits |
|
881 | 881 | EOF before obtaining size bytes). If the size argument is negative or |
|
882 | 882 | omitted, read all data until EOF is reached. The bytes are returned as |
|
883 | 883 | a string object. An empty string is returned when EOF is encountered |
|
884 | 884 | immediately. """ |
|
885 | 885 | |
|
886 | 886 | if size == 0: |
|
887 | 887 | return self._empty_buffer |
|
888 | 888 | if size < 0: |
|
889 | 889 | self.expect (self.delimiter) # delimiter default is EOF |
|
890 | 890 | return self.before |
|
891 | 891 | |
|
892 | 892 | # I could have done this more directly by not using expect(), but |
|
893 | 893 | # I deliberately decided to couple read() to expect() so that |
|
894 | 894 | # I would catch any bugs early and ensure consistant behavior. |
|
895 | 895 | # It's a little less efficient, but there is less for me to |
|
896 | 896 | # worry about if I have to later modify read() or expect(). |
|
897 | 897 | # Note, it's OK if size==-1 in the regex. That just means it |
|
898 | 898 | # will never match anything in which case we stop only on EOF. |
|
899 | 899 | if self._buffer_type is bytes: |
|
900 | 900 | pat = (u'.{%d}' % size).encode('ascii') |
|
901 | 901 | else: |
|
902 | 902 | pat = u'.{%d}' % size |
|
903 | 903 | cre = re.compile(pat, re.DOTALL) |
|
904 | 904 | index = self.expect ([cre, self.delimiter]) # delimiter default is EOF |
|
905 | 905 | if index == 0: |
|
906 | 906 | return self.after ### self.before should be ''. Should I assert this? |
|
907 | 907 | return self.before |
|
908 | 908 | |
|
909 | 909 | def readline(self, size = -1): |
|
910 | 910 | """This reads and returns one entire line. A trailing newline is kept |
|
911 | 911 | in the string, but may be absent when a file ends with an incomplete |
|
912 | 912 | line. Note: This readline() looks for a \\r\\n pair even on UNIX |
|
913 | 913 | because this is what the pseudo tty device returns. So contrary to what |
|
914 | 914 | you may expect you will receive the newline as \\r\\n. An empty string |
|
915 | 915 | is returned when EOF is hit immediately. Currently, the size argument is |
|
916 | 916 | mostly ignored, so this behavior is not standard for a file-like |
|
917 | 917 | object. If size is 0 then an empty string is returned. """ |
|
918 | 918 | |
|
919 | 919 | if size == 0: |
|
920 | 920 | return self._empty_buffer |
|
921 | 921 | index = self.expect ([self._pty_newline, self.delimiter]) # delimiter default is EOF |
|
922 | 922 | if index == 0: |
|
923 | 923 | return self.before + self._pty_newline |
|
924 | 924 | return self.before |
|
925 | 925 | |
|
926 | 926 | def __iter__ (self): # File-like object. |
|
927 | 927 | |
|
928 | 928 | """This is to support iterators over a file-like object. |
|
929 | 929 | """ |
|
930 | 930 | |
|
931 | 931 | return self |
|
932 | 932 | |
|
933 | 933 | def next (self): # File-like object. |
|
934 | 934 | |
|
935 | 935 | """This is to support iterators over a file-like object. |
|
936 | 936 | """ |
|
937 | 937 | |
|
938 | 938 | result = self.readline() |
|
939 | 939 | if result == self._empty_buffer: |
|
940 | 940 | raise StopIteration |
|
941 | 941 | return result |
|
942 | 942 | |
|
943 | 943 | def readlines (self, sizehint = -1): # File-like object. |
|
944 | 944 | |
|
945 | 945 | """This reads until EOF using readline() and returns a list containing |
|
946 | 946 | the lines thus read. The optional "sizehint" argument is ignored. """ |
|
947 | 947 | |
|
948 | 948 | lines = [] |
|
949 | 949 | while True: |
|
950 | 950 | line = self.readline() |
|
951 | 951 | if not line: |
|
952 | 952 | break |
|
953 | 953 | lines.append(line) |
|
954 | 954 | return lines |
|
955 | 955 | |
|
956 | 956 | def write(self, s): # File-like object. |
|
957 | 957 | |
|
958 | 958 | """This is similar to send() except that there is no return value. |
|
959 | 959 | """ |
|
960 | 960 | |
|
961 | 961 | self.send (s) |
|
962 | 962 | |
|
963 | 963 | def writelines (self, sequence): # File-like object. |
|
964 | 964 | |
|
965 | 965 | """This calls write() for each element in the sequence. The sequence |
|
966 | 966 | can be any iterable object producing strings, typically a list of |
|
967 | 967 | strings. This does not add line separators There is no return value. |
|
968 | 968 | """ |
|
969 | 969 | |
|
970 | 970 | for s in sequence: |
|
971 | 971 | self.write (s) |
|
972 | 972 | |
|
973 | 973 | def send(self, s): |
|
974 | 974 | |
|
975 | 975 | """This sends a string to the child process. This returns the number of |
|
976 | 976 | bytes written. If a log file was set then the data is also written to |
|
977 | 977 | the log. """ |
|
978 | 978 | |
|
979 | 979 | time.sleep(self.delaybeforesend) |
|
980 | 980 | |
|
981 | 981 | s2 = self._cast_buffer_type(s) |
|
982 | 982 | if self.logfile is not None: |
|
983 | 983 | self.logfile.write(s2) |
|
984 | 984 | self.logfile.flush() |
|
985 | 985 | if self.logfile_send is not None: |
|
986 | 986 | self.logfile_send.write(s2) |
|
987 | 987 | self.logfile_send.flush() |
|
988 | 988 | c = os.write (self.child_fd, _cast_bytes(s, self.encoding)) |
|
989 | 989 | return c |
|
990 | 990 | |
|
991 | 991 | def sendline(self, s=''): |
|
992 | 992 | |
|
993 | 993 | """This is like send(), but it adds a line feed (os.linesep). This |
|
994 | 994 | returns the number of bytes written. """ |
|
995 | 995 | |
|
996 | 996 | n = self.send (s) |
|
997 | 997 | n = n + self.send (os.linesep) |
|
998 | 998 | return n |
|
999 | 999 | |
|
1000 | 1000 | def sendcontrol(self, char): |
|
1001 | 1001 | |
|
1002 | 1002 | """This sends a control character to the child such as Ctrl-C or |
|
1003 | 1003 | Ctrl-D. For example, to send a Ctrl-G (ASCII 7):: |
|
1004 | 1004 | |
|
1005 | 1005 | child.sendcontrol('g') |
|
1006 | 1006 | |
|
1007 | 1007 | See also, sendintr() and sendeof(). |
|
1008 | 1008 | """ |
|
1009 | 1009 | |
|
1010 | 1010 | char = char.lower() |
|
1011 | 1011 | a = ord(char) |
|
1012 | 1012 | if a>=97 and a<=122: |
|
1013 | 1013 | a = a - ord('a') + 1 |
|
1014 | 1014 | return self.send (chr(a)) |
|
1015 | 1015 | d = {'@':0, '`':0, |
|
1016 | 1016 | '[':27, '{':27, |
|
1017 | 1017 | '\\':28, '|':28, |
|
1018 | 1018 | ']':29, '}': 29, |
|
1019 | 1019 | '^':30, '~':30, |
|
1020 | 1020 | '_':31, |
|
1021 | 1021 | '?':127} |
|
1022 | 1022 | if char not in d: |
|
1023 | 1023 | return 0 |
|
1024 | 1024 | return self.send (chr(d[char])) |
|
1025 | 1025 | |
|
1026 | 1026 | def sendeof(self): |
|
1027 | 1027 | |
|
1028 | 1028 | """This sends an EOF to the child. This sends a character which causes |
|
1029 | 1029 | the pending parent output buffer to be sent to the waiting child |
|
1030 | 1030 | program without waiting for end-of-line. If it is the first character |
|
1031 | 1031 | of the line, the read() in the user program returns 0, which signifies |
|
1032 | 1032 | end-of-file. This means to work as expected a sendeof() has to be |
|
1033 | 1033 | called at the beginning of a line. This method does not send a newline. |
|
1034 | 1034 | It is the responsibility of the caller to ensure the eof is sent at the |
|
1035 | 1035 | beginning of a line. """ |
|
1036 | 1036 | |
|
1037 | 1037 | ### Hmmm... how do I send an EOF? |
|
1038 | 1038 | ###C if ((m = write(pty, *buf, p - *buf)) < 0) |
|
1039 | 1039 | ###C return (errno == EWOULDBLOCK) ? n : -1; |
|
1040 | 1040 | #fd = sys.stdin.fileno() |
|
1041 | 1041 | #old = termios.tcgetattr(fd) # remember current state |
|
1042 | 1042 | #attr = termios.tcgetattr(fd) |
|
1043 | 1043 | #attr[3] = attr[3] | termios.ICANON # ICANON must be set to recognize EOF |
|
1044 | 1044 | #try: # use try/finally to ensure state gets restored |
|
1045 | 1045 | # termios.tcsetattr(fd, termios.TCSADRAIN, attr) |
|
1046 | 1046 | # if hasattr(termios, 'CEOF'): |
|
1047 | 1047 | # os.write (self.child_fd, '%c' % termios.CEOF) |
|
1048 | 1048 | # else: |
|
1049 | 1049 | # # Silly platform does not define CEOF so assume CTRL-D |
|
1050 | 1050 | # os.write (self.child_fd, '%c' % 4) |
|
1051 | 1051 | #finally: # restore state |
|
1052 | 1052 | # termios.tcsetattr(fd, termios.TCSADRAIN, old) |
|
1053 | 1053 | if hasattr(termios, 'VEOF'): |
|
1054 | 1054 | char = termios.tcgetattr(self.child_fd)[6][termios.VEOF] |
|
1055 | 1055 | else: |
|
1056 | 1056 | # platform does not define VEOF so assume CTRL-D |
|
1057 | 1057 | char = chr(4) |
|
1058 | 1058 | self.send(char) |
|
1059 | 1059 | |
|
1060 | 1060 | def sendintr(self): |
|
1061 | 1061 | |
|
1062 | 1062 | """This sends a SIGINT to the child. It does not require |
|
1063 | 1063 | the SIGINT to be the first character on a line. """ |
|
1064 | 1064 | |
|
1065 | 1065 | if hasattr(termios, 'VINTR'): |
|
1066 | 1066 | char = termios.tcgetattr(self.child_fd)[6][termios.VINTR] |
|
1067 | 1067 | else: |
|
1068 | 1068 | # platform does not define VINTR so assume CTRL-C |
|
1069 | 1069 | char = chr(3) |
|
1070 | 1070 | self.send (char) |
|
1071 | 1071 | |
|
1072 | 1072 | def eof (self): |
|
1073 | 1073 | |
|
1074 | 1074 | """This returns True if the EOF exception was ever raised. |
|
1075 | 1075 | """ |
|
1076 | 1076 | |
|
1077 | 1077 | return self.flag_eof |
|
1078 | 1078 | |
|
1079 | 1079 | def terminate(self, force=False): |
|
1080 | 1080 | |
|
1081 | 1081 | """This forces a child process to terminate. It starts nicely with |
|
1082 | 1082 | SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This |
|
1083 | 1083 | returns True if the child was terminated. This returns False if the |
|
1084 | 1084 | child could not be terminated. """ |
|
1085 | 1085 | |
|
1086 | 1086 | if not self.isalive(): |
|
1087 | 1087 | return True |
|
1088 | 1088 | try: |
|
1089 | 1089 | self.kill(signal.SIGHUP) |
|
1090 | 1090 | time.sleep(self.delayafterterminate) |
|
1091 | 1091 | if not self.isalive(): |
|
1092 | 1092 | return True |
|
1093 | 1093 | self.kill(signal.SIGCONT) |
|
1094 | 1094 | time.sleep(self.delayafterterminate) |
|
1095 | 1095 | if not self.isalive(): |
|
1096 | 1096 | return True |
|
1097 | 1097 | self.kill(signal.SIGINT) |
|
1098 | 1098 | time.sleep(self.delayafterterminate) |
|
1099 | 1099 | if not self.isalive(): |
|
1100 | 1100 | return True |
|
1101 | 1101 | if force: |
|
1102 | 1102 | self.kill(signal.SIGKILL) |
|
1103 | 1103 | time.sleep(self.delayafterterminate) |
|
1104 | 1104 | if not self.isalive(): |
|
1105 | 1105 | return True |
|
1106 | 1106 | else: |
|
1107 | 1107 | return False |
|
1108 | 1108 | return False |
|
1109 | 1109 | except OSError as e: |
|
1110 | 1110 | # I think there are kernel timing issues that sometimes cause |
|
1111 | 1111 | # this to happen. I think isalive() reports True, but the |
|
1112 | 1112 | # process is dead to the kernel. |
|
1113 | 1113 | # Make one last attempt to see if the kernel is up to date. |
|
1114 | 1114 | time.sleep(self.delayafterterminate) |
|
1115 | 1115 | if not self.isalive(): |
|
1116 | 1116 | return True |
|
1117 | 1117 | else: |
|
1118 | 1118 | return False |
|
1119 | 1119 | |
|
1120 | 1120 | def wait(self): |
|
1121 | 1121 | |
|
1122 | 1122 | """This waits until the child exits. This is a blocking call. This will |
|
1123 | 1123 | not read any data from the child, so this will block forever if the |
|
1124 | 1124 | child has unread output and has terminated. In other words, the child |
|
1125 | 1125 | may have printed output then called exit(); but, technically, the child |
|
1126 | 1126 | is still alive until its output is read. """ |
|
1127 | 1127 | |
|
1128 | 1128 | if self.isalive(): |
|
1129 | 1129 | pid, status = os.waitpid(self.pid, 0) |
|
1130 | 1130 | else: |
|
1131 | 1131 | raise ExceptionPexpect ('Cannot wait for dead child process.') |
|
1132 | 1132 | self.exitstatus = os.WEXITSTATUS(status) |
|
1133 | 1133 | if os.WIFEXITED (status): |
|
1134 | 1134 | self.status = status |
|
1135 | 1135 | self.exitstatus = os.WEXITSTATUS(status) |
|
1136 | 1136 | self.signalstatus = None |
|
1137 | 1137 | self.terminated = True |
|
1138 | 1138 | elif os.WIFSIGNALED (status): |
|
1139 | 1139 | self.status = status |
|
1140 | 1140 | self.exitstatus = None |
|
1141 | 1141 | self.signalstatus = os.WTERMSIG(status) |
|
1142 | 1142 | self.terminated = True |
|
1143 | 1143 | elif os.WIFSTOPPED (status): |
|
1144 | 1144 | raise ExceptionPexpect ('Wait was called for a child process that is stopped. This is not supported. Is some other process attempting job control with our child pid?') |
|
1145 | 1145 | return self.exitstatus |
|
1146 | 1146 | |
|
1147 | 1147 | def isalive(self): |
|
1148 | 1148 | |
|
1149 | 1149 | """This tests if the child process is running or not. This is |
|
1150 | 1150 | non-blocking. If the child was terminated then this will read the |
|
1151 | 1151 | exitstatus or signalstatus of the child. This returns True if the child |
|
1152 | 1152 | process appears to be running or False if not. It can take literally |
|
1153 | 1153 | SECONDS for Solaris to return the right status. """ |
|
1154 | 1154 | |
|
1155 | 1155 | if self.terminated: |
|
1156 | 1156 | return False |
|
1157 | 1157 | |
|
1158 | 1158 | if self.flag_eof: |
|
1159 | 1159 | # This is for Linux, which requires the blocking form of waitpid to get |
|
1160 | 1160 | # status of a defunct process. This is super-lame. The flag_eof would have |
|
1161 | 1161 | # been set in read_nonblocking(), so this should be safe. |
|
1162 | 1162 | waitpid_options = 0 |
|
1163 | 1163 | else: |
|
1164 | 1164 | waitpid_options = os.WNOHANG |
|
1165 | 1165 | |
|
1166 | 1166 | try: |
|
1167 | 1167 | pid, status = os.waitpid(self.pid, waitpid_options) |
|
1168 | 1168 | except OSError as e: # No child processes |
|
1169 | 1169 | if e.errno == errno.ECHILD: |
|
1170 | 1170 | raise ExceptionPexpect ('isalive() encountered condition where "terminated" is 0, but there was no child process. Did someone else call waitpid() on our process?') |
|
1171 | 1171 | else: |
|
1172 | 1172 | raise e |
|
1173 | 1173 | |
|
1174 | 1174 | # I have to do this twice for Solaris. I can't even believe that I figured this out... |
|
1175 | 1175 | # If waitpid() returns 0 it means that no child process wishes to |
|
1176 | 1176 | # report, and the value of status is undefined. |
|
1177 | 1177 | if pid == 0: |
|
1178 | 1178 | try: |
|
1179 | 1179 | pid, status = os.waitpid(self.pid, waitpid_options) ### os.WNOHANG) # Solaris! |
|
1180 | 1180 | except OSError as e: # This should never happen... |
|
1181 | 1181 | if e[0] == errno.ECHILD: |
|
1182 | 1182 | raise ExceptionPexpect ('isalive() encountered condition that should never happen. There was no child process. Did someone else call waitpid() on our process?') |
|
1183 | 1183 | else: |
|
1184 | 1184 | raise e |
|
1185 | 1185 | |
|
1186 | 1186 | # If pid is still 0 after two calls to waitpid() then |
|
1187 | 1187 | # the process really is alive. This seems to work on all platforms, except |
|
1188 | 1188 | # for Irix which seems to require a blocking call on waitpid or select, so I let read_nonblocking |
|
1189 | 1189 | # take care of this situation (unfortunately, this requires waiting through the timeout). |
|
1190 | 1190 | if pid == 0: |
|
1191 | 1191 | return True |
|
1192 | 1192 | |
|
1193 | 1193 | if pid == 0: |
|
1194 | 1194 | return True |
|
1195 | 1195 | |
|
1196 | 1196 | if os.WIFEXITED (status): |
|
1197 | 1197 | self.status = status |
|
1198 | 1198 | self.exitstatus = os.WEXITSTATUS(status) |
|
1199 | 1199 | self.signalstatus = None |
|
1200 | 1200 | self.terminated = True |
|
1201 | 1201 | elif os.WIFSIGNALED (status): |
|
1202 | 1202 | self.status = status |
|
1203 | 1203 | self.exitstatus = None |
|
1204 | 1204 | self.signalstatus = os.WTERMSIG(status) |
|
1205 | 1205 | self.terminated = True |
|
1206 | 1206 | elif os.WIFSTOPPED (status): |
|
1207 | 1207 | raise ExceptionPexpect ('isalive() encountered condition where child process is stopped. This is not supported. Is some other process attempting job control with our child pid?') |
|
1208 | 1208 | return False |
|
1209 | 1209 | |
|
1210 | 1210 | def kill(self, sig): |
|
1211 | 1211 | |
|
1212 | 1212 | """This sends the given signal to the child application. In keeping |
|
1213 | 1213 | with UNIX tradition it has a misleading name. It does not necessarily |
|
1214 | 1214 | kill the child unless you send the right signal. """ |
|
1215 | 1215 | |
|
1216 | 1216 | # Same as os.kill, but the pid is given for you. |
|
1217 | 1217 | if self.isalive(): |
|
1218 | 1218 | os.kill(self.pid, sig) |
|
1219 | 1219 | |
|
1220 | 1220 | def compile_pattern_list(self, patterns): |
|
1221 | 1221 | |
|
1222 | 1222 | """This compiles a pattern-string or a list of pattern-strings. |
|
1223 | 1223 | Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or a list of |
|
1224 | 1224 | those. Patterns may also be None which results in an empty list (you |
|
1225 | 1225 | might do this if waiting for an EOF or TIMEOUT condition without |
|
1226 | 1226 | expecting any pattern). |
|
1227 | 1227 | |
|
1228 | 1228 | This is used by expect() when calling expect_list(). Thus expect() is |
|
1229 | 1229 | nothing more than:: |
|
1230 | 1230 | |
|
1231 | 1231 | cpl = self.compile_pattern_list(pl) |
|
1232 | 1232 | return self.expect_list(cpl, timeout) |
|
1233 | 1233 | |
|
1234 | 1234 | If you are using expect() within a loop it may be more |
|
1235 | 1235 | efficient to compile the patterns first and then call expect_list(). |
|
1236 | 1236 | This avoid calls in a loop to compile_pattern_list():: |
|
1237 | 1237 | |
|
1238 | 1238 | cpl = self.compile_pattern_list(my_pattern) |
|
1239 | 1239 | while some_condition: |
|
1240 | 1240 | ... |
|
1241 | 1241 | i = self.expect_list(clp, timeout) |
|
1242 | 1242 | ... |
|
1243 | 1243 | """ |
|
1244 | 1244 | |
|
1245 | 1245 | if patterns is None: |
|
1246 | 1246 | return [] |
|
1247 | 1247 | if not isinstance(patterns, list): |
|
1248 | 1248 | patterns = [patterns] |
|
1249 | 1249 | |
|
1250 | 1250 | compile_flags = re.DOTALL # Allow dot to match \n |
|
1251 | 1251 | if self.ignorecase: |
|
1252 | 1252 | compile_flags = compile_flags | re.IGNORECASE |
|
1253 | 1253 | compiled_pattern_list = [] |
|
1254 | 1254 | for p in patterns: |
|
1255 | 1255 | if isinstance(p, (bytes, unicode)): |
|
1256 | 1256 | p = self._cast_buffer_type(p) |
|
1257 | 1257 | compiled_pattern_list.append(re.compile(p, compile_flags)) |
|
1258 | 1258 | elif p is EOF: |
|
1259 | 1259 | compiled_pattern_list.append(EOF) |
|
1260 | 1260 | elif p is TIMEOUT: |
|
1261 | 1261 | compiled_pattern_list.append(TIMEOUT) |
|
1262 | 1262 | elif type(p) is re_type: |
|
1263 | 1263 | p = self._prepare_regex_pattern(p) |
|
1264 | 1264 | compiled_pattern_list.append(p) |
|
1265 | 1265 | else: |
|
1266 | 1266 | raise TypeError ('Argument must be one of StringTypes, EOF, TIMEOUT, SRE_Pattern, or a list of those type. %s' % str(type(p))) |
|
1267 | 1267 | |
|
1268 | 1268 | return compiled_pattern_list |
|
1269 | 1269 | |
|
1270 | 1270 | def _prepare_regex_pattern(self, p): |
|
1271 | 1271 | "Recompile unicode regexes as bytes regexes. Overridden in subclass." |
|
1272 | 1272 | if isinstance(p.pattern, unicode): |
|
1273 | 1273 | p = re.compile(p.pattern.encode('utf-8'), p.flags &~ re.UNICODE) |
|
1274 | 1274 | return p |
|
1275 | 1275 | |
|
1276 | 1276 | def expect(self, pattern, timeout = -1, searchwindowsize=-1): |
|
1277 | 1277 | |
|
1278 | 1278 | """This seeks through the stream until a pattern is matched. The |
|
1279 | 1279 | pattern is overloaded and may take several types. The pattern can be a |
|
1280 | 1280 | StringType, EOF, a compiled re, or a list of any of those types. |
|
1281 | 1281 | Strings will be compiled to re types. This returns the index into the |
|
1282 | 1282 | pattern list. If the pattern was not a list this returns index 0 on a |
|
1283 | 1283 | successful match. This may raise exceptions for EOF or TIMEOUT. To |
|
1284 | 1284 | avoid the EOF or TIMEOUT exceptions add EOF or TIMEOUT to the pattern |
|
1285 | 1285 | list. That will cause expect to match an EOF or TIMEOUT condition |
|
1286 | 1286 | instead of raising an exception. |
|
1287 | 1287 | |
|
1288 | 1288 | If you pass a list of patterns and more than one matches, the first match |
|
1289 | 1289 | in the stream is chosen. If more than one pattern matches at that point, |
|
1290 | 1290 | the leftmost in the pattern list is chosen. For example:: |
|
1291 | 1291 | |
|
1292 | 1292 | # the input is 'foobar' |
|
1293 | 1293 | index = p.expect (['bar', 'foo', 'foobar']) |
|
1294 | 1294 | # returns 1 ('foo') even though 'foobar' is a "better" match |
|
1295 | 1295 | |
|
1296 | 1296 | Please note, however, that buffering can affect this behavior, since |
|
1297 | 1297 | input arrives in unpredictable chunks. For example:: |
|
1298 | 1298 | |
|
1299 | 1299 | # the input is 'foobar' |
|
1300 | 1300 | index = p.expect (['foobar', 'foo']) |
|
1301 | 1301 | # returns 0 ('foobar') if all input is available at once, |
|
1302 | 1302 | # but returs 1 ('foo') if parts of the final 'bar' arrive late |
|
1303 | 1303 | |
|
1304 | 1304 | After a match is found the instance attributes 'before', 'after' and |
|
1305 | 1305 | 'match' will be set. You can see all the data read before the match in |
|
1306 | 1306 | 'before'. You can see the data that was matched in 'after'. The |
|
1307 | 1307 | re.MatchObject used in the re match will be in 'match'. If an error |
|
1308 | 1308 | occurred then 'before' will be set to all the data read so far and |
|
1309 | 1309 | 'after' and 'match' will be None. |
|
1310 | 1310 | |
|
1311 | 1311 | If timeout is -1 then timeout will be set to the self.timeout value. |
|
1312 | 1312 | |
|
1313 | 1313 | A list entry may be EOF or TIMEOUT instead of a string. This will |
|
1314 | 1314 | catch these exceptions and return the index of the list entry instead |
|
1315 | 1315 | of raising the exception. The attribute 'after' will be set to the |
|
1316 | 1316 | exception type. The attribute 'match' will be None. This allows you to |
|
1317 | 1317 | write code like this:: |
|
1318 | 1318 | |
|
1319 | 1319 | index = p.expect (['good', 'bad', pexpect.EOF, pexpect.TIMEOUT]) |
|
1320 | 1320 | if index == 0: |
|
1321 | 1321 | do_something() |
|
1322 | 1322 | elif index == 1: |
|
1323 | 1323 | do_something_else() |
|
1324 | 1324 | elif index == 2: |
|
1325 | 1325 | do_some_other_thing() |
|
1326 | 1326 | elif index == 3: |
|
1327 | 1327 | do_something_completely_different() |
|
1328 | 1328 | |
|
1329 | 1329 | instead of code like this:: |
|
1330 | 1330 | |
|
1331 | 1331 | try: |
|
1332 | 1332 | index = p.expect (['good', 'bad']) |
|
1333 | 1333 | if index == 0: |
|
1334 | 1334 | do_something() |
|
1335 | 1335 | elif index == 1: |
|
1336 | 1336 | do_something_else() |
|
1337 | 1337 | except EOF: |
|
1338 | 1338 | do_some_other_thing() |
|
1339 | 1339 | except TIMEOUT: |
|
1340 | 1340 | do_something_completely_different() |
|
1341 | 1341 | |
|
1342 | 1342 | These two forms are equivalent. It all depends on what you want. You |
|
1343 | 1343 | can also just expect the EOF if you are waiting for all output of a |
|
1344 | 1344 | child to finish. For example:: |
|
1345 | 1345 | |
|
1346 | 1346 | p = pexpect.spawn('/bin/ls') |
|
1347 | 1347 | p.expect (pexpect.EOF) |
|
1348 | 1348 | print p.before |
|
1349 | 1349 | |
|
1350 | 1350 | If you are trying to optimize for speed then see expect_list(). |
|
1351 | 1351 | """ |
|
1352 | 1352 | |
|
1353 | 1353 | compiled_pattern_list = self.compile_pattern_list(pattern) |
|
1354 | 1354 | return self.expect_list(compiled_pattern_list, timeout, searchwindowsize) |
|
1355 | 1355 | |
|
1356 | 1356 | def expect_list(self, pattern_list, timeout = -1, searchwindowsize = -1): |
|
1357 | 1357 | |
|
1358 | 1358 | """This takes a list of compiled regular expressions and returns the |
|
1359 | 1359 | index into the pattern_list that matched the child output. The list may |
|
1360 | 1360 | also contain EOF or TIMEOUT (which are not compiled regular |
|
1361 | 1361 | expressions). This method is similar to the expect() method except that |
|
1362 | 1362 | expect_list() does not recompile the pattern list on every call. This |
|
1363 | 1363 | may help if you are trying to optimize for speed, otherwise just use |
|
1364 | 1364 | the expect() method. This is called by expect(). If timeout==-1 then |
|
1365 | 1365 | the self.timeout value is used. If searchwindowsize==-1 then the |
|
1366 | 1366 | self.searchwindowsize value is used. """ |
|
1367 | 1367 | |
|
1368 | 1368 | return self.expect_loop(searcher_re(pattern_list), timeout, searchwindowsize) |
|
1369 | 1369 | |
|
1370 | 1370 | def expect_exact(self, pattern_list, timeout = -1, searchwindowsize = -1): |
|
1371 | 1371 | |
|
1372 | 1372 | """This is similar to expect(), but uses plain string matching instead |
|
1373 | 1373 | of compiled regular expressions in 'pattern_list'. The 'pattern_list' |
|
1374 | 1374 | may be a string; a list or other sequence of strings; or TIMEOUT and |
|
1375 | 1375 | EOF. |
|
1376 | 1376 | |
|
1377 | 1377 | This call might be faster than expect() for two reasons: string |
|
1378 | 1378 | searching is faster than RE matching and it is possible to limit the |
|
1379 | 1379 | search to just the end of the input buffer. |
|
1380 | 1380 | |
|
1381 | 1381 | This method is also useful when you don't want to have to worry about |
|
1382 | 1382 | escaping regular expression characters that you want to match.""" |
|
1383 | 1383 | |
|
1384 | 1384 | if isinstance(pattern_list, (bytes, unicode)) or pattern_list in (TIMEOUT, EOF): |
|
1385 | 1385 | pattern_list = [pattern_list] |
|
1386 | 1386 | return self.expect_loop(searcher_string(pattern_list), timeout, searchwindowsize) |
|
1387 | 1387 | |
|
1388 | 1388 | def expect_loop(self, searcher, timeout = -1, searchwindowsize = -1): |
|
1389 | 1389 | |
|
1390 | 1390 | """This is the common loop used inside expect. The 'searcher' should be |
|
1391 | 1391 | an instance of searcher_re or searcher_string, which describes how and what |
|
1392 | 1392 | to search for in the input. |
|
1393 | 1393 | |
|
1394 | 1394 | See expect() for other arguments, return value and exceptions. """ |
|
1395 | 1395 | |
|
1396 | 1396 | self.searcher = searcher |
|
1397 | 1397 | |
|
1398 | 1398 | if timeout == -1: |
|
1399 | 1399 | timeout = self.timeout |
|
1400 | 1400 | if timeout is not None: |
|
1401 | 1401 | end_time = time.time() + timeout |
|
1402 | 1402 | if searchwindowsize == -1: |
|
1403 | 1403 | searchwindowsize = self.searchwindowsize |
|
1404 | 1404 | |
|
1405 | 1405 | try: |
|
1406 | 1406 | incoming = self.buffer |
|
1407 | 1407 | freshlen = len(incoming) |
|
1408 | 1408 | while True: # Keep reading until exception or return. |
|
1409 | 1409 | index = searcher.search(incoming, freshlen, searchwindowsize) |
|
1410 | 1410 | if index >= 0: |
|
1411 | 1411 | self.buffer = incoming[searcher.end : ] |
|
1412 | 1412 | self.before = incoming[ : searcher.start] |
|
1413 | 1413 | self.after = incoming[searcher.start : searcher.end] |
|
1414 | 1414 | self.match = searcher.match |
|
1415 | 1415 | self.match_index = index |
|
1416 | 1416 | return self.match_index |
|
1417 | 1417 | # No match at this point |
|
1418 | 1418 | if timeout is not None and timeout < 0: |
|
1419 | 1419 | raise TIMEOUT ('Timeout exceeded in expect_any().') |
|
1420 | 1420 | # Still have time left, so read more data |
|
1421 | 1421 | c = self.read_nonblocking (self.maxread, timeout) |
|
1422 | 1422 | freshlen = len(c) |
|
1423 | 1423 | time.sleep (0.0001) |
|
1424 | 1424 | incoming = incoming + c |
|
1425 | 1425 | if timeout is not None: |
|
1426 | 1426 | timeout = end_time - time.time() |
|
1427 | 1427 | except EOF as e: |
|
1428 | 1428 | self.buffer = self._empty_buffer |
|
1429 | 1429 | self.before = incoming |
|
1430 | 1430 | self.after = EOF |
|
1431 | 1431 | index = searcher.eof_index |
|
1432 | 1432 | if index >= 0: |
|
1433 | 1433 | self.match = EOF |
|
1434 | 1434 | self.match_index = index |
|
1435 | 1435 | return self.match_index |
|
1436 | 1436 | else: |
|
1437 | 1437 | self.match = None |
|
1438 | 1438 | self.match_index = None |
|
1439 | 1439 | raise EOF (str(e) + '\n' + str(self)) |
|
1440 | 1440 | except TIMEOUT as e: |
|
1441 | 1441 | self.buffer = incoming |
|
1442 | 1442 | self.before = incoming |
|
1443 | 1443 | self.after = TIMEOUT |
|
1444 | 1444 | index = searcher.timeout_index |
|
1445 | 1445 | if index >= 0: |
|
1446 | 1446 | self.match = TIMEOUT |
|
1447 | 1447 | self.match_index = index |
|
1448 | 1448 | return self.match_index |
|
1449 | 1449 | else: |
|
1450 | 1450 | self.match = None |
|
1451 | 1451 | self.match_index = None |
|
1452 | 1452 | raise TIMEOUT (str(e) + '\n' + str(self)) |
|
1453 | 1453 | except: |
|
1454 | 1454 | self.before = incoming |
|
1455 | 1455 | self.after = None |
|
1456 | 1456 | self.match = None |
|
1457 | 1457 | self.match_index = None |
|
1458 | 1458 | raise |
|
1459 | 1459 | |
|
1460 | 1460 | def getwinsize(self): |
|
1461 | 1461 | |
|
1462 | 1462 | """This returns the terminal window size of the child tty. The return |
|
1463 | 1463 | value is a tuple of (rows, cols). """ |
|
1464 | 1464 | |
|
1465 | 1465 | TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912L) |
|
1466 | 1466 | s = struct.pack('HHHH', 0, 0, 0, 0) |
|
1467 | 1467 | x = fcntl.ioctl(self.fileno(), TIOCGWINSZ, s) |
|
1468 | 1468 | return struct.unpack('HHHH', x)[0:2] |
|
1469 | 1469 | |
|
1470 | 1470 | def setwinsize(self, r, c): |
|
1471 | 1471 | |
|
1472 | 1472 | """This sets the terminal window size of the child tty. This will cause |
|
1473 | 1473 | a SIGWINCH signal to be sent to the child. This does not change the |
|
1474 | 1474 | physical window size. It changes the size reported to TTY-aware |
|
1475 | 1475 | applications like vi or curses -- applications that respond to the |
|
1476 | 1476 | SIGWINCH signal. """ |
|
1477 | 1477 | |
|
1478 | 1478 | # Check for buggy platforms. Some Python versions on some platforms |
|
1479 | 1479 | # (notably OSF1 Alpha and RedHat 7.1) truncate the value for |
|
1480 | 1480 | # termios.TIOCSWINSZ. It is not clear why this happens. |
|
1481 | 1481 | # These platforms don't seem to handle the signed int very well; |
|
1482 | 1482 | # yet other platforms like OpenBSD have a large negative value for |
|
1483 | 1483 | # TIOCSWINSZ and they don't have a truncate problem. |
|
1484 | 1484 | # Newer versions of Linux have totally different values for TIOCSWINSZ. |
|
1485 | 1485 | # Note that this fix is a hack. |
|
1486 | 1486 | TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561) |
|
1487 | 1487 | if TIOCSWINSZ == 2148037735L: # L is not required in Python >= 2.2. |
|
1488 | 1488 | TIOCSWINSZ = -2146929561 # Same bits, but with sign. |
|
1489 | 1489 | # Note, assume ws_xpixel and ws_ypixel are zero. |
|
1490 | 1490 | s = struct.pack('HHHH', r, c, 0, 0) |
|
1491 | 1491 | fcntl.ioctl(self.fileno(), TIOCSWINSZ, s) |
|
1492 | 1492 | |
|
1493 | 1493 | def interact(self, escape_character = b'\x1d', input_filter = None, output_filter = None): |
|
1494 | 1494 | |
|
1495 | 1495 | """This gives control of the child process to the interactive user (the |
|
1496 | 1496 | human at the keyboard). Keystrokes are sent to the child process, and |
|
1497 | 1497 | the stdout and stderr output of the child process is printed. This |
|
1498 | 1498 | simply echos the child stdout and child stderr to the real stdout and |
|
1499 | 1499 | it echos the real stdin to the child stdin. When the user types the |
|
1500 | 1500 | escape_character this method will stop. The default for |
|
1501 | 1501 | escape_character is ^]. This should not be confused with ASCII 27 -- |
|
1502 | 1502 | the ESC character. ASCII 29 was chosen for historical merit because |
|
1503 | 1503 | this is the character used by 'telnet' as the escape character. The |
|
1504 | 1504 | escape_character will not be sent to the child process. |
|
1505 | 1505 | |
|
1506 | 1506 | You may pass in optional input and output filter functions. These |
|
1507 | 1507 | functions should take a string and return a string. The output_filter |
|
1508 | 1508 | will be passed all the output from the child process. The input_filter |
|
1509 | 1509 | will be passed all the keyboard input from the user. The input_filter |
|
1510 | 1510 | is run BEFORE the check for the escape_character. |
|
1511 | 1511 | |
|
1512 | 1512 | Note that if you change the window size of the parent the SIGWINCH |
|
1513 | 1513 | signal will not be passed through to the child. If you want the child |
|
1514 | 1514 | window size to change when the parent's window size changes then do |
|
1515 | 1515 | something like the following example:: |
|
1516 | 1516 | |
|
1517 | 1517 | import pexpect, struct, fcntl, termios, signal, sys |
|
1518 | 1518 | def sigwinch_passthrough (sig, data): |
|
1519 | 1519 | s = struct.pack("HHHH", 0, 0, 0, 0) |
|
1520 | 1520 | a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ , s)) |
|
1521 | 1521 | global p |
|
1522 | 1522 | p.setwinsize(a[0],a[1]) |
|
1523 | 1523 | p = pexpect.spawn('/bin/bash') # Note this is global and used in sigwinch_passthrough. |
|
1524 | 1524 | signal.signal(signal.SIGWINCH, sigwinch_passthrough) |
|
1525 | 1525 | p.interact() |
|
1526 | 1526 | """ |
|
1527 | 1527 | |
|
1528 | 1528 | # Flush the buffer. |
|
1529 | 1529 | if PY3: self.stdout.write(_cast_unicode(self.buffer, self.encoding)) |
|
1530 | 1530 | else: self.stdout.write(self.buffer) |
|
1531 | 1531 | self.stdout.flush() |
|
1532 | 1532 | self.buffer = self._empty_buffer |
|
1533 | 1533 | mode = tty.tcgetattr(self.STDIN_FILENO) |
|
1534 | 1534 | tty.setraw(self.STDIN_FILENO) |
|
1535 | 1535 | try: |
|
1536 | 1536 | self.__interact_copy(escape_character, input_filter, output_filter) |
|
1537 | 1537 | finally: |
|
1538 | 1538 | tty.tcsetattr(self.STDIN_FILENO, tty.TCSAFLUSH, mode) |
|
1539 | 1539 | |
|
1540 | 1540 | def __interact_writen(self, fd, data): |
|
1541 | 1541 | |
|
1542 | 1542 | """This is used by the interact() method. |
|
1543 | 1543 | """ |
|
1544 | 1544 | |
|
1545 | 1545 | while data != b'' and self.isalive(): |
|
1546 | 1546 | n = os.write(fd, data) |
|
1547 | 1547 | data = data[n:] |
|
1548 | 1548 | |
|
1549 | 1549 | def __interact_read(self, fd): |
|
1550 | 1550 | |
|
1551 | 1551 | """This is used by the interact() method. |
|
1552 | 1552 | """ |
|
1553 | 1553 | |
|
1554 | 1554 | return os.read(fd, 1000) |
|
1555 | 1555 | |
|
1556 | 1556 | def __interact_copy(self, escape_character = None, input_filter = None, output_filter = None): |
|
1557 | 1557 | |
|
1558 | 1558 | """This is used by the interact() method. |
|
1559 | 1559 | """ |
|
1560 | 1560 | |
|
1561 | 1561 | while self.isalive(): |
|
1562 | 1562 | r,w,e = self.__select([self.child_fd, self.STDIN_FILENO], [], []) |
|
1563 | 1563 | if self.child_fd in r: |
|
1564 | 1564 | data = self.__interact_read(self.child_fd) |
|
1565 | 1565 | if output_filter: data = output_filter(data) |
|
1566 | 1566 | if self.logfile is not None: |
|
1567 | 1567 | self.logfile.write (data) |
|
1568 | 1568 | self.logfile.flush() |
|
1569 | 1569 | os.write(self.STDOUT_FILENO, data) |
|
1570 | 1570 | if self.STDIN_FILENO in r: |
|
1571 | 1571 | data = self.__interact_read(self.STDIN_FILENO) |
|
1572 | 1572 | if input_filter: data = input_filter(data) |
|
1573 | 1573 | i = data.rfind(escape_character) |
|
1574 | 1574 | if i != -1: |
|
1575 | 1575 | data = data[:i] |
|
1576 | 1576 | self.__interact_writen(self.child_fd, data) |
|
1577 | 1577 | break |
|
1578 | 1578 | self.__interact_writen(self.child_fd, data) |
|
1579 | 1579 | |
|
1580 | 1580 | def __select (self, iwtd, owtd, ewtd, timeout=None): |
|
1581 | 1581 | |
|
1582 | 1582 | """This is a wrapper around select.select() that ignores signals. If |
|
1583 | 1583 | select.select raises a select.error exception and errno is an EINTR |
|
1584 | 1584 | error then it is ignored. Mainly this is used to ignore sigwinch |
|
1585 | 1585 | (terminal resize). """ |
|
1586 | 1586 | |
|
1587 | 1587 | # if select() is interrupted by a signal (errno==EINTR) then |
|
1588 | 1588 | # we loop back and enter the select() again. |
|
1589 | 1589 | if timeout is not None: |
|
1590 | 1590 | end_time = time.time() + timeout |
|
1591 | 1591 | while True: |
|
1592 | 1592 | try: |
|
1593 | 1593 | return select.select (iwtd, owtd, ewtd, timeout) |
|
1594 | 1594 | except select.error as e: |
|
1595 | 1595 | if e.args[0] == errno.EINTR: |
|
1596 | 1596 | # if we loop back we have to subtract the amount of time we already waited. |
|
1597 | 1597 | if timeout is not None: |
|
1598 | 1598 | timeout = end_time - time.time() |
|
1599 | 1599 | if timeout < 0: |
|
1600 | 1600 | return ([],[],[]) |
|
1601 | 1601 | else: # something else caused the select.error, so this really is an exception |
|
1602 | 1602 | raise |
|
1603 | 1603 | |
|
1604 | 1604 | class spawn(spawnb): |
|
1605 | 1605 | """This is the main class interface for Pexpect. Use this class to start |
|
1606 | 1606 | and control child applications.""" |
|
1607 | 1607 | |
|
1608 | 1608 | _buffer_type = unicode |
|
1609 | 1609 | def _cast_buffer_type(self, s): |
|
1610 | 1610 | return _cast_unicode(s, self.encoding) |
|
1611 | 1611 | _empty_buffer = u'' |
|
1612 | 1612 | _pty_newline = u'\r\n' |
|
1613 | 1613 | |
|
1614 | 1614 | def __init__(self, command, args=[], timeout=30, maxread=2000, searchwindowsize=None, |
|
1615 | 1615 | logfile=None, cwd=None, env=None, encoding='utf-8'): |
|
1616 | 1616 | super(spawn, self).__init__(command, args, timeout=timeout, maxread=maxread, |
|
1617 | 1617 | searchwindowsize=searchwindowsize, logfile=logfile, cwd=cwd, env=env) |
|
1618 | 1618 | self.encoding = encoding |
|
1619 | 1619 | |
|
1620 | 1620 | def _prepare_regex_pattern(self, p): |
|
1621 | 1621 | "Recompile bytes regexes as unicode regexes." |
|
1622 | 1622 | if isinstance(p.pattern, bytes): |
|
1623 | 1623 | p = re.compile(p.pattern.decode(self.encoding), p.flags) |
|
1624 | 1624 | return p |
|
1625 | 1625 | |
|
1626 | 1626 | def read_nonblocking(self, size=1, timeout=-1): |
|
1627 | 1627 | return super(spawn, self).read_nonblocking(size=size, timeout=timeout)\ |
|
1628 | 1628 | .decode(self.encoding) |
|
1629 | 1629 | |
|
1630 | 1630 | read_nonblocking.__doc__ = spawnb.read_nonblocking.__doc__ |
|
1631 | 1631 | |
|
1632 | 1632 | |
|
1633 | 1633 | ############################################################################## |
|
1634 | 1634 | # End of spawn class |
|
1635 | 1635 | ############################################################################## |
|
1636 | 1636 | |
|
1637 | 1637 | class searcher_string (object): |
|
1638 | 1638 | |
|
1639 | 1639 | """This is a plain string search helper for the spawn.expect_any() method. |
|
1640 | 1640 | This helper class is for speed. For more powerful regex patterns |
|
1641 | 1641 | see the helper class, searcher_re. |
|
1642 | 1642 | |
|
1643 | 1643 | Attributes: |
|
1644 | 1644 | |
|
1645 | 1645 | eof_index - index of EOF, or -1 |
|
1646 | 1646 | timeout_index - index of TIMEOUT, or -1 |
|
1647 | 1647 | |
|
1648 | 1648 | After a successful match by the search() method the following attributes |
|
1649 | 1649 | are available: |
|
1650 | 1650 | |
|
1651 | 1651 | start - index into the buffer, first byte of match |
|
1652 | 1652 | end - index into the buffer, first byte after match |
|
1653 | 1653 | match - the matching string itself |
|
1654 | 1654 | |
|
1655 | 1655 | """ |
|
1656 | 1656 | |
|
1657 | 1657 | def __init__(self, strings): |
|
1658 | 1658 | |
|
1659 | 1659 | """This creates an instance of searcher_string. This argument 'strings' |
|
1660 | 1660 | may be a list; a sequence of strings; or the EOF or TIMEOUT types. """ |
|
1661 | 1661 | |
|
1662 | 1662 | self.eof_index = -1 |
|
1663 | 1663 | self.timeout_index = -1 |
|
1664 | 1664 | self._strings = [] |
|
1665 | 1665 | for n, s in enumerate(strings): |
|
1666 | 1666 | if s is EOF: |
|
1667 | 1667 | self.eof_index = n |
|
1668 | 1668 | continue |
|
1669 | 1669 | if s is TIMEOUT: |
|
1670 | 1670 | self.timeout_index = n |
|
1671 | 1671 | continue |
|
1672 | 1672 | self._strings.append((n, s)) |
|
1673 | 1673 | |
|
1674 | 1674 | def __str__(self): |
|
1675 | 1675 | |
|
1676 | 1676 | """This returns a human-readable string that represents the state of |
|
1677 | 1677 | the object.""" |
|
1678 | 1678 | |
|
1679 | 1679 | ss = [ (ns[0],' %d: "%s"' % ns) for ns in self._strings ] |
|
1680 | 1680 | ss.append((-1,'searcher_string:')) |
|
1681 | 1681 | if self.eof_index >= 0: |
|
1682 | 1682 | ss.append ((self.eof_index,' %d: EOF' % self.eof_index)) |
|
1683 | 1683 | if self.timeout_index >= 0: |
|
1684 | 1684 | ss.append ((self.timeout_index,' %d: TIMEOUT' % self.timeout_index)) |
|
1685 | 1685 | ss.sort() |
|
1686 | 1686 | return '\n'.join(a[1] for a in ss) |
|
1687 | 1687 | |
|
1688 | 1688 | def search(self, buffer, freshlen, searchwindowsize=None): |
|
1689 | 1689 | |
|
1690 | 1690 | """This searches 'buffer' for the first occurence of one of the search |
|
1691 | 1691 | strings. 'freshlen' must indicate the number of bytes at the end of |
|
1692 | 1692 | 'buffer' which have not been searched before. It helps to avoid |
|
1693 | 1693 | searching the same, possibly big, buffer over and over again. |
|
1694 | 1694 | |
|
1695 | 1695 | See class spawn for the 'searchwindowsize' argument. |
|
1696 | 1696 | |
|
1697 | 1697 | If there is a match this returns the index of that string, and sets |
|
1698 | 1698 | 'start', 'end' and 'match'. Otherwise, this returns -1. """ |
|
1699 | 1699 | |
|
1700 | 1700 | absurd_match = len(buffer) |
|
1701 | 1701 | first_match = absurd_match |
|
1702 | 1702 | |
|
1703 | 1703 | # 'freshlen' helps a lot here. Further optimizations could |
|
1704 | 1704 | # possibly include: |
|
1705 | 1705 | # |
|
1706 | 1706 | # using something like the Boyer-Moore Fast String Searching |
|
1707 | 1707 | # Algorithm; pre-compiling the search through a list of |
|
1708 | 1708 | # strings into something that can scan the input once to |
|
1709 | 1709 | # search for all N strings; realize that if we search for |
|
1710 | 1710 | # ['bar', 'baz'] and the input is '...foo' we need not bother |
|
1711 | 1711 | # rescanning until we've read three more bytes. |
|
1712 | 1712 | # |
|
1713 | 1713 | # Sadly, I don't know enough about this interesting topic. /grahn |
|
1714 | 1714 | |
|
1715 | 1715 | for index, s in self._strings: |
|
1716 | 1716 | if searchwindowsize is None: |
|
1717 | 1717 | # the match, if any, can only be in the fresh data, |
|
1718 | 1718 | # or at the very end of the old data |
|
1719 | 1719 | offset = -(freshlen+len(s)) |
|
1720 | 1720 | else: |
|
1721 | 1721 | # better obey searchwindowsize |
|
1722 | 1722 | offset = -searchwindowsize |
|
1723 | 1723 | n = buffer.find(s, offset) |
|
1724 | 1724 | if n >= 0 and n < first_match: |
|
1725 | 1725 | first_match = n |
|
1726 | 1726 | best_index, best_match = index, s |
|
1727 | 1727 | if first_match == absurd_match: |
|
1728 | 1728 | return -1 |
|
1729 | 1729 | self.match = best_match |
|
1730 | 1730 | self.start = first_match |
|
1731 | 1731 | self.end = self.start + len(self.match) |
|
1732 | 1732 | return best_index |
|
1733 | 1733 | |
|
1734 | 1734 | class searcher_re (object): |
|
1735 | 1735 | |
|
1736 | 1736 | """This is regular expression string search helper for the |
|
1737 | 1737 | spawn.expect_any() method. This helper class is for powerful |
|
1738 | 1738 | pattern matching. For speed, see the helper class, searcher_string. |
|
1739 | 1739 | |
|
1740 | 1740 | Attributes: |
|
1741 | 1741 | |
|
1742 | 1742 | eof_index - index of EOF, or -1 |
|
1743 | 1743 | timeout_index - index of TIMEOUT, or -1 |
|
1744 | 1744 | |
|
1745 | 1745 | After a successful match by the search() method the following attributes |
|
1746 | 1746 | are available: |
|
1747 | 1747 | |
|
1748 | 1748 | start - index into the buffer, first byte of match |
|
1749 | 1749 | end - index into the buffer, first byte after match |
|
1750 | 1750 | match - the re.match object returned by a succesful re.search |
|
1751 | 1751 | |
|
1752 | 1752 | """ |
|
1753 | 1753 | |
|
1754 | 1754 | def __init__(self, patterns): |
|
1755 | 1755 | |
|
1756 | 1756 | """This creates an instance that searches for 'patterns' Where |
|
1757 | 1757 | 'patterns' may be a list or other sequence of compiled regular |
|
1758 | 1758 | expressions, or the EOF or TIMEOUT types.""" |
|
1759 | 1759 | |
|
1760 | 1760 | self.eof_index = -1 |
|
1761 | 1761 | self.timeout_index = -1 |
|
1762 | 1762 | self._searches = [] |
|
1763 | 1763 | for n, s in enumerate(patterns): |
|
1764 | 1764 | if s is EOF: |
|
1765 | 1765 | self.eof_index = n |
|
1766 | 1766 | continue |
|
1767 | 1767 | if s is TIMEOUT: |
|
1768 | 1768 | self.timeout_index = n |
|
1769 | 1769 | continue |
|
1770 | 1770 | self._searches.append((n, s)) |
|
1771 | 1771 | |
|
1772 | 1772 | def __str__(self): |
|
1773 | 1773 | |
|
1774 | 1774 | """This returns a human-readable string that represents the state of |
|
1775 | 1775 | the object.""" |
|
1776 | 1776 | |
|
1777 | 1777 | ss = [ (n,' %d: re.compile("%s")' % (n,str(s.pattern))) for n,s in self._searches] |
|
1778 | 1778 | ss.append((-1,'searcher_re:')) |
|
1779 | 1779 | if self.eof_index >= 0: |
|
1780 | 1780 | ss.append ((self.eof_index,' %d: EOF' % self.eof_index)) |
|
1781 | 1781 | if self.timeout_index >= 0: |
|
1782 | 1782 | ss.append ((self.timeout_index,' %d: TIMEOUT' % self.timeout_index)) |
|
1783 | 1783 | ss.sort() |
|
1784 | 1784 | return '\n'.join(a[1] for a in ss) |
|
1785 | 1785 | |
|
1786 | 1786 | def search(self, buffer, freshlen, searchwindowsize=None): |
|
1787 | 1787 | |
|
1788 | 1788 | """This searches 'buffer' for the first occurence of one of the regular |
|
1789 | 1789 | expressions. 'freshlen' must indicate the number of bytes at the end of |
|
1790 | 1790 | 'buffer' which have not been searched before. |
|
1791 | 1791 | |
|
1792 | 1792 | See class spawn for the 'searchwindowsize' argument. |
|
1793 | 1793 | |
|
1794 | 1794 | If there is a match this returns the index of that string, and sets |
|
1795 | 1795 | 'start', 'end' and 'match'. Otherwise, returns -1.""" |
|
1796 | 1796 | |
|
1797 | 1797 | absurd_match = len(buffer) |
|
1798 | 1798 | first_match = absurd_match |
|
1799 | 1799 | # 'freshlen' doesn't help here -- we cannot predict the |
|
1800 | 1800 | # length of a match, and the re module provides no help. |
|
1801 | 1801 | if searchwindowsize is None: |
|
1802 | 1802 | searchstart = 0 |
|
1803 | 1803 | else: |
|
1804 | 1804 | searchstart = max(0, len(buffer)-searchwindowsize) |
|
1805 | 1805 | for index, s in self._searches: |
|
1806 | 1806 | match = s.search(buffer, searchstart) |
|
1807 | 1807 | if match is None: |
|
1808 | 1808 | continue |
|
1809 | 1809 | n = match.start() |
|
1810 | 1810 | if n < first_match: |
|
1811 | 1811 | first_match = n |
|
1812 | 1812 | the_match = match |
|
1813 | 1813 | best_index = index |
|
1814 | 1814 | if first_match == absurd_match: |
|
1815 | 1815 | return -1 |
|
1816 | 1816 | self.start = first_match |
|
1817 | 1817 | self.match = the_match |
|
1818 | 1818 | self.end = self.match.end() |
|
1819 | 1819 | return best_index |
|
1820 | 1820 | |
|
1821 | 1821 | def which (filename): |
|
1822 | 1822 | |
|
1823 | 1823 | """This takes a given filename; tries to find it in the environment path; |
|
1824 | 1824 | then checks if it is executable. This returns the full path to the filename |
|
1825 | 1825 | if found and executable. Otherwise this returns None.""" |
|
1826 | 1826 | |
|
1827 | 1827 | # Special case where filename already contains a path. |
|
1828 | 1828 | if os.path.dirname(filename) != '': |
|
1829 | 1829 | if os.access (filename, os.X_OK): |
|
1830 | 1830 | return filename |
|
1831 | 1831 | |
|
1832 | 1832 | if not os.environ.has_key('PATH') or os.environ['PATH'] == '': |
|
1833 | 1833 | p = os.defpath |
|
1834 | 1834 | else: |
|
1835 | 1835 | p = os.environ['PATH'] |
|
1836 | 1836 | |
|
1837 | 1837 | pathlist = p.split(os.pathsep) |
|
1838 | 1838 | |
|
1839 | 1839 | for path in pathlist: |
|
1840 | 1840 | f = os.path.join(path, filename) |
|
1841 | 1841 | if os.access(f, os.X_OK): |
|
1842 | 1842 | return f |
|
1843 | 1843 | return None |
|
1844 | 1844 | |
|
1845 | 1845 | def split_command_line(command_line): |
|
1846 | 1846 | |
|
1847 | 1847 | """This splits a command line into a list of arguments. It splits arguments |
|
1848 | 1848 | on spaces, but handles embedded quotes, doublequotes, and escaped |
|
1849 | 1849 | characters. It's impossible to do this with a regular expression, so I |
|
1850 | 1850 | wrote a little state machine to parse the command line. """ |
|
1851 | 1851 | |
|
1852 | 1852 | arg_list = [] |
|
1853 | 1853 | arg = '' |
|
1854 | 1854 | |
|
1855 | 1855 | # Constants to name the states we can be in. |
|
1856 | 1856 | state_basic = 0 |
|
1857 | 1857 | state_esc = 1 |
|
1858 | 1858 | state_singlequote = 2 |
|
1859 | 1859 | state_doublequote = 3 |
|
1860 | 1860 | state_whitespace = 4 # The state of consuming whitespace between commands. |
|
1861 | 1861 | state = state_basic |
|
1862 | 1862 | |
|
1863 | 1863 | for c in command_line: |
|
1864 | 1864 | if state == state_basic or state == state_whitespace: |
|
1865 | 1865 | if c == '\\': # Escape the next character |
|
1866 | 1866 | state = state_esc |
|
1867 | 1867 | elif c == r"'": # Handle single quote |
|
1868 | 1868 | state = state_singlequote |
|
1869 | 1869 | elif c == r'"': # Handle double quote |
|
1870 | 1870 | state = state_doublequote |
|
1871 | 1871 | elif c.isspace(): |
|
1872 | 1872 | # Add arg to arg_list if we aren't in the middle of whitespace. |
|
1873 | 1873 | if state == state_whitespace: |
|
1874 | 1874 | None # Do nothing. |
|
1875 | 1875 | else: |
|
1876 | 1876 | arg_list.append(arg) |
|
1877 | 1877 | arg = '' |
|
1878 | 1878 | state = state_whitespace |
|
1879 | 1879 | else: |
|
1880 | 1880 | arg = arg + c |
|
1881 | 1881 | state = state_basic |
|
1882 | 1882 | elif state == state_esc: |
|
1883 | 1883 | arg = arg + c |
|
1884 | 1884 | state = state_basic |
|
1885 | 1885 | elif state == state_singlequote: |
|
1886 | 1886 | if c == r"'": |
|
1887 | 1887 | state = state_basic |
|
1888 | 1888 | else: |
|
1889 | 1889 | arg = arg + c |
|
1890 | 1890 | elif state == state_doublequote: |
|
1891 | 1891 | if c == r'"': |
|
1892 | 1892 | state = state_basic |
|
1893 | 1893 | else: |
|
1894 | 1894 | arg = arg + c |
|
1895 | 1895 | |
|
1896 | 1896 | if arg != '': |
|
1897 | 1897 | arg_list.append(arg) |
|
1898 | 1898 | return arg_list |
|
1899 | 1899 | |
|
1900 | 1900 | # vi:set sr et ts=4 sw=4 ft=python : |
@@ -1,484 +1,483 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Manage background (threaded) jobs conveniently from an interactive shell. |
|
3 | 3 | |
|
4 | 4 | This module provides a BackgroundJobManager class. This is the main class |
|
5 | 5 | meant for public usage, it implements an object which can create and manage |
|
6 | 6 | new background jobs. |
|
7 | 7 | |
|
8 | 8 | It also provides the actual job classes managed by these BackgroundJobManager |
|
9 | 9 | objects, see their docstrings below. |
|
10 | 10 | |
|
11 | 11 | |
|
12 | 12 | This system was inspired by discussions with B. Granger and the |
|
13 | 13 | BackgroundCommand class described in the book Python Scripting for |
|
14 | 14 | Computational Science, by H. P. Langtangen: |
|
15 | 15 | |
|
16 | 16 | http://folk.uio.no/hpl/scripting |
|
17 | 17 | |
|
18 | 18 | (although ultimately no code from this text was used, as IPython's system is a |
|
19 | 19 | separate implementation). |
|
20 | 20 | |
|
21 | 21 | An example notebook is provided in our documentation illustrating interactive |
|
22 | 22 | use of the system. |
|
23 | 23 | """ |
|
24 | 24 | |
|
25 | 25 | #***************************************************************************** |
|
26 | 26 | # Copyright (C) 2005-2006 Fernando Perez <fperez@colorado.edu> |
|
27 | 27 | # |
|
28 | 28 | # Distributed under the terms of the BSD License. The full license is in |
|
29 | 29 | # the file COPYING, distributed as part of this software. |
|
30 | 30 | #***************************************************************************** |
|
31 | 31 | |
|
32 | 32 | # Code begins |
|
33 | 33 | import sys |
|
34 | 34 | import threading |
|
35 | 35 | |
|
36 | 36 | from IPython.core.ultratb import AutoFormattedTB |
|
37 | 37 | from IPython.utils.warn import warn, error |
|
38 | 38 | |
|
39 | 39 | |
|
40 | 40 | class BackgroundJobManager(object): |
|
41 | 41 | """Class to manage a pool of backgrounded threaded jobs. |
|
42 | 42 | |
|
43 | 43 | Below, we assume that 'jobs' is a BackgroundJobManager instance. |
|
44 | 44 | |
|
45 | 45 | Usage summary (see the method docstrings for details): |
|
46 | 46 | |
|
47 | 47 | jobs.new(...) -> start a new job |
|
48 | 48 | |
|
49 | 49 | jobs() or jobs.status() -> print status summary of all jobs |
|
50 | 50 | |
|
51 | 51 | jobs[N] -> returns job number N. |
|
52 | 52 | |
|
53 | 53 | foo = jobs[N].result -> assign to variable foo the result of job N |
|
54 | 54 | |
|
55 | 55 | jobs[N].traceback() -> print the traceback of dead job N |
|
56 | 56 | |
|
57 | 57 | jobs.remove(N) -> remove (finished) job N |
|
58 | 58 | |
|
59 | 59 | jobs.flush() -> remove all finished jobs |
|
60 | 60 | |
|
61 | 61 | As a convenience feature, BackgroundJobManager instances provide the |
|
62 | 62 | utility result and traceback methods which retrieve the corresponding |
|
63 | 63 | information from the jobs list: |
|
64 | 64 | |
|
65 | 65 | jobs.result(N) <--> jobs[N].result |
|
66 | 66 | jobs.traceback(N) <--> jobs[N].traceback() |
|
67 | 67 | |
|
68 | 68 | While this appears minor, it allows you to use tab completion |
|
69 | 69 | interactively on the job manager instance. |
|
70 | 70 | """ |
|
71 | 71 | |
|
72 | 72 | def __init__(self): |
|
73 | 73 | # Lists for job management, accessed via a property to ensure they're |
|
74 | 74 | # up to date.x |
|
75 | 75 | self._running = [] |
|
76 | 76 | self._completed = [] |
|
77 | 77 | self._dead = [] |
|
78 | 78 | # A dict of all jobs, so users can easily access any of them |
|
79 | 79 | self.all = {} |
|
80 | 80 | # For reporting |
|
81 | 81 | self._comp_report = [] |
|
82 | 82 | self._dead_report = [] |
|
83 | 83 | # Store status codes locally for fast lookups |
|
84 | 84 | self._s_created = BackgroundJobBase.stat_created_c |
|
85 | 85 | self._s_running = BackgroundJobBase.stat_running_c |
|
86 | 86 | self._s_completed = BackgroundJobBase.stat_completed_c |
|
87 | 87 | self._s_dead = BackgroundJobBase.stat_dead_c |
|
88 | 88 | |
|
89 | 89 | @property |
|
90 | 90 | def running(self): |
|
91 | 91 | self._update_status() |
|
92 | 92 | return self._running |
|
93 | 93 | |
|
94 | 94 | @property |
|
95 | 95 | def dead(self): |
|
96 | 96 | self._update_status() |
|
97 | 97 | return self._dead |
|
98 | 98 | |
|
99 | 99 | @property |
|
100 | 100 | def completed(self): |
|
101 | 101 | self._update_status() |
|
102 | 102 | return self._completed |
|
103 | 103 | |
|
104 | 104 | def new(self, func_or_exp, *args, **kwargs): |
|
105 | 105 | """Add a new background job and start it in a separate thread. |
|
106 | 106 | |
|
107 | 107 | There are two types of jobs which can be created: |
|
108 | 108 | |
|
109 | 109 | 1. Jobs based on expressions which can be passed to an eval() call. |
|
110 | 110 | The expression must be given as a string. For example: |
|
111 | 111 | |
|
112 | 112 | job_manager.new('myfunc(x,y,z=1)'[,glob[,loc]]) |
|
113 | 113 | |
|
114 | 114 | The given expression is passed to eval(), along with the optional |
|
115 | 115 | global/local dicts provided. If no dicts are given, they are |
|
116 | 116 | extracted automatically from the caller's frame. |
|
117 | 117 | |
|
118 | 118 | A Python statement is NOT a valid eval() expression. Basically, you |
|
119 | 119 | can only use as an eval() argument something which can go on the right |
|
120 | 120 | of an '=' sign and be assigned to a variable. |
|
121 | 121 | |
|
122 | 122 | For example,"print 'hello'" is not valid, but '2+3' is. |
|
123 | 123 | |
|
124 | 124 | 2. Jobs given a function object, optionally passing additional |
|
125 | 125 | positional arguments: |
|
126 | 126 | |
|
127 | 127 | job_manager.new(myfunc, x, y) |
|
128 | 128 | |
|
129 | 129 | The function is called with the given arguments. |
|
130 | 130 | |
|
131 | 131 | If you need to pass keyword arguments to your function, you must |
|
132 | 132 | supply them as a dict named kw: |
|
133 | 133 | |
|
134 | 134 | job_manager.new(myfunc, x, y, kw=dict(z=1)) |
|
135 | 135 | |
|
136 | 136 | The reason for this assymmetry is that the new() method needs to |
|
137 | 137 | maintain access to its own keywords, and this prevents name collisions |
|
138 | 138 | between arguments to new() and arguments to your own functions. |
|
139 | 139 | |
|
140 | 140 | In both cases, the result is stored in the job.result field of the |
|
141 | 141 | background job object. |
|
142 | 142 | |
|
143 | 143 | You can set `daemon` attribute of the thread by giving the keyword |
|
144 | 144 | argument `daemon`. |
|
145 | 145 | |
|
146 | 146 | Notes and caveats: |
|
147 | 147 | |
|
148 | 148 | 1. All threads running share the same standard output. Thus, if your |
|
149 | 149 | background jobs generate output, it will come out on top of whatever |
|
150 | 150 | you are currently writing. For this reason, background jobs are best |
|
151 | 151 | used with silent functions which simply return their output. |
|
152 | 152 | |
|
153 | 153 | 2. Threads also all work within the same global namespace, and this |
|
154 | 154 | system does not lock interactive variables. So if you send job to the |
|
155 | 155 | background which operates on a mutable object for a long time, and |
|
156 | 156 | start modifying that same mutable object interactively (or in another |
|
157 | 157 | backgrounded job), all sorts of bizarre behaviour will occur. |
|
158 | 158 | |
|
159 | 159 | 3. If a background job is spending a lot of time inside a C extension |
|
160 | 160 | module which does not release the Python Global Interpreter Lock |
|
161 | 161 | (GIL), this will block the IPython prompt. This is simply because the |
|
162 | 162 | Python interpreter can only switch between threads at Python |
|
163 | 163 | bytecodes. While the execution is inside C code, the interpreter must |
|
164 | 164 | simply wait unless the extension module releases the GIL. |
|
165 | 165 | |
|
166 | 166 | 4. There is no way, due to limitations in the Python threads library, |
|
167 | 167 | to kill a thread once it has started.""" |
|
168 | 168 | |
|
169 | 169 | if callable(func_or_exp): |
|
170 | 170 | kw = kwargs.get('kw',{}) |
|
171 | 171 | job = BackgroundJobFunc(func_or_exp,*args,**kw) |
|
172 | 172 | elif isinstance(func_or_exp, basestring): |
|
173 | 173 | if not args: |
|
174 | 174 | frame = sys._getframe(1) |
|
175 | 175 | glob, loc = frame.f_globals, frame.f_locals |
|
176 | 176 | elif len(args)==1: |
|
177 | 177 | glob = loc = args[0] |
|
178 | 178 | elif len(args)==2: |
|
179 | 179 | glob,loc = args |
|
180 | 180 | else: |
|
181 | 181 | raise ValueError( |
|
182 | 182 | 'Expression jobs take at most 2 args (globals,locals)') |
|
183 | 183 | job = BackgroundJobExpr(func_or_exp, glob, loc) |
|
184 | 184 | else: |
|
185 | 185 | raise TypeError('invalid args for new job') |
|
186 | 186 | |
|
187 | 187 | if kwargs.get('daemon', False): |
|
188 | 188 | job.daemon = True |
|
189 | 189 | job.num = len(self.all)+1 if self.all else 0 |
|
190 | 190 | self.running.append(job) |
|
191 | 191 | self.all[job.num] = job |
|
192 | 192 | print 'Starting job # %s in a separate thread.' % job.num |
|
193 | 193 | job.start() |
|
194 | 194 | return job |
|
195 | 195 | |
|
196 | 196 | def __getitem__(self, job_key): |
|
197 | 197 | num = job_key if isinstance(job_key, int) else job_key.num |
|
198 | 198 | return self.all[num] |
|
199 | 199 | |
|
200 | 200 | def __call__(self): |
|
201 | 201 | """An alias to self.status(), |
|
202 | 202 | |
|
203 | 203 | This allows you to simply call a job manager instance much like the |
|
204 | 204 | Unix `jobs` shell command.""" |
|
205 | 205 | |
|
206 | 206 | return self.status() |
|
207 | 207 | |
|
208 | 208 | def _update_status(self): |
|
209 | 209 | """Update the status of the job lists. |
|
210 | 210 | |
|
211 | 211 | This method moves finished jobs to one of two lists: |
|
212 | 212 | - self.completed: jobs which completed successfully |
|
213 | 213 | - self.dead: jobs which finished but died. |
|
214 | 214 | |
|
215 | 215 | It also copies those jobs to corresponding _report lists. These lists |
|
216 | 216 | are used to report jobs completed/dead since the last update, and are |
|
217 | 217 | then cleared by the reporting function after each call.""" |
|
218 | 218 | |
|
219 | 219 | # Status codes |
|
220 | 220 | srun, scomp, sdead = self._s_running, self._s_completed, self._s_dead |
|
221 | 221 | # State lists, use the actual lists b/c the public names are properties |
|
222 | 222 | # that call this very function on access |
|
223 | 223 | running, completed, dead = self._running, self._completed, self._dead |
|
224 | 224 | |
|
225 | 225 | # Now, update all state lists |
|
226 | 226 | for num, job in enumerate(running): |
|
227 | 227 | stat = job.stat_code |
|
228 | 228 | if stat == srun: |
|
229 | 229 | continue |
|
230 | 230 | elif stat == scomp: |
|
231 | 231 | completed.append(job) |
|
232 | 232 | self._comp_report.append(job) |
|
233 | 233 | running[num] = False |
|
234 | 234 | elif stat == sdead: |
|
235 | 235 | dead.append(job) |
|
236 | 236 | self._dead_report.append(job) |
|
237 | 237 | running[num] = False |
|
238 | 238 | # Remove dead/completed jobs from running list |
|
239 | 239 | running[:] = filter(None, running) |
|
240 | 240 | |
|
241 | 241 | def _group_report(self,group,name): |
|
242 | 242 | """Report summary for a given job group. |
|
243 | 243 | |
|
244 | 244 | Return True if the group had any elements.""" |
|
245 | 245 | |
|
246 | 246 | if group: |
|
247 | 247 | print '%s jobs:' % name |
|
248 | 248 | for job in group: |
|
249 | 249 | print '%s : %s' % (job.num,job) |
|
250 | 250 | |
|
251 | 251 | return True |
|
252 | 252 | |
|
253 | 253 | def _group_flush(self,group,name): |
|
254 | 254 | """Flush a given job group |
|
255 | 255 | |
|
256 | 256 | Return True if the group had any elements.""" |
|
257 | 257 | |
|
258 | 258 | njobs = len(group) |
|
259 | 259 | if njobs: |
|
260 | 260 | plural = {1:''}.setdefault(njobs,'s') |
|
261 | 261 | print 'Flushing %s %s job%s.' % (njobs,name,plural) |
|
262 | 262 | group[:] = [] |
|
263 | 263 | return True |
|
264 | 264 | |
|
265 | 265 | def _status_new(self): |
|
266 | 266 | """Print the status of newly finished jobs. |
|
267 | 267 | |
|
268 | 268 | Return True if any new jobs are reported. |
|
269 | 269 | |
|
270 | 270 | This call resets its own state every time, so it only reports jobs |
|
271 | 271 | which have finished since the last time it was called.""" |
|
272 | 272 | |
|
273 | 273 | self._update_status() |
|
274 | 274 | new_comp = self._group_report(self._comp_report, 'Completed') |
|
275 | 275 | new_dead = self._group_report(self._dead_report, |
|
276 | 276 | 'Dead, call jobs.traceback() for details') |
|
277 | 277 | self._comp_report[:] = [] |
|
278 | 278 | self._dead_report[:] = [] |
|
279 | 279 | return new_comp or new_dead |
|
280 | 280 | |
|
281 | 281 | def status(self,verbose=0): |
|
282 | 282 | """Print a status of all jobs currently being managed.""" |
|
283 | 283 | |
|
284 | 284 | self._update_status() |
|
285 | 285 | self._group_report(self.running,'Running') |
|
286 | 286 | self._group_report(self.completed,'Completed') |
|
287 | 287 | self._group_report(self.dead,'Dead') |
|
288 | 288 | # Also flush the report queues |
|
289 | 289 | self._comp_report[:] = [] |
|
290 | 290 | self._dead_report[:] = [] |
|
291 | 291 | |
|
292 | 292 | def remove(self,num): |
|
293 | 293 | """Remove a finished (completed or dead) job.""" |
|
294 | 294 | |
|
295 | 295 | try: |
|
296 | 296 | job = self.all[num] |
|
297 | 297 | except KeyError: |
|
298 | 298 | error('Job #%s not found' % num) |
|
299 | 299 | else: |
|
300 | 300 | stat_code = job.stat_code |
|
301 | 301 | if stat_code == self._s_running: |
|
302 | 302 | error('Job #%s is still running, it can not be removed.' % num) |
|
303 | 303 | return |
|
304 | 304 | elif stat_code == self._s_completed: |
|
305 | 305 | self.completed.remove(job) |
|
306 | 306 | elif stat_code == self._s_dead: |
|
307 | 307 | self.dead.remove(job) |
|
308 | 308 | |
|
309 | 309 | def flush(self): |
|
310 | 310 | """Flush all finished jobs (completed and dead) from lists. |
|
311 | 311 | |
|
312 | 312 | Running jobs are never flushed. |
|
313 | 313 | |
|
314 | 314 | It first calls _status_new(), to update info. If any jobs have |
|
315 | 315 | completed since the last _status_new() call, the flush operation |
|
316 | 316 | aborts.""" |
|
317 | 317 | |
|
318 | 318 | # Remove the finished jobs from the master dict |
|
319 | 319 | alljobs = self.all |
|
320 | 320 | for job in self.completed+self.dead: |
|
321 | 321 | del(alljobs[job.num]) |
|
322 | 322 | |
|
323 | 323 | # Now flush these lists completely |
|
324 | 324 | fl_comp = self._group_flush(self.completed, 'Completed') |
|
325 | 325 | fl_dead = self._group_flush(self.dead, 'Dead') |
|
326 | 326 | if not (fl_comp or fl_dead): |
|
327 | 327 | print 'No jobs to flush.' |
|
328 | 328 | |
|
329 | 329 | def result(self,num): |
|
330 | 330 | """result(N) -> return the result of job N.""" |
|
331 | 331 | try: |
|
332 | 332 | return self.all[num].result |
|
333 | 333 | except KeyError: |
|
334 | 334 | error('Job #%s not found' % num) |
|
335 | 335 | |
|
336 | 336 | def _traceback(self, job): |
|
337 | 337 | num = job if isinstance(job, int) else job.num |
|
338 | 338 | try: |
|
339 | 339 | self.all[num].traceback() |
|
340 | 340 | except KeyError: |
|
341 | 341 | error('Job #%s not found' % num) |
|
342 | 342 | |
|
343 | 343 | def traceback(self, job=None): |
|
344 | 344 | if job is None: |
|
345 | 345 | self._update_status() |
|
346 | 346 | for deadjob in self.dead: |
|
347 | 347 | print "Traceback for: %r" % deadjob |
|
348 | 348 | self._traceback(deadjob) |
|
349 | 349 | |
|
350 | 350 | else: |
|
351 | 351 | self._traceback(job) |
|
352 | 352 | |
|
353 | 353 | |
|
354 | 354 | class BackgroundJobBase(threading.Thread): |
|
355 | 355 | """Base class to build BackgroundJob classes. |
|
356 | 356 | |
|
357 | 357 | The derived classes must implement: |
|
358 | 358 | |
|
359 | 359 | - Their own __init__, since the one here raises NotImplementedError. The |
|
360 | 360 | derived constructor must call self._init() at the end, to provide common |
|
361 | 361 | initialization. |
|
362 | 362 | |
|
363 | 363 | - A strform attribute used in calls to __str__. |
|
364 | 364 | |
|
365 | 365 | - A call() method, which will make the actual execution call and must |
|
366 | 366 | return a value to be held in the 'result' field of the job object.""" |
|
367 | 367 | |
|
368 | 368 | # Class constants for status, in string and as numerical codes (when |
|
369 | 369 | # updating jobs lists, we don't want to do string comparisons). This will |
|
370 | 370 | # be done at every user prompt, so it has to be as fast as possible |
|
371 | 371 | stat_created = 'Created'; stat_created_c = 0 |
|
372 | 372 | stat_running = 'Running'; stat_running_c = 1 |
|
373 | 373 | stat_completed = 'Completed'; stat_completed_c = 2 |
|
374 | 374 | stat_dead = 'Dead (Exception), call jobs.traceback() for details' |
|
375 | 375 | stat_dead_c = -1 |
|
376 | 376 | |
|
377 | 377 | def __init__(self): |
|
378 | raise NotImplementedError, \ | |
|
379 | "This class can not be instantiated directly." | |
|
378 | raise NotImplementedError("This class can not be instantiated directly.") | |
|
380 | 379 | |
|
381 | 380 | def _init(self): |
|
382 | 381 | """Common initialization for all BackgroundJob objects""" |
|
383 | 382 | |
|
384 | 383 | for attr in ['call','strform']: |
|
385 | 384 | assert hasattr(self,attr), "Missing attribute <%s>" % attr |
|
386 | 385 | |
|
387 | 386 | # The num tag can be set by an external job manager |
|
388 | 387 | self.num = None |
|
389 | 388 | |
|
390 | 389 | self.status = BackgroundJobBase.stat_created |
|
391 | 390 | self.stat_code = BackgroundJobBase.stat_created_c |
|
392 | 391 | self.finished = False |
|
393 | 392 | self.result = '<BackgroundJob has not completed>' |
|
394 | 393 | |
|
395 | 394 | # reuse the ipython traceback handler if we can get to it, otherwise |
|
396 | 395 | # make a new one |
|
397 | 396 | try: |
|
398 | 397 | make_tb = get_ipython().InteractiveTB.text |
|
399 | 398 | except: |
|
400 | 399 | make_tb = AutoFormattedTB(mode = 'Context', |
|
401 | 400 | color_scheme='NoColor', |
|
402 | 401 | tb_offset = 1).text |
|
403 | 402 | # Note that the actual API for text() requires the three args to be |
|
404 | 403 | # passed in, so we wrap it in a simple lambda. |
|
405 | 404 | self._make_tb = lambda : make_tb(None, None, None) |
|
406 | 405 | |
|
407 | 406 | # Hold a formatted traceback if one is generated. |
|
408 | 407 | self._tb = None |
|
409 | 408 | |
|
410 | 409 | threading.Thread.__init__(self) |
|
411 | 410 | |
|
412 | 411 | def __str__(self): |
|
413 | 412 | return self.strform |
|
414 | 413 | |
|
415 | 414 | def __repr__(self): |
|
416 | 415 | return '<BackgroundJob #%d: %s>' % (self.num, self.strform) |
|
417 | 416 | |
|
418 | 417 | def traceback(self): |
|
419 | 418 | print self._tb |
|
420 | 419 | |
|
421 | 420 | def run(self): |
|
422 | 421 | try: |
|
423 | 422 | self.status = BackgroundJobBase.stat_running |
|
424 | 423 | self.stat_code = BackgroundJobBase.stat_running_c |
|
425 | 424 | self.result = self.call() |
|
426 | 425 | except: |
|
427 | 426 | self.status = BackgroundJobBase.stat_dead |
|
428 | 427 | self.stat_code = BackgroundJobBase.stat_dead_c |
|
429 | 428 | self.finished = None |
|
430 | 429 | self.result = ('<BackgroundJob died, call jobs.traceback() for details>') |
|
431 | 430 | self._tb = self._make_tb() |
|
432 | 431 | else: |
|
433 | 432 | self.status = BackgroundJobBase.stat_completed |
|
434 | 433 | self.stat_code = BackgroundJobBase.stat_completed_c |
|
435 | 434 | self.finished = True |
|
436 | 435 | |
|
437 | 436 | |
|
438 | 437 | class BackgroundJobExpr(BackgroundJobBase): |
|
439 | 438 | """Evaluate an expression as a background job (uses a separate thread).""" |
|
440 | 439 | |
|
441 | 440 | def __init__(self, expression, glob=None, loc=None): |
|
442 | 441 | """Create a new job from a string which can be fed to eval(). |
|
443 | 442 | |
|
444 | 443 | global/locals dicts can be provided, which will be passed to the eval |
|
445 | 444 | call.""" |
|
446 | 445 | |
|
447 | 446 | # fail immediately if the given expression can't be compiled |
|
448 | 447 | self.code = compile(expression,'<BackgroundJob compilation>','eval') |
|
449 | 448 | |
|
450 | 449 | glob = {} if glob is None else glob |
|
451 | 450 | loc = {} if loc is None else loc |
|
452 | 451 | self.expression = self.strform = expression |
|
453 | 452 | self.glob = glob |
|
454 | 453 | self.loc = loc |
|
455 | 454 | self._init() |
|
456 | 455 | |
|
457 | 456 | def call(self): |
|
458 | 457 | return eval(self.code,self.glob,self.loc) |
|
459 | 458 | |
|
460 | 459 | |
|
461 | 460 | class BackgroundJobFunc(BackgroundJobBase): |
|
462 | 461 | """Run a function call as a background job (uses a separate thread).""" |
|
463 | 462 | |
|
464 | 463 | def __init__(self, func, *args, **kwargs): |
|
465 | 464 | """Create a new job from a callable object. |
|
466 | 465 | |
|
467 | 466 | Any positional arguments and keyword args given to this constructor |
|
468 | 467 | after the initial callable are passed directly to it.""" |
|
469 | 468 | |
|
470 | 469 | if not callable(func): |
|
471 | 470 | raise TypeError( |
|
472 | 471 | 'first argument to BackgroundJobFunc must be callable') |
|
473 | 472 | |
|
474 | 473 | self.func = func |
|
475 | 474 | self.args = args |
|
476 | 475 | self.kwargs = kwargs |
|
477 | 476 | # The string form will only include the function passed, because |
|
478 | 477 | # generating string representations of the arguments is a potentially |
|
479 | 478 | # _very_ expensive operation (e.g. with large arrays). |
|
480 | 479 | self.strform = str(func) |
|
481 | 480 | self._init() |
|
482 | 481 | |
|
483 | 482 | def call(self): |
|
484 | 483 | return self.func(*self.args, **self.kwargs) |
@@ -1,188 +1,188 b'' | |||
|
1 | 1 | """Tests for the decorators we've created for IPython. |
|
2 | 2 | """ |
|
3 | 3 | |
|
4 | 4 | # Module imports |
|
5 | 5 | # Std lib |
|
6 | 6 | import inspect |
|
7 | 7 | import sys |
|
8 | 8 | import unittest |
|
9 | 9 | |
|
10 | 10 | # Third party |
|
11 | 11 | import nose.tools as nt |
|
12 | 12 | |
|
13 | 13 | # Our own |
|
14 | 14 | from IPython.testing import decorators as dec |
|
15 | 15 | from IPython.testing.skipdoctest import skip_doctest |
|
16 | 16 | from IPython.testing.ipunittest import ParametricTestCase |
|
17 | 17 | |
|
18 | 18 | #----------------------------------------------------------------------------- |
|
19 | 19 | # Utilities |
|
20 | 20 | |
|
21 | 21 | # Note: copied from OInspect, kept here so the testing stuff doesn't create |
|
22 | 22 | # circular dependencies and is easier to reuse. |
|
23 | 23 | def getargspec(obj): |
|
24 | 24 | """Get the names and default values of a function's arguments. |
|
25 | 25 | |
|
26 | 26 | A tuple of four things is returned: (args, varargs, varkw, defaults). |
|
27 | 27 | 'args' is a list of the argument names (it may contain nested lists). |
|
28 | 28 | 'varargs' and 'varkw' are the names of the * and ** arguments or None. |
|
29 | 29 | 'defaults' is an n-tuple of the default values of the last n arguments. |
|
30 | 30 | |
|
31 | 31 | Modified version of inspect.getargspec from the Python Standard |
|
32 | 32 | Library.""" |
|
33 | 33 | |
|
34 | 34 | if inspect.isfunction(obj): |
|
35 | 35 | func_obj = obj |
|
36 | 36 | elif inspect.ismethod(obj): |
|
37 | 37 | func_obj = obj.im_func |
|
38 | 38 | else: |
|
39 |
raise TypeError |
|
|
39 | raise TypeError('arg is not a Python function') | |
|
40 | 40 | args, varargs, varkw = inspect.getargs(func_obj.func_code) |
|
41 | 41 | return args, varargs, varkw, func_obj.func_defaults |
|
42 | 42 | |
|
43 | 43 | #----------------------------------------------------------------------------- |
|
44 | 44 | # Testing functions |
|
45 | 45 | |
|
46 | 46 | @dec.as_unittest |
|
47 | 47 | def trivial(): |
|
48 | 48 | """A trivial test""" |
|
49 | 49 | pass |
|
50 | 50 | |
|
51 | 51 | # Some examples of parametric tests. |
|
52 | 52 | |
|
53 | 53 | def is_smaller(i,j): |
|
54 | 54 | assert i<j,"%s !< %s" % (i,j) |
|
55 | 55 | |
|
56 | 56 | class Tester(ParametricTestCase): |
|
57 | 57 | |
|
58 | 58 | def test_parametric(self): |
|
59 | 59 | yield is_smaller(3, 4) |
|
60 | 60 | x, y = 1, 2 |
|
61 | 61 | yield is_smaller(x, y) |
|
62 | 62 | |
|
63 | 63 | @dec.parametric |
|
64 | 64 | def test_par_standalone(): |
|
65 | 65 | yield is_smaller(3, 4) |
|
66 | 66 | x, y = 1, 2 |
|
67 | 67 | yield is_smaller(x, y) |
|
68 | 68 | |
|
69 | 69 | |
|
70 | 70 | @dec.skip |
|
71 | 71 | def test_deliberately_broken(): |
|
72 | 72 | """A deliberately broken test - we want to skip this one.""" |
|
73 | 73 | 1/0 |
|
74 | 74 | |
|
75 | 75 | @dec.skip('Testing the skip decorator') |
|
76 | 76 | def test_deliberately_broken2(): |
|
77 | 77 | """Another deliberately broken test - we want to skip this one.""" |
|
78 | 78 | 1/0 |
|
79 | 79 | |
|
80 | 80 | |
|
81 | 81 | # Verify that we can correctly skip the doctest for a function at will, but |
|
82 | 82 | # that the docstring itself is NOT destroyed by the decorator. |
|
83 | 83 | @skip_doctest |
|
84 | 84 | def doctest_bad(x,y=1,**k): |
|
85 | 85 | """A function whose doctest we need to skip. |
|
86 | 86 | |
|
87 | 87 | >>> 1+1 |
|
88 | 88 | 3 |
|
89 | 89 | """ |
|
90 | 90 | print 'x:',x |
|
91 | 91 | print 'y:',y |
|
92 | 92 | print 'k:',k |
|
93 | 93 | |
|
94 | 94 | |
|
95 | 95 | def call_doctest_bad(): |
|
96 | 96 | """Check that we can still call the decorated functions. |
|
97 | 97 | |
|
98 | 98 | >>> doctest_bad(3,y=4) |
|
99 | 99 | x: 3 |
|
100 | 100 | y: 4 |
|
101 | 101 | k: {} |
|
102 | 102 | """ |
|
103 | 103 | pass |
|
104 | 104 | |
|
105 | 105 | |
|
106 | 106 | def test_skip_dt_decorator(): |
|
107 | 107 | """Doctest-skipping decorator should preserve the docstring. |
|
108 | 108 | """ |
|
109 | 109 | # Careful: 'check' must be a *verbatim* copy of the doctest_bad docstring! |
|
110 | 110 | check = """A function whose doctest we need to skip. |
|
111 | 111 | |
|
112 | 112 | >>> 1+1 |
|
113 | 113 | 3 |
|
114 | 114 | """ |
|
115 | 115 | # Fetch the docstring from doctest_bad after decoration. |
|
116 | 116 | val = doctest_bad.__doc__ |
|
117 | 117 | |
|
118 | 118 | nt.assert_equal(check,val,"doctest_bad docstrings don't match") |
|
119 | 119 | |
|
120 | 120 | |
|
121 | 121 | # Doctest skipping should work for class methods too |
|
122 | 122 | class FooClass(object): |
|
123 | 123 | """FooClass |
|
124 | 124 | |
|
125 | 125 | Example: |
|
126 | 126 | |
|
127 | 127 | >>> 1+1 |
|
128 | 128 | 2 |
|
129 | 129 | """ |
|
130 | 130 | |
|
131 | 131 | @skip_doctest |
|
132 | 132 | def __init__(self,x): |
|
133 | 133 | """Make a FooClass. |
|
134 | 134 | |
|
135 | 135 | Example: |
|
136 | 136 | |
|
137 | 137 | >>> f = FooClass(3) |
|
138 | 138 | junk |
|
139 | 139 | """ |
|
140 | 140 | print 'Making a FooClass.' |
|
141 | 141 | self.x = x |
|
142 | 142 | |
|
143 | 143 | @skip_doctest |
|
144 | 144 | def bar(self,y): |
|
145 | 145 | """Example: |
|
146 | 146 | |
|
147 | 147 | >>> ff = FooClass(3) |
|
148 | 148 | >>> ff.bar(0) |
|
149 | 149 | boom! |
|
150 | 150 | >>> 1/0 |
|
151 | 151 | bam! |
|
152 | 152 | """ |
|
153 | 153 | return 1/y |
|
154 | 154 | |
|
155 | 155 | def baz(self,y): |
|
156 | 156 | """Example: |
|
157 | 157 | |
|
158 | 158 | >>> ff2 = FooClass(3) |
|
159 | 159 | Making a FooClass. |
|
160 | 160 | >>> ff2.baz(3) |
|
161 | 161 | True |
|
162 | 162 | """ |
|
163 | 163 | return self.x==y |
|
164 | 164 | |
|
165 | 165 | |
|
166 | 166 | def test_skip_dt_decorator2(): |
|
167 | 167 | """Doctest-skipping decorator should preserve function signature. |
|
168 | 168 | """ |
|
169 | 169 | # Hardcoded correct answer |
|
170 | 170 | dtargs = (['x', 'y'], None, 'k', (1,)) |
|
171 | 171 | # Introspect out the value |
|
172 | 172 | dtargsr = getargspec(doctest_bad) |
|
173 | 173 | assert dtargsr==dtargs, \ |
|
174 | 174 | "Incorrectly reconstructed args for doctest_bad: %s" % (dtargsr,) |
|
175 | 175 | |
|
176 | 176 | |
|
177 | 177 | @dec.skip_linux |
|
178 | 178 | def test_linux(): |
|
179 | 179 | nt.assert_false(sys.platform.startswith('linux'),"This test can't run under linux") |
|
180 | 180 | |
|
181 | 181 | @dec.skip_win32 |
|
182 | 182 | def test_win32(): |
|
183 | 183 | nt.assert_not_equals(sys.platform,'win32',"This test can't run under windows") |
|
184 | 184 | |
|
185 | 185 | @dec.skip_osx |
|
186 | 186 | def test_osx(): |
|
187 | 187 | nt.assert_not_equals(sys.platform,'darwin',"This test can't run under osx") |
|
188 | 188 |
@@ -1,167 +1,167 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """ |
|
3 | 3 | Older utilities that are not being used. |
|
4 | 4 | |
|
5 | 5 | WARNING: IF YOU NEED TO USE ONE OF THESE FUNCTIONS, PLEASE FIRST MOVE IT |
|
6 | 6 | TO ANOTHER APPROPRIATE MODULE IN IPython.utils. |
|
7 | 7 | """ |
|
8 | 8 | |
|
9 | 9 | #----------------------------------------------------------------------------- |
|
10 | 10 | # Copyright (C) 2008-2011 The IPython Development Team |
|
11 | 11 | # |
|
12 | 12 | # Distributed under the terms of the BSD License. The full license is in |
|
13 | 13 | # the file COPYING, distributed as part of this software. |
|
14 | 14 | #----------------------------------------------------------------------------- |
|
15 | 15 | |
|
16 | 16 | #----------------------------------------------------------------------------- |
|
17 | 17 | # Imports |
|
18 | 18 | #----------------------------------------------------------------------------- |
|
19 | 19 | |
|
20 | 20 | import sys |
|
21 | 21 | import warnings |
|
22 | 22 | |
|
23 | 23 | from IPython.utils.warn import warn |
|
24 | 24 | |
|
25 | 25 | #----------------------------------------------------------------------------- |
|
26 | 26 | # Code |
|
27 | 27 | #----------------------------------------------------------------------------- |
|
28 | 28 | |
|
29 | 29 | |
|
30 | 30 | def mutex_opts(dict,ex_op): |
|
31 | 31 | """Check for presence of mutually exclusive keys in a dict. |
|
32 | 32 | |
|
33 | 33 | Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]""" |
|
34 | 34 | for op1,op2 in ex_op: |
|
35 | 35 | if op1 in dict and op2 in dict: |
|
36 |
raise ValueError |
|
|
37 | 'Options '+op1+' and '+op2+' are mutually exclusive.' | |
|
36 | raise ValueError('\n*** ERROR in Arguments *** '\ | |
|
37 | 'Options '+op1+' and '+op2+' are mutually exclusive.') | |
|
38 | 38 | |
|
39 | 39 | |
|
40 | 40 | class EvalDict: |
|
41 | 41 | """ |
|
42 | 42 | Emulate a dict which evaluates its contents in the caller's frame. |
|
43 | 43 | |
|
44 | 44 | Usage: |
|
45 | 45 | >>> number = 19 |
|
46 | 46 | |
|
47 | 47 | >>> text = "python" |
|
48 | 48 | |
|
49 | 49 | >>> print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict() |
|
50 | 50 | Python 2.1 rules! |
|
51 | 51 | """ |
|
52 | 52 | |
|
53 | 53 | # This version is due to sismex01@hebmex.com on c.l.py, and is basically a |
|
54 | 54 | # modified (shorter) version of: |
|
55 | 55 | # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by |
|
56 | 56 | # Skip Montanaro (skip@pobox.com). |
|
57 | 57 | |
|
58 | 58 | def __getitem__(self, name): |
|
59 | 59 | frame = sys._getframe(1) |
|
60 | 60 | return eval(name, frame.f_globals, frame.f_locals) |
|
61 | 61 | |
|
62 | 62 | EvalString = EvalDict # for backwards compatibility |
|
63 | 63 | |
|
64 | 64 | |
|
65 | 65 | def all_belong(candidates,checklist): |
|
66 | 66 | """Check whether a list of items ALL appear in a given list of options. |
|
67 | 67 | |
|
68 | 68 | Returns a single 1 or 0 value.""" |
|
69 | 69 | |
|
70 | 70 | return 1-(0 in [x in checklist for x in candidates]) |
|
71 | 71 | |
|
72 | 72 | |
|
73 | 73 | def belong(candidates,checklist): |
|
74 | 74 | """Check whether a list of items appear in a given list of options. |
|
75 | 75 | |
|
76 | 76 | Returns a list of 1 and 0, one for each candidate given.""" |
|
77 | 77 | |
|
78 | 78 | return [x in checklist for x in candidates] |
|
79 | 79 | |
|
80 | 80 | |
|
81 | 81 | def with_obj(object, **args): |
|
82 | 82 | """Set multiple attributes for an object, similar to Pascal's with. |
|
83 | 83 | |
|
84 | 84 | Example: |
|
85 | 85 | with_obj(jim, |
|
86 | 86 | born = 1960, |
|
87 | 87 | haircolour = 'Brown', |
|
88 | 88 | eyecolour = 'Green') |
|
89 | 89 | |
|
90 | 90 | Credit: Greg Ewing, in |
|
91 | 91 | http://mail.python.org/pipermail/python-list/2001-May/040703.html. |
|
92 | 92 | |
|
93 | 93 | NOTE: up until IPython 0.7.2, this was called simply 'with', but 'with' |
|
94 | 94 | has become a keyword for Python 2.5, so we had to rename it.""" |
|
95 | 95 | |
|
96 | 96 | object.__dict__.update(args) |
|
97 | 97 | |
|
98 | 98 | |
|
99 | 99 | def map_method(method,object_list,*argseq,**kw): |
|
100 | 100 | """map_method(method,object_list,*args,**kw) -> list |
|
101 | 101 | |
|
102 | 102 | Return a list of the results of applying the methods to the items of the |
|
103 | 103 | argument sequence(s). If more than one sequence is given, the method is |
|
104 | 104 | called with an argument list consisting of the corresponding item of each |
|
105 | 105 | sequence. All sequences must be of the same length. |
|
106 | 106 | |
|
107 | 107 | Keyword arguments are passed verbatim to all objects called. |
|
108 | 108 | |
|
109 | 109 | This is Python code, so it's not nearly as fast as the builtin map().""" |
|
110 | 110 | |
|
111 | 111 | out_list = [] |
|
112 | 112 | idx = 0 |
|
113 | 113 | for object in object_list: |
|
114 | 114 | try: |
|
115 | 115 | handler = getattr(object, method) |
|
116 | 116 | except AttributeError: |
|
117 | 117 | out_list.append(None) |
|
118 | 118 | else: |
|
119 | 119 | if argseq: |
|
120 | 120 | args = map(lambda lst:lst[idx],argseq) |
|
121 | 121 | #print 'ob',object,'hand',handler,'ar',args # dbg |
|
122 | 122 | out_list.append(handler(args,**kw)) |
|
123 | 123 | else: |
|
124 | 124 | out_list.append(handler(**kw)) |
|
125 | 125 | idx += 1 |
|
126 | 126 | return out_list |
|
127 | 127 | |
|
128 | 128 | |
|
129 | 129 | def import_fail_info(mod_name,fns=None): |
|
130 | 130 | """Inform load failure for a module.""" |
|
131 | 131 | |
|
132 | 132 | if fns == None: |
|
133 | 133 | warn("Loading of %s failed.\n" % (mod_name,)) |
|
134 | 134 | else: |
|
135 | 135 | warn("Loading of %s from %s failed.\n" % (fns,mod_name)) |
|
136 | 136 | |
|
137 | 137 | |
|
138 | 138 | class NotGiven: pass |
|
139 | 139 | |
|
140 | 140 | def popkey(dct,key,default=NotGiven): |
|
141 | 141 | """Return dct[key] and delete dct[key]. |
|
142 | 142 | |
|
143 | 143 | If default is given, return it if dct[key] doesn't exist, otherwise raise |
|
144 | 144 | KeyError. """ |
|
145 | 145 | |
|
146 | 146 | try: |
|
147 | 147 | val = dct[key] |
|
148 | 148 | except KeyError: |
|
149 | 149 | if default is NotGiven: |
|
150 | 150 | raise |
|
151 | 151 | else: |
|
152 | 152 | return default |
|
153 | 153 | else: |
|
154 | 154 | del dct[key] |
|
155 | 155 | return val |
|
156 | 156 | |
|
157 | 157 | |
|
158 | 158 | def wrap_deprecated(func, suggest = '<nothing>'): |
|
159 | 159 | def newFunc(*args, **kwargs): |
|
160 | 160 | warnings.warn("Call to deprecated function %s, use %s instead" % |
|
161 | 161 | ( func.__name__, suggest), |
|
162 | 162 | category=DeprecationWarning, |
|
163 | 163 | stacklevel = 2) |
|
164 | 164 | return func(*args, **kwargs) |
|
165 | 165 | return newFunc |
|
166 | 166 | |
|
167 | 167 |
@@ -1,186 +1,186 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Tools for coloring text in ANSI terminals. |
|
3 | 3 | """ |
|
4 | 4 | |
|
5 | 5 | #***************************************************************************** |
|
6 | 6 | # Copyright (C) 2002-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 | __all__ = ['TermColors','InputTermColors','ColorScheme','ColorSchemeTable'] |
|
13 | 13 | |
|
14 | 14 | import os |
|
15 | 15 | |
|
16 | 16 | from IPython.utils.ipstruct import Struct |
|
17 | 17 | |
|
18 | 18 | color_templates = ( |
|
19 | 19 | # Dark colors |
|
20 | 20 | ("Black" , "0;30"), |
|
21 | 21 | ("Red" , "0;31"), |
|
22 | 22 | ("Green" , "0;32"), |
|
23 | 23 | ("Brown" , "0;33"), |
|
24 | 24 | ("Blue" , "0;34"), |
|
25 | 25 | ("Purple" , "0;35"), |
|
26 | 26 | ("Cyan" , "0;36"), |
|
27 | 27 | ("LightGray" , "0;37"), |
|
28 | 28 | # Light colors |
|
29 | 29 | ("DarkGray" , "1;30"), |
|
30 | 30 | ("LightRed" , "1;31"), |
|
31 | 31 | ("LightGreen" , "1;32"), |
|
32 | 32 | ("Yellow" , "1;33"), |
|
33 | 33 | ("LightBlue" , "1;34"), |
|
34 | 34 | ("LightPurple" , "1;35"), |
|
35 | 35 | ("LightCyan" , "1;36"), |
|
36 | 36 | ("White" , "1;37"), |
|
37 | 37 | # Blinking colors. Probably should not be used in anything serious. |
|
38 | 38 | ("BlinkBlack" , "5;30"), |
|
39 | 39 | ("BlinkRed" , "5;31"), |
|
40 | 40 | ("BlinkGreen" , "5;32"), |
|
41 | 41 | ("BlinkYellow" , "5;33"), |
|
42 | 42 | ("BlinkBlue" , "5;34"), |
|
43 | 43 | ("BlinkPurple" , "5;35"), |
|
44 | 44 | ("BlinkCyan" , "5;36"), |
|
45 | 45 | ("BlinkLightGray", "5;37"), |
|
46 | 46 | ) |
|
47 | 47 | |
|
48 | 48 | def make_color_table(in_class): |
|
49 | 49 | """Build a set of color attributes in a class. |
|
50 | 50 | |
|
51 | 51 | Helper function for building the *TermColors classes.""" |
|
52 | 52 | |
|
53 | 53 | for name,value in color_templates: |
|
54 | 54 | setattr(in_class,name,in_class._base % value) |
|
55 | 55 | |
|
56 | 56 | class TermColors: |
|
57 | 57 | """Color escape sequences. |
|
58 | 58 | |
|
59 | 59 | This class defines the escape sequences for all the standard (ANSI?) |
|
60 | 60 | colors in terminals. Also defines a NoColor escape which is just the null |
|
61 | 61 | string, suitable for defining 'dummy' color schemes in terminals which get |
|
62 | 62 | confused by color escapes. |
|
63 | 63 | |
|
64 | 64 | This class should be used as a mixin for building color schemes.""" |
|
65 | 65 | |
|
66 | 66 | NoColor = '' # for color schemes in color-less terminals. |
|
67 | 67 | Normal = '\033[0m' # Reset normal coloring |
|
68 | 68 | _base = '\033[%sm' # Template for all other colors |
|
69 | 69 | |
|
70 | 70 | # Build the actual color table as a set of class attributes: |
|
71 | 71 | make_color_table(TermColors) |
|
72 | 72 | |
|
73 | 73 | class InputTermColors: |
|
74 | 74 | """Color escape sequences for input prompts. |
|
75 | 75 | |
|
76 | 76 | This class is similar to TermColors, but the escapes are wrapped in \001 |
|
77 | 77 | and \002 so that readline can properly know the length of each line and |
|
78 | 78 | can wrap lines accordingly. Use this class for any colored text which |
|
79 | 79 | needs to be used in input prompts, such as in calls to raw_input(). |
|
80 | 80 | |
|
81 | 81 | This class defines the escape sequences for all the standard (ANSI?) |
|
82 | 82 | colors in terminals. Also defines a NoColor escape which is just the null |
|
83 | 83 | string, suitable for defining 'dummy' color schemes in terminals which get |
|
84 | 84 | confused by color escapes. |
|
85 | 85 | |
|
86 | 86 | This class should be used as a mixin for building color schemes.""" |
|
87 | 87 | |
|
88 | 88 | NoColor = '' # for color schemes in color-less terminals. |
|
89 | 89 | |
|
90 | 90 | if os.name == 'nt' and os.environ.get('TERM','dumb') == 'emacs': |
|
91 | 91 | # (X)emacs on W32 gets confused with \001 and \002 so we remove them |
|
92 | 92 | Normal = '\033[0m' # Reset normal coloring |
|
93 | 93 | _base = '\033[%sm' # Template for all other colors |
|
94 | 94 | else: |
|
95 | 95 | Normal = '\001\033[0m\002' # Reset normal coloring |
|
96 | 96 | _base = '\001\033[%sm\002' # Template for all other colors |
|
97 | 97 | |
|
98 | 98 | # Build the actual color table as a set of class attributes: |
|
99 | 99 | make_color_table(InputTermColors) |
|
100 | 100 | |
|
101 | 101 | class NoColors: |
|
102 | 102 | """This defines all the same names as the colour classes, but maps them to |
|
103 | 103 | empty strings, so it can easily be substituted to turn off colours.""" |
|
104 | 104 | NoColor = '' |
|
105 | 105 | Normal = '' |
|
106 | 106 | |
|
107 | 107 | for name, value in color_templates: |
|
108 | 108 | setattr(NoColors, name, '') |
|
109 | 109 | |
|
110 | 110 | class ColorScheme: |
|
111 | 111 | """Generic color scheme class. Just a name and a Struct.""" |
|
112 | 112 | def __init__(self,__scheme_name_,colordict=None,**colormap): |
|
113 | 113 | self.name = __scheme_name_ |
|
114 | 114 | if colordict is None: |
|
115 | 115 | self.colors = Struct(**colormap) |
|
116 | 116 | else: |
|
117 | 117 | self.colors = Struct(colordict) |
|
118 | 118 | |
|
119 | 119 | def copy(self,name=None): |
|
120 | 120 | """Return a full copy of the object, optionally renaming it.""" |
|
121 | 121 | if name is None: |
|
122 | 122 | name = self.name |
|
123 | 123 | return ColorScheme(name, self.colors.dict()) |
|
124 | 124 | |
|
125 | 125 | class ColorSchemeTable(dict): |
|
126 | 126 | """General class to handle tables of color schemes. |
|
127 | 127 | |
|
128 | 128 | It's basically a dict of color schemes with a couple of shorthand |
|
129 | 129 | attributes and some convenient methods. |
|
130 | 130 | |
|
131 | 131 | active_scheme_name -> obvious |
|
132 | 132 | active_colors -> actual color table of the active scheme""" |
|
133 | 133 | |
|
134 | 134 | def __init__(self,scheme_list=None,default_scheme=''): |
|
135 | 135 | """Create a table of color schemes. |
|
136 | 136 | |
|
137 | 137 | The table can be created empty and manually filled or it can be |
|
138 | 138 | created with a list of valid color schemes AND the specification for |
|
139 | 139 | the default active scheme. |
|
140 | 140 | """ |
|
141 | 141 | |
|
142 | 142 | # create object attributes to be set later |
|
143 | 143 | self.active_scheme_name = '' |
|
144 | 144 | self.active_colors = None |
|
145 | 145 | |
|
146 | 146 | if scheme_list: |
|
147 | 147 | if default_scheme == '': |
|
148 |
raise ValueError |
|
|
148 | raise ValueError('you must specify the default color scheme') | |
|
149 | 149 | for scheme in scheme_list: |
|
150 | 150 | self.add_scheme(scheme) |
|
151 | 151 | self.set_active_scheme(default_scheme) |
|
152 | 152 | |
|
153 | 153 | def copy(self): |
|
154 | 154 | """Return full copy of object""" |
|
155 | 155 | return ColorSchemeTable(self.values(),self.active_scheme_name) |
|
156 | 156 | |
|
157 | 157 | def add_scheme(self,new_scheme): |
|
158 | 158 | """Add a new color scheme to the table.""" |
|
159 | 159 | if not isinstance(new_scheme,ColorScheme): |
|
160 |
raise ValueError |
|
|
160 | raise ValueError('ColorSchemeTable only accepts ColorScheme instances') | |
|
161 | 161 | self[new_scheme.name] = new_scheme |
|
162 | 162 | |
|
163 | 163 | def set_active_scheme(self,scheme,case_sensitive=0): |
|
164 | 164 | """Set the currently active scheme. |
|
165 | 165 | |
|
166 | 166 | Names are by default compared in a case-insensitive way, but this can |
|
167 | 167 | be changed by setting the parameter case_sensitive to true.""" |
|
168 | 168 | |
|
169 | 169 | scheme_names = self.keys() |
|
170 | 170 | if case_sensitive: |
|
171 | 171 | valid_schemes = scheme_names |
|
172 | 172 | scheme_test = scheme |
|
173 | 173 | else: |
|
174 | 174 | valid_schemes = [s.lower() for s in scheme_names] |
|
175 | 175 | scheme_test = scheme.lower() |
|
176 | 176 | try: |
|
177 | 177 | scheme_idx = valid_schemes.index(scheme_test) |
|
178 | 178 | except ValueError: |
|
179 |
raise ValueError |
|
|
180 | '\nValid schemes: '+str(scheme_names).replace("'', ",'') | |
|
179 | raise ValueError('Unrecognized color scheme: ' + scheme + \ | |
|
180 | '\nValid schemes: '+str(scheme_names).replace("'', ",'')) | |
|
181 | 181 | else: |
|
182 | 182 | active = scheme_names[scheme_idx] |
|
183 | 183 | self.active_scheme_name = active |
|
184 | 184 | self.active_colors = self[active].colors |
|
185 | 185 | # Now allow using '' as an index for the current active scheme |
|
186 | 186 | self[''] = self[active] |
@@ -1,468 +1,468 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """ |
|
3 | 3 | Utilities for path handling. |
|
4 | 4 | """ |
|
5 | 5 | |
|
6 | 6 | #----------------------------------------------------------------------------- |
|
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 | # Imports |
|
15 | 15 | #----------------------------------------------------------------------------- |
|
16 | 16 | |
|
17 | 17 | import os |
|
18 | 18 | import sys |
|
19 | 19 | import tempfile |
|
20 | 20 | import warnings |
|
21 | 21 | from hashlib import md5 |
|
22 | 22 | |
|
23 | 23 | import IPython |
|
24 | 24 | from IPython.testing.skipdoctest import skip_doctest |
|
25 | 25 | from IPython.utils.process import system |
|
26 | 26 | from IPython.utils.importstring import import_item |
|
27 | 27 | from IPython.utils import py3compat |
|
28 | 28 | #----------------------------------------------------------------------------- |
|
29 | 29 | # Code |
|
30 | 30 | #----------------------------------------------------------------------------- |
|
31 | 31 | |
|
32 | 32 | fs_encoding = sys.getfilesystemencoding() |
|
33 | 33 | |
|
34 | 34 | def _get_long_path_name(path): |
|
35 | 35 | """Dummy no-op.""" |
|
36 | 36 | return path |
|
37 | 37 | |
|
38 | 38 | def _writable_dir(path): |
|
39 | 39 | """Whether `path` is a directory, to which the user has write access.""" |
|
40 | 40 | return os.path.isdir(path) and os.access(path, os.W_OK) |
|
41 | 41 | |
|
42 | 42 | if sys.platform == 'win32': |
|
43 | 43 | @skip_doctest |
|
44 | 44 | def _get_long_path_name(path): |
|
45 | 45 | """Get a long path name (expand ~) on Windows using ctypes. |
|
46 | 46 | |
|
47 | 47 | Examples |
|
48 | 48 | -------- |
|
49 | 49 | |
|
50 | 50 | >>> get_long_path_name('c:\\docume~1') |
|
51 | 51 | u'c:\\\\Documents and Settings' |
|
52 | 52 | |
|
53 | 53 | """ |
|
54 | 54 | try: |
|
55 | 55 | import ctypes |
|
56 | 56 | except ImportError: |
|
57 | 57 | raise ImportError('you need to have ctypes installed for this to work') |
|
58 | 58 | _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW |
|
59 | 59 | _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p, |
|
60 | 60 | ctypes.c_uint ] |
|
61 | 61 | |
|
62 | 62 | buf = ctypes.create_unicode_buffer(260) |
|
63 | 63 | rv = _GetLongPathName(path, buf, 260) |
|
64 | 64 | if rv == 0 or rv > 260: |
|
65 | 65 | return path |
|
66 | 66 | else: |
|
67 | 67 | return buf.value |
|
68 | 68 | |
|
69 | 69 | |
|
70 | 70 | def get_long_path_name(path): |
|
71 | 71 | """Expand a path into its long form. |
|
72 | 72 | |
|
73 | 73 | On Windows this expands any ~ in the paths. On other platforms, it is |
|
74 | 74 | a null operation. |
|
75 | 75 | """ |
|
76 | 76 | return _get_long_path_name(path) |
|
77 | 77 | |
|
78 | 78 | |
|
79 | 79 | def unquote_filename(name, win32=(sys.platform=='win32')): |
|
80 | 80 | """ On Windows, remove leading and trailing quotes from filenames. |
|
81 | 81 | """ |
|
82 | 82 | if win32: |
|
83 | 83 | if name.startswith(("'", '"')) and name.endswith(("'", '"')): |
|
84 | 84 | name = name[1:-1] |
|
85 | 85 | return name |
|
86 | 86 | |
|
87 | 87 | |
|
88 | 88 | def get_py_filename(name, force_win32=None): |
|
89 | 89 | """Return a valid python filename in the current directory. |
|
90 | 90 | |
|
91 | 91 | If the given name is not a file, it adds '.py' and searches again. |
|
92 | 92 | Raises IOError with an informative message if the file isn't found. |
|
93 | 93 | |
|
94 | 94 | On Windows, apply Windows semantics to the filename. In particular, remove |
|
95 | 95 | any quoting that has been applied to it. This option can be forced for |
|
96 | 96 | testing purposes. |
|
97 | 97 | """ |
|
98 | 98 | |
|
99 | 99 | name = os.path.expanduser(name) |
|
100 | 100 | if force_win32 is None: |
|
101 | 101 | win32 = (sys.platform == 'win32') |
|
102 | 102 | else: |
|
103 | 103 | win32 = force_win32 |
|
104 | 104 | name = unquote_filename(name, win32=win32) |
|
105 | 105 | if not os.path.isfile(name) and not name.endswith('.py'): |
|
106 | 106 | name += '.py' |
|
107 | 107 | if os.path.isfile(name): |
|
108 | 108 | return name |
|
109 | 109 | else: |
|
110 |
raise IOError |
|
|
110 | raise IOError('File `%r` not found.' % name) | |
|
111 | 111 | |
|
112 | 112 | |
|
113 | 113 | def filefind(filename, path_dirs=None): |
|
114 | 114 | """Find a file by looking through a sequence of paths. |
|
115 | 115 | |
|
116 | 116 | This iterates through a sequence of paths looking for a file and returns |
|
117 | 117 | the full, absolute path of the first occurence of the file. If no set of |
|
118 | 118 | path dirs is given, the filename is tested as is, after running through |
|
119 | 119 | :func:`expandvars` and :func:`expanduser`. Thus a simple call:: |
|
120 | 120 | |
|
121 | 121 | filefind('myfile.txt') |
|
122 | 122 | |
|
123 | 123 | will find the file in the current working dir, but:: |
|
124 | 124 | |
|
125 | 125 | filefind('~/myfile.txt') |
|
126 | 126 | |
|
127 | 127 | Will find the file in the users home directory. This function does not |
|
128 | 128 | automatically try any paths, such as the cwd or the user's home directory. |
|
129 | 129 | |
|
130 | 130 | Parameters |
|
131 | 131 | ---------- |
|
132 | 132 | filename : str |
|
133 | 133 | The filename to look for. |
|
134 | 134 | path_dirs : str, None or sequence of str |
|
135 | 135 | The sequence of paths to look for the file in. If None, the filename |
|
136 | 136 | need to be absolute or be in the cwd. If a string, the string is |
|
137 | 137 | put into a sequence and the searched. If a sequence, walk through |
|
138 | 138 | each element and join with ``filename``, calling :func:`expandvars` |
|
139 | 139 | and :func:`expanduser` before testing for existence. |
|
140 | 140 | |
|
141 | 141 | Returns |
|
142 | 142 | ------- |
|
143 | 143 | Raises :exc:`IOError` or returns absolute path to file. |
|
144 | 144 | """ |
|
145 | 145 | |
|
146 | 146 | # If paths are quoted, abspath gets confused, strip them... |
|
147 | 147 | filename = filename.strip('"').strip("'") |
|
148 | 148 | # If the input is an absolute path, just check it exists |
|
149 | 149 | if os.path.isabs(filename) and os.path.isfile(filename): |
|
150 | 150 | return filename |
|
151 | 151 | |
|
152 | 152 | if path_dirs is None: |
|
153 | 153 | path_dirs = ("",) |
|
154 | 154 | elif isinstance(path_dirs, basestring): |
|
155 | 155 | path_dirs = (path_dirs,) |
|
156 | 156 | |
|
157 | 157 | for path in path_dirs: |
|
158 | 158 | if path == '.': path = os.getcwdu() |
|
159 | 159 | testname = expand_path(os.path.join(path, filename)) |
|
160 | 160 | if os.path.isfile(testname): |
|
161 | 161 | return os.path.abspath(testname) |
|
162 | 162 | |
|
163 | 163 | raise IOError("File %r does not exist in any of the search paths: %r" % |
|
164 | 164 | (filename, path_dirs) ) |
|
165 | 165 | |
|
166 | 166 | |
|
167 | 167 | class HomeDirError(Exception): |
|
168 | 168 | pass |
|
169 | 169 | |
|
170 | 170 | |
|
171 | 171 | def get_home_dir(require_writable=False): |
|
172 | 172 | """Return the 'home' directory, as a unicode string. |
|
173 | 173 | |
|
174 | 174 | * First, check for frozen env in case of py2exe |
|
175 | 175 | * Otherwise, defer to os.path.expanduser('~') |
|
176 | 176 | |
|
177 | 177 | See stdlib docs for how this is determined. |
|
178 | 178 | $HOME is first priority on *ALL* platforms. |
|
179 | 179 | |
|
180 | 180 | Parameters |
|
181 | 181 | ---------- |
|
182 | 182 | |
|
183 | 183 | require_writable : bool [default: False] |
|
184 | 184 | if True: |
|
185 | 185 | guarantees the return value is a writable directory, otherwise |
|
186 | 186 | raises HomeDirError |
|
187 | 187 | if False: |
|
188 | 188 | The path is resolved, but it is not guaranteed to exist or be writable. |
|
189 | 189 | """ |
|
190 | 190 | |
|
191 | 191 | # first, check py2exe distribution root directory for _ipython. |
|
192 | 192 | # This overrides all. Normally does not exist. |
|
193 | 193 | |
|
194 | 194 | if hasattr(sys, "frozen"): #Is frozen by py2exe |
|
195 | 195 | if '\\library.zip\\' in IPython.__file__.lower():#libraries compressed to zip-file |
|
196 | 196 | root, rest = IPython.__file__.lower().split('library.zip') |
|
197 | 197 | else: |
|
198 | 198 | root=os.path.join(os.path.split(IPython.__file__)[0],"../../") |
|
199 | 199 | root=os.path.abspath(root).rstrip('\\') |
|
200 | 200 | if _writable_dir(os.path.join(root, '_ipython')): |
|
201 | 201 | os.environ["IPYKITROOT"] = root |
|
202 | 202 | return py3compat.cast_unicode(root, fs_encoding) |
|
203 | 203 | |
|
204 | 204 | homedir = os.path.expanduser('~') |
|
205 | 205 | # Next line will make things work even when /home/ is a symlink to |
|
206 | 206 | # /usr/home as it is on FreeBSD, for example |
|
207 | 207 | homedir = os.path.realpath(homedir) |
|
208 | 208 | |
|
209 | 209 | if not _writable_dir(homedir) and os.name == 'nt': |
|
210 | 210 | # expanduser failed, use the registry to get the 'My Documents' folder. |
|
211 | 211 | try: |
|
212 | 212 | import _winreg as wreg |
|
213 | 213 | key = wreg.OpenKey( |
|
214 | 214 | wreg.HKEY_CURRENT_USER, |
|
215 | 215 | "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" |
|
216 | 216 | ) |
|
217 | 217 | homedir = wreg.QueryValueEx(key,'Personal')[0] |
|
218 | 218 | key.Close() |
|
219 | 219 | except: |
|
220 | 220 | pass |
|
221 | 221 | |
|
222 | 222 | if (not require_writable) or _writable_dir(homedir): |
|
223 | 223 | return py3compat.cast_unicode(homedir, fs_encoding) |
|
224 | 224 | else: |
|
225 | 225 | raise HomeDirError('%s is not a writable dir, ' |
|
226 | 226 | 'set $HOME environment variable to override' % homedir) |
|
227 | 227 | |
|
228 | 228 | def get_xdg_dir(): |
|
229 | 229 | """Return the XDG_CONFIG_HOME, if it is defined and exists, else None. |
|
230 | 230 | |
|
231 | 231 | This is only for non-OS X posix (Linux,Unix,etc.) systems. |
|
232 | 232 | """ |
|
233 | 233 | |
|
234 | 234 | env = os.environ |
|
235 | 235 | |
|
236 | 236 | if os.name == 'posix' and sys.platform != 'darwin': |
|
237 | 237 | # Linux, Unix, AIX, etc. |
|
238 | 238 | # use ~/.config if empty OR not set |
|
239 | 239 | xdg = env.get("XDG_CONFIG_HOME", None) or os.path.join(get_home_dir(), '.config') |
|
240 | 240 | if xdg and _writable_dir(xdg): |
|
241 | 241 | return py3compat.cast_unicode(xdg, fs_encoding) |
|
242 | 242 | |
|
243 | 243 | return None |
|
244 | 244 | |
|
245 | 245 | |
|
246 | 246 | def get_ipython_dir(): |
|
247 | 247 | """Get the IPython directory for this platform and user. |
|
248 | 248 | |
|
249 | 249 | This uses the logic in `get_home_dir` to find the home directory |
|
250 | 250 | and then adds .ipython to the end of the path. |
|
251 | 251 | """ |
|
252 | 252 | |
|
253 | 253 | env = os.environ |
|
254 | 254 | pjoin = os.path.join |
|
255 | 255 | |
|
256 | 256 | |
|
257 | 257 | ipdir_def = '.ipython' |
|
258 | 258 | xdg_def = 'ipython' |
|
259 | 259 | |
|
260 | 260 | home_dir = get_home_dir() |
|
261 | 261 | xdg_dir = get_xdg_dir() |
|
262 | 262 | |
|
263 | 263 | # import pdb; pdb.set_trace() # dbg |
|
264 | 264 | if 'IPYTHON_DIR' in env: |
|
265 | 265 | warnings.warn('The environment variable IPYTHON_DIR is deprecated. ' |
|
266 | 266 | 'Please use IPYTHONDIR instead.') |
|
267 | 267 | ipdir = env.get('IPYTHONDIR', env.get('IPYTHON_DIR', None)) |
|
268 | 268 | if ipdir is None: |
|
269 | 269 | # not set explicitly, use XDG_CONFIG_HOME or HOME |
|
270 | 270 | home_ipdir = pjoin(home_dir, ipdir_def) |
|
271 | 271 | if xdg_dir: |
|
272 | 272 | # use XDG, as long as the user isn't already |
|
273 | 273 | # using $HOME/.ipython and *not* XDG/ipython |
|
274 | 274 | |
|
275 | 275 | xdg_ipdir = pjoin(xdg_dir, xdg_def) |
|
276 | 276 | |
|
277 | 277 | if _writable_dir(xdg_ipdir) or not _writable_dir(home_ipdir): |
|
278 | 278 | ipdir = xdg_ipdir |
|
279 | 279 | |
|
280 | 280 | if ipdir is None: |
|
281 | 281 | # not using XDG |
|
282 | 282 | ipdir = home_ipdir |
|
283 | 283 | |
|
284 | 284 | ipdir = os.path.normpath(os.path.expanduser(ipdir)) |
|
285 | 285 | |
|
286 | 286 | if os.path.exists(ipdir) and not _writable_dir(ipdir): |
|
287 | 287 | # ipdir exists, but is not writable |
|
288 | 288 | warnings.warn("IPython dir '%s' is not a writable location," |
|
289 | 289 | " using a temp directory."%ipdir) |
|
290 | 290 | ipdir = tempfile.mkdtemp() |
|
291 | 291 | elif not os.path.exists(ipdir): |
|
292 | 292 | parent = ipdir.rsplit(os.path.sep, 1)[0] |
|
293 | 293 | if not _writable_dir(parent): |
|
294 | 294 | # ipdir does not exist and parent isn't writable |
|
295 | 295 | warnings.warn("IPython parent '%s' is not a writable location," |
|
296 | 296 | " using a temp directory."%parent) |
|
297 | 297 | ipdir = tempfile.mkdtemp() |
|
298 | 298 | |
|
299 | 299 | return py3compat.cast_unicode(ipdir, fs_encoding) |
|
300 | 300 | |
|
301 | 301 | |
|
302 | 302 | def get_ipython_package_dir(): |
|
303 | 303 | """Get the base directory where IPython itself is installed.""" |
|
304 | 304 | ipdir = os.path.dirname(IPython.__file__) |
|
305 | 305 | return py3compat.cast_unicode(ipdir, fs_encoding) |
|
306 | 306 | |
|
307 | 307 | |
|
308 | 308 | def get_ipython_module_path(module_str): |
|
309 | 309 | """Find the path to an IPython module in this version of IPython. |
|
310 | 310 | |
|
311 | 311 | This will always find the version of the module that is in this importable |
|
312 | 312 | IPython package. This will always return the path to the ``.py`` |
|
313 | 313 | version of the module. |
|
314 | 314 | """ |
|
315 | 315 | if module_str == 'IPython': |
|
316 | 316 | return os.path.join(get_ipython_package_dir(), '__init__.py') |
|
317 | 317 | mod = import_item(module_str) |
|
318 | 318 | the_path = mod.__file__.replace('.pyc', '.py') |
|
319 | 319 | the_path = the_path.replace('.pyo', '.py') |
|
320 | 320 | return py3compat.cast_unicode(the_path, fs_encoding) |
|
321 | 321 | |
|
322 | 322 | def locate_profile(profile='default'): |
|
323 | 323 | """Find the path to the folder associated with a given profile. |
|
324 | 324 | |
|
325 | 325 | I.e. find $IPYTHONDIR/profile_whatever. |
|
326 | 326 | """ |
|
327 | 327 | from IPython.core.profiledir import ProfileDir, ProfileDirError |
|
328 | 328 | try: |
|
329 | 329 | pd = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile) |
|
330 | 330 | except ProfileDirError: |
|
331 | 331 | # IOError makes more sense when people are expecting a path |
|
332 | 332 | raise IOError("Couldn't find profile %r" % profile) |
|
333 | 333 | return pd.location |
|
334 | 334 | |
|
335 | 335 | def expand_path(s): |
|
336 | 336 | """Expand $VARS and ~names in a string, like a shell |
|
337 | 337 | |
|
338 | 338 | :Examples: |
|
339 | 339 | |
|
340 | 340 | In [2]: os.environ['FOO']='test' |
|
341 | 341 | |
|
342 | 342 | In [3]: expand_path('variable FOO is $FOO') |
|
343 | 343 | Out[3]: 'variable FOO is test' |
|
344 | 344 | """ |
|
345 | 345 | # This is a pretty subtle hack. When expand user is given a UNC path |
|
346 | 346 | # on Windows (\\server\share$\%username%), os.path.expandvars, removes |
|
347 | 347 | # the $ to get (\\server\share\%username%). I think it considered $ |
|
348 | 348 | # alone an empty var. But, we need the $ to remains there (it indicates |
|
349 | 349 | # a hidden share). |
|
350 | 350 | if os.name=='nt': |
|
351 | 351 | s = s.replace('$\\', 'IPYTHON_TEMP') |
|
352 | 352 | s = os.path.expandvars(os.path.expanduser(s)) |
|
353 | 353 | if os.name=='nt': |
|
354 | 354 | s = s.replace('IPYTHON_TEMP', '$\\') |
|
355 | 355 | return s |
|
356 | 356 | |
|
357 | 357 | |
|
358 | 358 | def target_outdated(target,deps): |
|
359 | 359 | """Determine whether a target is out of date. |
|
360 | 360 | |
|
361 | 361 | target_outdated(target,deps) -> 1/0 |
|
362 | 362 | |
|
363 | 363 | deps: list of filenames which MUST exist. |
|
364 | 364 | target: single filename which may or may not exist. |
|
365 | 365 | |
|
366 | 366 | If target doesn't exist or is older than any file listed in deps, return |
|
367 | 367 | true, otherwise return false. |
|
368 | 368 | """ |
|
369 | 369 | try: |
|
370 | 370 | target_time = os.path.getmtime(target) |
|
371 | 371 | except os.error: |
|
372 | 372 | return 1 |
|
373 | 373 | for dep in deps: |
|
374 | 374 | dep_time = os.path.getmtime(dep) |
|
375 | 375 | if dep_time > target_time: |
|
376 | 376 | #print "For target",target,"Dep failed:",dep # dbg |
|
377 | 377 | #print "times (dep,tar):",dep_time,target_time # dbg |
|
378 | 378 | return 1 |
|
379 | 379 | return 0 |
|
380 | 380 | |
|
381 | 381 | |
|
382 | 382 | def target_update(target,deps,cmd): |
|
383 | 383 | """Update a target with a given command given a list of dependencies. |
|
384 | 384 | |
|
385 | 385 | target_update(target,deps,cmd) -> runs cmd if target is outdated. |
|
386 | 386 | |
|
387 | 387 | This is just a wrapper around target_outdated() which calls the given |
|
388 | 388 | command if target is outdated.""" |
|
389 | 389 | |
|
390 | 390 | if target_outdated(target,deps): |
|
391 | 391 | system(cmd) |
|
392 | 392 | |
|
393 | 393 | def filehash(path): |
|
394 | 394 | """Make an MD5 hash of a file, ignoring any differences in line |
|
395 | 395 | ending characters.""" |
|
396 | 396 | with open(path, "rU") as f: |
|
397 | 397 | return md5(py3compat.str_to_bytes(f.read())).hexdigest() |
|
398 | 398 | |
|
399 | 399 | # If the config is unmodified from the default, we'll just delete it. |
|
400 | 400 | # These are consistent for 0.10.x, thankfully. We're not going to worry about |
|
401 | 401 | # older versions. |
|
402 | 402 | old_config_md5 = {'ipy_user_conf.py': 'fc108bedff4b9a00f91fa0a5999140d3', |
|
403 | 403 | 'ipythonrc': '12a68954f3403eea2eec09dc8fe5a9b5'} |
|
404 | 404 | |
|
405 | 405 | def check_for_old_config(ipython_dir=None): |
|
406 | 406 | """Check for old config files, and present a warning if they exist. |
|
407 | 407 | |
|
408 | 408 | A link to the docs of the new config is included in the message. |
|
409 | 409 | |
|
410 | 410 | This should mitigate confusion with the transition to the new |
|
411 | 411 | config system in 0.11. |
|
412 | 412 | """ |
|
413 | 413 | if ipython_dir is None: |
|
414 | 414 | ipython_dir = get_ipython_dir() |
|
415 | 415 | |
|
416 | 416 | old_configs = ['ipy_user_conf.py', 'ipythonrc', 'ipython_config.py'] |
|
417 | 417 | warned = False |
|
418 | 418 | for cfg in old_configs: |
|
419 | 419 | f = os.path.join(ipython_dir, cfg) |
|
420 | 420 | if os.path.exists(f): |
|
421 | 421 | if filehash(f) == old_config_md5.get(cfg, ''): |
|
422 | 422 | os.unlink(f) |
|
423 | 423 | else: |
|
424 | 424 | warnings.warn("Found old IPython config file %r (modified by user)"%f) |
|
425 | 425 | warned = True |
|
426 | 426 | |
|
427 | 427 | if warned: |
|
428 | 428 | warnings.warn(""" |
|
429 | 429 | The IPython configuration system has changed as of 0.11, and these files will |
|
430 | 430 | be ignored. See http://ipython.github.com/ipython-doc/dev/config for details |
|
431 | 431 | of the new config system. |
|
432 | 432 | To start configuring IPython, do `ipython profile create`, and edit |
|
433 | 433 | `ipython_config.py` in <ipython_dir>/profile_default. |
|
434 | 434 | If you need to leave the old config files in place for an older version of |
|
435 | 435 | IPython and want to suppress this warning message, set |
|
436 | 436 | `c.InteractiveShellApp.ignore_old_config=True` in the new config.""") |
|
437 | 437 | |
|
438 | 438 | def get_security_file(filename, profile='default'): |
|
439 | 439 | """Return the absolute path of a security file given by filename and profile |
|
440 | 440 | |
|
441 | 441 | This allows users and developers to find security files without |
|
442 | 442 | knowledge of the IPython directory structure. The search path |
|
443 | 443 | will be ['.', profile.security_dir] |
|
444 | 444 | |
|
445 | 445 | Parameters |
|
446 | 446 | ---------- |
|
447 | 447 | |
|
448 | 448 | filename : str |
|
449 | 449 | The file to be found. If it is passed as an absolute path, it will |
|
450 | 450 | simply be returned. |
|
451 | 451 | profile : str [default: 'default'] |
|
452 | 452 | The name of the profile to search. Leaving this unspecified |
|
453 | 453 | The file to be found. If it is passed as an absolute path, fname will |
|
454 | 454 | simply be returned. |
|
455 | 455 | |
|
456 | 456 | Returns |
|
457 | 457 | ------- |
|
458 | 458 | Raises :exc:`IOError` if file not found or returns absolute path to file. |
|
459 | 459 | """ |
|
460 | 460 | # import here, because profiledir also imports from utils.path |
|
461 | 461 | from IPython.core.profiledir import ProfileDir |
|
462 | 462 | try: |
|
463 | 463 | pd = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile) |
|
464 | 464 | except Exception: |
|
465 | 465 | # will raise ProfileDirError if no such profile |
|
466 | 466 | raise IOError("Profile %r not found") |
|
467 | 467 | return filefind(filename, ['.', pd.security_dir]) |
|
468 | 468 |
General Comments 0
You need to be logged in to leave comments.
Login now