Show More
@@ -0,0 +1,41 b'' | |||
|
1 | from IPython.utils.capture import capture_output | |
|
2 | ||
|
3 | import nose.tools as nt | |
|
4 | ||
|
5 | def test_alias_lifecycle(): | |
|
6 | name = 'test_alias1' | |
|
7 | cmd = 'echo "Hello"' | |
|
8 | am = _ip.alias_manager | |
|
9 | am.clear_aliases() | |
|
10 | am.define_alias(name, cmd) | |
|
11 | assert am.is_alias(name) | |
|
12 | nt.assert_equal(am.retrieve_alias(name), cmd) | |
|
13 | nt.assert_in((name, cmd), am.aliases) | |
|
14 | ||
|
15 | # Test running the alias | |
|
16 | orig_system = _ip.system | |
|
17 | result = [] | |
|
18 | _ip.system = result.append | |
|
19 | try: | |
|
20 | _ip.run_cell('%{}'.format(name)) | |
|
21 | result = [c.strip() for c in result] | |
|
22 | nt.assert_equal(result, [cmd]) | |
|
23 | finally: | |
|
24 | _ip.system = orig_system | |
|
25 | ||
|
26 | # Test removing the alias | |
|
27 | am.undefine_alias(name) | |
|
28 | assert not am.is_alias(name) | |
|
29 | with nt.assert_raises(ValueError): | |
|
30 | am.retrieve_alias(name) | |
|
31 | nt.assert_not_in((name, cmd), am.aliases) | |
|
32 | ||
|
33 | ||
|
34 | def test_alias_args_error(): | |
|
35 | """Error expanding with wrong number of arguments""" | |
|
36 | _ip.alias_manager.define_alias('parts', 'echo first %s second %s') | |
|
37 | # capture stderr: | |
|
38 | with capture_output() as cap: | |
|
39 | _ip.run_cell('parts 1') | |
|
40 | ||
|
41 | nt.assert_equal(cap.stderr.split(':')[0], 'UsageError') No newline at end of file |
@@ -0,0 +1,3 b'' | |||
|
1 | - The alias system has been reimplemented to use magic functions. There should be little | |
|
2 | visible difference while automagics are enabled, as they are by default, but parts of the | |
|
3 | :class:`~IPython.core.alias.AliasManager` API have been removed. |
@@ -1,262 +1,237 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """ |
|
3 | 3 | System command aliases. |
|
4 | 4 | |
|
5 | 5 | Authors: |
|
6 | 6 | |
|
7 | 7 | * Fernando Perez |
|
8 | 8 | * Brian Granger |
|
9 | 9 | """ |
|
10 | 10 | |
|
11 | 11 | #----------------------------------------------------------------------------- |
|
12 | 12 | # Copyright (C) 2008-2011 The IPython Development Team |
|
13 | 13 | # |
|
14 | 14 | # Distributed under the terms of the BSD License. |
|
15 | 15 | # |
|
16 | 16 | # The full license is in the file COPYING.txt, distributed with this software. |
|
17 | 17 | #----------------------------------------------------------------------------- |
|
18 | 18 | |
|
19 | 19 | #----------------------------------------------------------------------------- |
|
20 | 20 | # Imports |
|
21 | 21 | #----------------------------------------------------------------------------- |
|
22 | 22 | |
|
23 | import __builtin__ | |
|
24 | import keyword | |
|
25 | 23 | import os |
|
26 | 24 | import re |
|
27 | 25 | import sys |
|
28 | 26 | |
|
29 | 27 | from IPython.config.configurable import Configurable |
|
30 |
from IPython.core. |
|
|
28 | from IPython.core.error import UsageError | |
|
31 | 29 | |
|
32 | 30 | from IPython.utils.traitlets import List, Instance |
|
33 |
from IPython.utils.warn import |
|
|
31 | from IPython.utils.warn import error | |
|
34 | 32 | |
|
35 | 33 | #----------------------------------------------------------------------------- |
|
36 | 34 | # Utilities |
|
37 | 35 | #----------------------------------------------------------------------------- |
|
38 | 36 | |
|
39 | 37 | # This is used as the pattern for calls to split_user_input. |
|
40 | 38 | shell_line_split = re.compile(r'^(\s*)()(\S+)(.*$)') |
|
41 | 39 | |
|
42 | 40 | def default_aliases(): |
|
43 | 41 | """Return list of shell aliases to auto-define. |
|
44 | 42 | """ |
|
45 | 43 | # Note: the aliases defined here should be safe to use on a kernel |
|
46 | 44 | # regardless of what frontend it is attached to. Frontends that use a |
|
47 | 45 | # kernel in-process can define additional aliases that will only work in |
|
48 | 46 | # their case. For example, things like 'less' or 'clear' that manipulate |
|
49 | 47 | # the terminal should NOT be declared here, as they will only work if the |
|
50 | 48 | # kernel is running inside a true terminal, and not over the network. |
|
51 | 49 | |
|
52 | 50 | if os.name == 'posix': |
|
53 | 51 | default_aliases = [('mkdir', 'mkdir'), ('rmdir', 'rmdir'), |
|
54 | 52 | ('mv', 'mv -i'), ('rm', 'rm -i'), ('cp', 'cp -i'), |
|
55 | 53 | ('cat', 'cat'), |
|
56 | 54 | ] |
|
57 | 55 | # Useful set of ls aliases. The GNU and BSD options are a little |
|
58 | 56 | # different, so we make aliases that provide as similar as possible |
|
59 | 57 | # behavior in ipython, by passing the right flags for each platform |
|
60 | 58 | if sys.platform.startswith('linux'): |
|
61 | 59 | ls_aliases = [('ls', 'ls -F --color'), |
|
62 | 60 | # long ls |
|
63 | 61 | ('ll', 'ls -F -o --color'), |
|
64 | 62 | # ls normal files only |
|
65 | 63 | ('lf', 'ls -F -o --color %l | grep ^-'), |
|
66 | 64 | # ls symbolic links |
|
67 | 65 | ('lk', 'ls -F -o --color %l | grep ^l'), |
|
68 | 66 | # directories or links to directories, |
|
69 | 67 | ('ldir', 'ls -F -o --color %l | grep /$'), |
|
70 | 68 | # things which are executable |
|
71 | 69 | ('lx', 'ls -F -o --color %l | grep ^-..x'), |
|
72 | 70 | ] |
|
73 | 71 | else: |
|
74 | 72 | # BSD, OSX, etc. |
|
75 | 73 | ls_aliases = [('ls', 'ls -F -G'), |
|
76 | 74 | # long ls |
|
77 | 75 | ('ll', 'ls -F -l -G'), |
|
78 | 76 | # ls normal files only |
|
79 | 77 | ('lf', 'ls -F -l -G %l | grep ^-'), |
|
80 | 78 | # ls symbolic links |
|
81 | 79 | ('lk', 'ls -F -l -G %l | grep ^l'), |
|
82 | 80 | # directories or links to directories, |
|
83 | 81 | ('ldir', 'ls -F -G -l %l | grep /$'), |
|
84 | 82 | # things which are executable |
|
85 | 83 | ('lx', 'ls -F -l -G %l | grep ^-..x'), |
|
86 | 84 | ] |
|
87 | 85 | default_aliases = default_aliases + ls_aliases |
|
88 | 86 | elif os.name in ['nt', 'dos']: |
|
89 | 87 | default_aliases = [('ls', 'dir /on'), |
|
90 | 88 | ('ddir', 'dir /ad /on'), ('ldir', 'dir /ad /on'), |
|
91 | 89 | ('mkdir', 'mkdir'), ('rmdir', 'rmdir'), |
|
92 | 90 | ('echo', 'echo'), ('ren', 'ren'), ('copy', 'copy'), |
|
93 | 91 | ] |
|
94 | 92 | else: |
|
95 | 93 | default_aliases = [] |
|
96 | 94 | |
|
97 | 95 | return default_aliases |
|
98 | 96 | |
|
99 | 97 | |
|
100 | 98 | class AliasError(Exception): |
|
101 | 99 | pass |
|
102 | 100 | |
|
103 | 101 | |
|
104 | 102 | class InvalidAliasError(AliasError): |
|
105 | 103 | pass |
|
106 | 104 | |
|
105 | class Alias(object): | |
|
106 | """Callable object storing the details of one alias. | |
|
107 | ||
|
108 | Instances are registered as magic functions to allow use of aliases. | |
|
109 | """ | |
|
110 | ||
|
111 | # Prepare blacklist | |
|
112 | blacklist = {'cd','popd','pushd','dhist','alias','unalias'} | |
|
113 | ||
|
114 | def __init__(self, shell, name, cmd): | |
|
115 | self.shell = shell | |
|
116 | self.name = name | |
|
117 | self.cmd = cmd | |
|
118 | self.nargs = self.validate() | |
|
119 | ||
|
120 | def validate(self): | |
|
121 | """Validate the alias, and return the number of arguments.""" | |
|
122 | if self.name in self.blacklist: | |
|
123 | raise InvalidAliasError("The name %s can't be aliased " | |
|
124 | "because it is a keyword or builtin." % self.name) | |
|
125 | try: | |
|
126 | caller = self.shell.magics_manager.magics['line'][self.name] | |
|
127 | except KeyError: | |
|
128 | pass | |
|
129 | else: | |
|
130 | if not isinstance(caller, Alias): | |
|
131 | raise InvalidAliasError("The name %s can't be aliased " | |
|
132 | "because it is another magic command." % self.name) | |
|
133 | ||
|
134 | if not (isinstance(self.cmd, basestring)): | |
|
135 | raise InvalidAliasError("An alias command must be a string, " | |
|
136 | "got: %r" % self.cmd) | |
|
137 | ||
|
138 | nargs = self.cmd.count('%s') | |
|
139 | ||
|
140 | if (nargs > 0) and (self.cmd.find('%l') >= 0): | |
|
141 | raise InvalidAliasError('The %s and %l specifiers are mutually ' | |
|
142 | 'exclusive in alias definitions.') | |
|
143 | ||
|
144 | return nargs | |
|
145 | ||
|
146 | def __repr__(self): | |
|
147 | return "<alias {} for {!r}>".format(self.name, self.cmd) | |
|
148 | ||
|
149 | def __call__(self, rest=''): | |
|
150 | cmd = self.cmd | |
|
151 | nargs = self.nargs | |
|
152 | # Expand the %l special to be the user's input line | |
|
153 | if cmd.find('%l') >= 0: | |
|
154 | cmd = cmd.replace('%l', rest) | |
|
155 | rest = '' | |
|
156 | if nargs==0: | |
|
157 | # Simple, argument-less aliases | |
|
158 | cmd = '%s %s' % (cmd, rest) | |
|
159 | else: | |
|
160 | # Handle aliases with positional arguments | |
|
161 | args = rest.split(None, nargs) | |
|
162 | if len(args) < nargs: | |
|
163 | raise UsageError('Alias <%s> requires %s arguments, %s given.' % | |
|
164 | (self.name, nargs, len(args))) | |
|
165 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) | |
|
166 | ||
|
167 | self.shell.system(cmd) | |
|
168 | ||
|
107 | 169 | #----------------------------------------------------------------------------- |
|
108 | 170 | # Main AliasManager class |
|
109 | 171 | #----------------------------------------------------------------------------- |
|
110 | 172 | |
|
111 | 173 | class AliasManager(Configurable): |
|
112 | 174 | |
|
113 | 175 | default_aliases = List(default_aliases(), config=True) |
|
114 | 176 | user_aliases = List(default_value=[], config=True) |
|
115 | 177 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
116 | 178 | |
|
117 | 179 | def __init__(self, shell=None, **kwargs): |
|
118 | 180 | super(AliasManager, self).__init__(shell=shell, **kwargs) |
|
119 | self.alias_table = {} | |
|
120 | self.exclude_aliases() | |
|
181 | # For convenient access | |
|
182 | self.linemagics = self.shell.magics_manager.magics['line'] | |
|
121 | 183 | self.init_aliases() |
|
122 | 184 | |
|
123 | def __contains__(self, name): | |
|
124 | return name in self.alias_table | |
|
125 | ||
|
126 | @property | |
|
127 | def aliases(self): | |
|
128 | return [(item[0], item[1][1]) for item in self.alias_table.iteritems()] | |
|
129 | ||
|
130 | def exclude_aliases(self): | |
|
131 | # set of things NOT to alias (keywords, builtins and some magics) | |
|
132 | no_alias = set(['cd','popd','pushd','dhist','alias','unalias']) | |
|
133 | no_alias.update(set(keyword.kwlist)) | |
|
134 | no_alias.update(set(__builtin__.__dict__.keys())) | |
|
135 | self.no_alias = no_alias | |
|
136 | ||
|
137 | 185 | def init_aliases(self): |
|
138 | # Load default aliases | |
|
139 | for name, cmd in self.default_aliases: | |
|
140 | self.soft_define_alias(name, cmd) | |
|
141 | ||
|
142 | # Load user aliases | |
|
143 | for name, cmd in self.user_aliases: | |
|
186 | # Load default & user aliases | |
|
187 | for name, cmd in self.default_aliases + self.user_aliases: | |
|
144 | 188 | self.soft_define_alias(name, cmd) |
|
145 | 189 | |
|
146 | def clear_aliases(self): | |
|
147 | self.alias_table.clear() | |
|
190 | @property | |
|
191 | def aliases(self): | |
|
192 | return [(n, func.cmd) for (n, func) in self.linemagics.items() | |
|
193 | if isinstance(func, Alias)] | |
|
148 | 194 | |
|
149 | 195 | def soft_define_alias(self, name, cmd): |
|
150 | 196 | """Define an alias, but don't raise on an AliasError.""" |
|
151 | 197 | try: |
|
152 | 198 | self.define_alias(name, cmd) |
|
153 | 199 | except AliasError as e: |
|
154 | 200 | error("Invalid alias: %s" % e) |
|
155 | 201 | |
|
156 | 202 | def define_alias(self, name, cmd): |
|
157 | 203 | """Define a new alias after validating it. |
|
158 | 204 | |
|
159 | 205 | This will raise an :exc:`AliasError` if there are validation |
|
160 | 206 | problems. |
|
161 | 207 | """ |
|
162 | nargs = self.validate_alias(name, cmd) | |
|
163 | self.alias_table[name] = (nargs, cmd) | |
|
208 | caller = Alias(shell=self.shell, name=name, cmd=cmd) | |
|
209 | self.shell.magics_manager.register_function(caller, magic_kind='line', | |
|
210 | magic_name=name) | |
|
164 | 211 | |
|
165 |
def |
|
|
166 | if name in self.alias_table: | |
|
167 | del self.alias_table[name] | |
|
212 | def get_alias(self, name): | |
|
213 | """Return an alias, or None if no alias by that name exists.""" | |
|
214 | aname = self.linemagics.get(name, None) | |
|
215 | return aname if isinstance(aname, Alias) else None | |
|
168 | 216 | |
|
169 |
def |
|
|
170 | """Validate an alias and return the its number of arguments.""" | |
|
171 | if name in self.no_alias: | |
|
172 | raise InvalidAliasError("The name %s can't be aliased " | |
|
173 | "because it is a keyword or builtin." % name) | |
|
174 | if not (isinstance(cmd, basestring)): | |
|
175 | raise InvalidAliasError("An alias command must be a string, " | |
|
176 | "got: %r" % cmd) | |
|
177 | nargs = cmd.count('%s') | |
|
178 | if nargs>0 and cmd.find('%l')>=0: | |
|
179 | raise InvalidAliasError('The %s and %l specifiers are mutually ' | |
|
180 | 'exclusive in alias definitions.') | |
|
181 | return nargs | |
|
217 | def is_alias(self, name): | |
|
218 | """Return whether or not a given name has been defined as an alias""" | |
|
219 | return self.get_alias(name) is not None | |
|
182 | 220 | |
|
183 |
def |
|
|
184 | """Call an alias given its name and the rest of the line.""" | |
|
185 | cmd = self.transform_alias(alias, rest) | |
|
186 | try: | |
|
187 | self.shell.system(cmd) | |
|
188 | except: | |
|
189 | self.shell.showtraceback() | |
|
190 | ||
|
191 | def transform_alias(self, alias,rest=''): | |
|
192 | """Transform alias to system command string.""" | |
|
193 | nargs, cmd = self.alias_table[alias] | |
|
194 | ||
|
195 | if ' ' in cmd and os.path.isfile(cmd): | |
|
196 | cmd = '"%s"' % cmd | |
|
197 | ||
|
198 | # Expand the %l special to be the user's input line | |
|
199 | if cmd.find('%l') >= 0: | |
|
200 | cmd = cmd.replace('%l', rest) | |
|
201 | rest = '' | |
|
202 | if nargs==0: | |
|
203 | # Simple, argument-less aliases | |
|
204 | cmd = '%s %s' % (cmd, rest) | |
|
221 | def undefine_alias(self, name): | |
|
222 | if self.is_alias(name): | |
|
223 | del self.linemagics[name] | |
|
205 | 224 | else: |
|
206 | # Handle aliases with positional arguments | |
|
207 | args = rest.split(None, nargs) | |
|
208 | if len(args) < nargs: | |
|
209 | raise AliasError('Alias <%s> requires %s arguments, %s given.' % | |
|
210 | (alias, nargs, len(args))) | |
|
211 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) | |
|
212 | return cmd | |
|
213 | ||
|
214 | def expand_alias(self, line): | |
|
215 | """ Expand an alias in the command line | |
|
225 | raise ValueError('%s is not an alias' % name) | |
|
216 | 226 | |
|
217 | Returns the provided command line, possibly with the first word | |
|
218 | (command) translated according to alias expansion rules. | |
|
219 | ||
|
220 | [ipython]|16> _ip.expand_aliases("np myfile.txt") | |
|
221 | <16> 'q:/opt/np/notepad++.exe myfile.txt' | |
|
222 | """ | |
|
223 | ||
|
224 | pre,_,fn,rest = split_user_input(line) | |
|
225 | res = pre + self.expand_aliases(fn, rest) | |
|
226 |
|
|
|
227 | ||
|
228 | def expand_aliases(self, fn, rest): | |
|
229 | """Expand multiple levels of aliases: | |
|
230 | ||
|
231 | if: | |
|
232 | ||
|
233 | alias foo bar /tmp | |
|
234 | alias baz foo | |
|
235 | ||
|
236 | then: | |
|
237 | ||
|
238 | baz huhhahhei -> bar /tmp huhhahhei | |
|
239 | """ | |
|
240 | line = fn + " " + rest | |
|
241 | ||
|
242 | done = set() | |
|
243 | while 1: | |
|
244 | pre,_,fn,rest = split_user_input(line, shell_line_split) | |
|
245 | if fn in self.alias_table: | |
|
246 | if fn in done: | |
|
247 | warn("Cyclic alias definition, repeated '%s'" % fn) | |
|
248 | return "" | |
|
249 | done.add(fn) | |
|
250 | ||
|
251 | l2 = self.transform_alias(fn, rest) | |
|
252 | if l2 == line: | |
|
253 | break | |
|
254 | # ls -> ls -F should not recurse forever | |
|
255 | if l2.split(None,1)[0] == line.split(None,1)[0]: | |
|
256 | line = l2 | |
|
257 | break | |
|
258 | line = l2 | |
|
259 | else: | |
|
260 | break | |
|
261 | ||
|
262 | return line | |
|
227 | def clear_aliases(self): | |
|
228 | for name, cmd in self.aliases: | |
|
229 | self.undefine_alias(name) | |
|
230 | ||
|
231 | def retrieve_alias(self, name): | |
|
232 | """Retrieve the command to which an alias expands.""" | |
|
233 | caller = self.get_alias(name) | |
|
234 | if caller: | |
|
235 | return caller.cmd | |
|
236 | else: | |
|
237 | raise ValueError('%s is not an alias' % name) |
@@ -1,979 +1,955 b'' | |||
|
1 | 1 | """Word completion for IPython. |
|
2 | 2 | |
|
3 | 3 | This module is a fork of the rlcompleter module in the Python standard |
|
4 | 4 | library. The original enhancements made to rlcompleter have been sent |
|
5 | 5 | upstream and were accepted as of Python 2.3, but we need a lot more |
|
6 | 6 | functionality specific to IPython, so this module will continue to live as an |
|
7 | 7 | IPython-specific utility. |
|
8 | 8 | |
|
9 | 9 | Original rlcompleter documentation: |
|
10 | 10 | |
|
11 | 11 | This requires the latest extension to the readline module (the |
|
12 | 12 | completes keywords, built-ins and globals in __main__; when completing |
|
13 | 13 | NAME.NAME..., it evaluates (!) the expression up to the last dot and |
|
14 | 14 | completes its attributes. |
|
15 | 15 | |
|
16 | 16 | It's very cool to do "import string" type "string.", hit the |
|
17 | 17 | completion key (twice), and see the list of names defined by the |
|
18 | 18 | string module! |
|
19 | 19 | |
|
20 | 20 | Tip: to use the tab key as the completion key, call |
|
21 | 21 | |
|
22 | 22 | readline.parse_and_bind("tab: complete") |
|
23 | 23 | |
|
24 | 24 | Notes: |
|
25 | 25 | |
|
26 | 26 | - Exceptions raised by the completer function are *ignored* (and |
|
27 | 27 | generally cause the completion to fail). This is a feature -- since |
|
28 | 28 | readline sets the tty device in raw (or cbreak) mode, printing a |
|
29 | 29 | traceback wouldn't work well without some complicated hoopla to save, |
|
30 | 30 | reset and restore the tty state. |
|
31 | 31 | |
|
32 | 32 | - The evaluation of the NAME.NAME... form may cause arbitrary |
|
33 | 33 | application defined code to be executed if an object with a |
|
34 | 34 | ``__getattr__`` hook is found. Since it is the responsibility of the |
|
35 | 35 | application (or the user) to enable this feature, I consider this an |
|
36 | 36 | acceptable risk. More complicated expressions (e.g. function calls or |
|
37 | 37 | indexing operations) are *not* evaluated. |
|
38 | 38 | |
|
39 | 39 | - GNU readline is also used by the built-in functions input() and |
|
40 | 40 | raw_input(), and thus these also benefit/suffer from the completer |
|
41 | 41 | features. Clearly an interactive application can benefit by |
|
42 | 42 | specifying its own completer function and using raw_input() for all |
|
43 | 43 | its input. |
|
44 | 44 | |
|
45 | 45 | - When the original stdin is not a tty device, GNU readline is never |
|
46 | 46 | used, and this module (and the readline module) are silently inactive. |
|
47 | 47 | """ |
|
48 | 48 | |
|
49 | 49 | #***************************************************************************** |
|
50 | 50 | # |
|
51 | 51 | # Since this file is essentially a minimally modified copy of the rlcompleter |
|
52 | 52 | # module which is part of the standard Python distribution, I assume that the |
|
53 | 53 | # proper procedure is to maintain its copyright as belonging to the Python |
|
54 | 54 | # Software Foundation (in addition to my own, for all new code). |
|
55 | 55 | # |
|
56 | 56 | # Copyright (C) 2008 IPython Development Team |
|
57 | 57 | # Copyright (C) 2001 Fernando Perez. <fperez@colorado.edu> |
|
58 | 58 | # Copyright (C) 2001 Python Software Foundation, www.python.org |
|
59 | 59 | # |
|
60 | 60 | # Distributed under the terms of the BSD License. The full license is in |
|
61 | 61 | # the file COPYING, distributed as part of this software. |
|
62 | 62 | # |
|
63 | 63 | #***************************************************************************** |
|
64 | 64 | |
|
65 | 65 | #----------------------------------------------------------------------------- |
|
66 | 66 | # Imports |
|
67 | 67 | #----------------------------------------------------------------------------- |
|
68 | 68 | |
|
69 | 69 | import __builtin__ |
|
70 | 70 | import __main__ |
|
71 | 71 | import glob |
|
72 | 72 | import inspect |
|
73 | 73 | import itertools |
|
74 | 74 | import keyword |
|
75 | 75 | import os |
|
76 | 76 | import re |
|
77 | 77 | import sys |
|
78 | 78 | |
|
79 | 79 | from IPython.config.configurable import Configurable |
|
80 | 80 | from IPython.core.error import TryNext |
|
81 | 81 | from IPython.core.inputsplitter import ESC_MAGIC |
|
82 | 82 | from IPython.utils import generics |
|
83 | 83 | from IPython.utils import io |
|
84 | 84 | from IPython.utils.dir2 import dir2 |
|
85 | 85 | from IPython.utils.process import arg_split |
|
86 | 86 | from IPython.utils.traitlets import CBool, Enum |
|
87 | 87 | |
|
88 | 88 | #----------------------------------------------------------------------------- |
|
89 | 89 | # Globals |
|
90 | 90 | #----------------------------------------------------------------------------- |
|
91 | 91 | |
|
92 | 92 | # Public API |
|
93 | 93 | __all__ = ['Completer','IPCompleter'] |
|
94 | 94 | |
|
95 | 95 | if sys.platform == 'win32': |
|
96 | 96 | PROTECTABLES = ' ' |
|
97 | 97 | else: |
|
98 | 98 | PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&' |
|
99 | 99 | |
|
100 | 100 | #----------------------------------------------------------------------------- |
|
101 | 101 | # Main functions and classes |
|
102 | 102 | #----------------------------------------------------------------------------- |
|
103 | 103 | |
|
104 | 104 | def has_open_quotes(s): |
|
105 | 105 | """Return whether a string has open quotes. |
|
106 | 106 | |
|
107 | 107 | This simply counts whether the number of quote characters of either type in |
|
108 | 108 | the string is odd. |
|
109 | 109 | |
|
110 | 110 | Returns |
|
111 | 111 | ------- |
|
112 | 112 | If there is an open quote, the quote character is returned. Else, return |
|
113 | 113 | False. |
|
114 | 114 | """ |
|
115 | 115 | # We check " first, then ', so complex cases with nested quotes will get |
|
116 | 116 | # the " to take precedence. |
|
117 | 117 | if s.count('"') % 2: |
|
118 | 118 | return '"' |
|
119 | 119 | elif s.count("'") % 2: |
|
120 | 120 | return "'" |
|
121 | 121 | else: |
|
122 | 122 | return False |
|
123 | 123 | |
|
124 | 124 | |
|
125 | 125 | def protect_filename(s): |
|
126 | 126 | """Escape a string to protect certain characters.""" |
|
127 | 127 | |
|
128 | 128 | return "".join([(ch in PROTECTABLES and '\\' + ch or ch) |
|
129 | 129 | for ch in s]) |
|
130 | 130 | |
|
131 | 131 | def expand_user(path): |
|
132 | 132 | """Expand '~'-style usernames in strings. |
|
133 | 133 | |
|
134 | 134 | This is similar to :func:`os.path.expanduser`, but it computes and returns |
|
135 | 135 | extra information that will be useful if the input was being used in |
|
136 | 136 | computing completions, and you wish to return the completions with the |
|
137 | 137 | original '~' instead of its expanded value. |
|
138 | 138 | |
|
139 | 139 | Parameters |
|
140 | 140 | ---------- |
|
141 | 141 | path : str |
|
142 | 142 | String to be expanded. If no ~ is present, the output is the same as the |
|
143 | 143 | input. |
|
144 | 144 | |
|
145 | 145 | Returns |
|
146 | 146 | ------- |
|
147 | 147 | newpath : str |
|
148 | 148 | Result of ~ expansion in the input path. |
|
149 | 149 | tilde_expand : bool |
|
150 | 150 | Whether any expansion was performed or not. |
|
151 | 151 | tilde_val : str |
|
152 | 152 | The value that ~ was replaced with. |
|
153 | 153 | """ |
|
154 | 154 | # Default values |
|
155 | 155 | tilde_expand = False |
|
156 | 156 | tilde_val = '' |
|
157 | 157 | newpath = path |
|
158 | 158 | |
|
159 | 159 | if path.startswith('~'): |
|
160 | 160 | tilde_expand = True |
|
161 | 161 | rest = len(path)-1 |
|
162 | 162 | newpath = os.path.expanduser(path) |
|
163 | 163 | if rest: |
|
164 | 164 | tilde_val = newpath[:-rest] |
|
165 | 165 | else: |
|
166 | 166 | tilde_val = newpath |
|
167 | 167 | |
|
168 | 168 | return newpath, tilde_expand, tilde_val |
|
169 | 169 | |
|
170 | 170 | |
|
171 | 171 | def compress_user(path, tilde_expand, tilde_val): |
|
172 | 172 | """Does the opposite of expand_user, with its outputs. |
|
173 | 173 | """ |
|
174 | 174 | if tilde_expand: |
|
175 | 175 | return path.replace(tilde_val, '~') |
|
176 | 176 | else: |
|
177 | 177 | return path |
|
178 | 178 | |
|
179 | 179 | |
|
180 | 180 | class Bunch(object): pass |
|
181 | 181 | |
|
182 | 182 | |
|
183 | 183 | DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?' |
|
184 | 184 | GREEDY_DELIMS = ' =\r\n' |
|
185 | 185 | |
|
186 | 186 | |
|
187 | 187 | class CompletionSplitter(object): |
|
188 | 188 | """An object to split an input line in a manner similar to readline. |
|
189 | 189 | |
|
190 | 190 | By having our own implementation, we can expose readline-like completion in |
|
191 | 191 | a uniform manner to all frontends. This object only needs to be given the |
|
192 | 192 | line of text to be split and the cursor position on said line, and it |
|
193 | 193 | returns the 'word' to be completed on at the cursor after splitting the |
|
194 | 194 | entire line. |
|
195 | 195 | |
|
196 | 196 | What characters are used as splitting delimiters can be controlled by |
|
197 | 197 | setting the `delims` attribute (this is a property that internally |
|
198 | 198 | automatically builds the necessary regular expression)""" |
|
199 | 199 | |
|
200 | 200 | # Private interface |
|
201 | 201 | |
|
202 | 202 | # A string of delimiter characters. The default value makes sense for |
|
203 | 203 | # IPython's most typical usage patterns. |
|
204 | 204 | _delims = DELIMS |
|
205 | 205 | |
|
206 | 206 | # The expression (a normal string) to be compiled into a regular expression |
|
207 | 207 | # for actual splitting. We store it as an attribute mostly for ease of |
|
208 | 208 | # debugging, since this type of code can be so tricky to debug. |
|
209 | 209 | _delim_expr = None |
|
210 | 210 | |
|
211 | 211 | # The regular expression that does the actual splitting |
|
212 | 212 | _delim_re = None |
|
213 | 213 | |
|
214 | 214 | def __init__(self, delims=None): |
|
215 | 215 | delims = CompletionSplitter._delims if delims is None else delims |
|
216 | 216 | self.delims = delims |
|
217 | 217 | |
|
218 | 218 | @property |
|
219 | 219 | def delims(self): |
|
220 | 220 | """Return the string of delimiter characters.""" |
|
221 | 221 | return self._delims |
|
222 | 222 | |
|
223 | 223 | @delims.setter |
|
224 | 224 | def delims(self, delims): |
|
225 | 225 | """Set the delimiters for line splitting.""" |
|
226 | 226 | expr = '[' + ''.join('\\'+ c for c in delims) + ']' |
|
227 | 227 | self._delim_re = re.compile(expr) |
|
228 | 228 | self._delims = delims |
|
229 | 229 | self._delim_expr = expr |
|
230 | 230 | |
|
231 | 231 | def split_line(self, line, cursor_pos=None): |
|
232 | 232 | """Split a line of text with a cursor at the given position. |
|
233 | 233 | """ |
|
234 | 234 | l = line if cursor_pos is None else line[:cursor_pos] |
|
235 | 235 | return self._delim_re.split(l)[-1] |
|
236 | 236 | |
|
237 | 237 | |
|
238 | 238 | class Completer(Configurable): |
|
239 | 239 | |
|
240 | 240 | greedy = CBool(False, config=True, |
|
241 | 241 | help="""Activate greedy completion |
|
242 | 242 | |
|
243 | 243 | This will enable completion on elements of lists, results of function calls, etc., |
|
244 | 244 | but can be unsafe because the code is actually evaluated on TAB. |
|
245 | 245 | """ |
|
246 | 246 | ) |
|
247 | 247 | |
|
248 | 248 | |
|
249 | 249 | def __init__(self, namespace=None, global_namespace=None, **kwargs): |
|
250 | 250 | """Create a new completer for the command line. |
|
251 | 251 | |
|
252 | 252 | Completer(namespace=ns,global_namespace=ns2) -> completer instance. |
|
253 | 253 | |
|
254 | 254 | If unspecified, the default namespace where completions are performed |
|
255 | 255 | is __main__ (technically, __main__.__dict__). Namespaces should be |
|
256 | 256 | given as dictionaries. |
|
257 | 257 | |
|
258 | 258 | An optional second namespace can be given. This allows the completer |
|
259 | 259 | to handle cases where both the local and global scopes need to be |
|
260 | 260 | distinguished. |
|
261 | 261 | |
|
262 | 262 | Completer instances should be used as the completion mechanism of |
|
263 | 263 | readline via the set_completer() call: |
|
264 | 264 | |
|
265 | 265 | readline.set_completer(Completer(my_namespace).complete) |
|
266 | 266 | """ |
|
267 | 267 | |
|
268 | 268 | # Don't bind to namespace quite yet, but flag whether the user wants a |
|
269 | 269 | # specific namespace or to use __main__.__dict__. This will allow us |
|
270 | 270 | # to bind to __main__.__dict__ at completion time, not now. |
|
271 | 271 | if namespace is None: |
|
272 | 272 | self.use_main_ns = 1 |
|
273 | 273 | else: |
|
274 | 274 | self.use_main_ns = 0 |
|
275 | 275 | self.namespace = namespace |
|
276 | 276 | |
|
277 | 277 | # The global namespace, if given, can be bound directly |
|
278 | 278 | if global_namespace is None: |
|
279 | 279 | self.global_namespace = {} |
|
280 | 280 | else: |
|
281 | 281 | self.global_namespace = global_namespace |
|
282 | 282 | |
|
283 | 283 | super(Completer, self).__init__(**kwargs) |
|
284 | 284 | |
|
285 | 285 | def complete(self, text, state): |
|
286 | 286 | """Return the next possible completion for 'text'. |
|
287 | 287 | |
|
288 | 288 | This is called successively with state == 0, 1, 2, ... until it |
|
289 | 289 | returns None. The completion should begin with 'text'. |
|
290 | 290 | |
|
291 | 291 | """ |
|
292 | 292 | if self.use_main_ns: |
|
293 | 293 | self.namespace = __main__.__dict__ |
|
294 | 294 | |
|
295 | 295 | if state == 0: |
|
296 | 296 | if "." in text: |
|
297 | 297 | self.matches = self.attr_matches(text) |
|
298 | 298 | else: |
|
299 | 299 | self.matches = self.global_matches(text) |
|
300 | 300 | try: |
|
301 | 301 | return self.matches[state] |
|
302 | 302 | except IndexError: |
|
303 | 303 | return None |
|
304 | 304 | |
|
305 | 305 | def global_matches(self, text): |
|
306 | 306 | """Compute matches when text is a simple name. |
|
307 | 307 | |
|
308 | 308 | Return a list of all keywords, built-in functions and names currently |
|
309 | 309 | defined in self.namespace or self.global_namespace that match. |
|
310 | 310 | |
|
311 | 311 | """ |
|
312 | 312 | #print 'Completer->global_matches, txt=%r' % text # dbg |
|
313 | 313 | matches = [] |
|
314 | 314 | match_append = matches.append |
|
315 | 315 | n = len(text) |
|
316 | 316 | for lst in [keyword.kwlist, |
|
317 | 317 | __builtin__.__dict__.keys(), |
|
318 | 318 | self.namespace.keys(), |
|
319 | 319 | self.global_namespace.keys()]: |
|
320 | 320 | for word in lst: |
|
321 | 321 | if word[:n] == text and word != "__builtins__": |
|
322 | 322 | match_append(word) |
|
323 | 323 | return matches |
|
324 | 324 | |
|
325 | 325 | def attr_matches(self, text): |
|
326 | 326 | """Compute matches when text contains a dot. |
|
327 | 327 | |
|
328 | 328 | Assuming the text is of the form NAME.NAME....[NAME], and is |
|
329 | 329 | evaluatable in self.namespace or self.global_namespace, it will be |
|
330 | 330 | evaluated and its attributes (as revealed by dir()) are used as |
|
331 | 331 | possible completions. (For class instances, class members are are |
|
332 | 332 | also considered.) |
|
333 | 333 | |
|
334 | 334 | WARNING: this can still invoke arbitrary C code, if an object |
|
335 | 335 | with a __getattr__ hook is evaluated. |
|
336 | 336 | |
|
337 | 337 | """ |
|
338 | 338 | |
|
339 | 339 | #io.rprint('Completer->attr_matches, txt=%r' % text) # dbg |
|
340 | 340 | # Another option, seems to work great. Catches things like ''.<tab> |
|
341 | 341 | m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) |
|
342 | 342 | |
|
343 | 343 | if m: |
|
344 | 344 | expr, attr = m.group(1, 3) |
|
345 | 345 | elif self.greedy: |
|
346 | 346 | m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer) |
|
347 | 347 | if not m2: |
|
348 | 348 | return [] |
|
349 | 349 | expr, attr = m2.group(1,2) |
|
350 | 350 | else: |
|
351 | 351 | return [] |
|
352 | 352 | |
|
353 | 353 | try: |
|
354 | 354 | obj = eval(expr, self.namespace) |
|
355 | 355 | except: |
|
356 | 356 | try: |
|
357 | 357 | obj = eval(expr, self.global_namespace) |
|
358 | 358 | except: |
|
359 | 359 | return [] |
|
360 | 360 | |
|
361 | 361 | if self.limit_to__all__ and hasattr(obj, '__all__'): |
|
362 | 362 | words = get__all__entries(obj) |
|
363 | 363 | else: |
|
364 | 364 | words = dir2(obj) |
|
365 | 365 | |
|
366 | 366 | try: |
|
367 | 367 | words = generics.complete_object(obj, words) |
|
368 | 368 | except TryNext: |
|
369 | 369 | pass |
|
370 | 370 | except Exception: |
|
371 | 371 | # Silence errors from completion function |
|
372 | 372 | #raise # dbg |
|
373 | 373 | pass |
|
374 | 374 | # Build match list to return |
|
375 | 375 | n = len(attr) |
|
376 | 376 | res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ] |
|
377 | 377 | return res |
|
378 | 378 | |
|
379 | 379 | |
|
380 | 380 | def get__all__entries(obj): |
|
381 | 381 | """returns the strings in the __all__ attribute""" |
|
382 | 382 | try: |
|
383 | 383 | words = getattr(obj, '__all__') |
|
384 | 384 | except: |
|
385 | 385 | return [] |
|
386 | 386 | |
|
387 | 387 | return [w for w in words if isinstance(w, basestring)] |
|
388 | 388 | |
|
389 | 389 | |
|
390 | 390 | class IPCompleter(Completer): |
|
391 | 391 | """Extension of the completer class with IPython-specific features""" |
|
392 | 392 | |
|
393 | 393 | def _greedy_changed(self, name, old, new): |
|
394 | 394 | """update the splitter and readline delims when greedy is changed""" |
|
395 | 395 | if new: |
|
396 | 396 | self.splitter.delims = GREEDY_DELIMS |
|
397 | 397 | else: |
|
398 | 398 | self.splitter.delims = DELIMS |
|
399 | 399 | |
|
400 | 400 | if self.readline: |
|
401 | 401 | self.readline.set_completer_delims(self.splitter.delims) |
|
402 | 402 | |
|
403 | 403 | merge_completions = CBool(True, config=True, |
|
404 | 404 | help="""Whether to merge completion results into a single list |
|
405 | 405 | |
|
406 | 406 | If False, only the completion results from the first non-empty |
|
407 | 407 | completer will be returned. |
|
408 | 408 | """ |
|
409 | 409 | ) |
|
410 | 410 | omit__names = Enum((0,1,2), default_value=2, config=True, |
|
411 | 411 | help="""Instruct the completer to omit private method names |
|
412 | 412 | |
|
413 | 413 | Specifically, when completing on ``object.<tab>``. |
|
414 | 414 | |
|
415 | 415 | When 2 [default]: all names that start with '_' will be excluded. |
|
416 | 416 | |
|
417 | 417 | When 1: all 'magic' names (``__foo__``) will be excluded. |
|
418 | 418 | |
|
419 | 419 | When 0: nothing will be excluded. |
|
420 | 420 | """ |
|
421 | 421 | ) |
|
422 | 422 | limit_to__all__ = CBool(default_value=False, config=True, |
|
423 | 423 | help="""Instruct the completer to use __all__ for the completion |
|
424 | 424 | |
|
425 | 425 | Specifically, when completing on ``object.<tab>``. |
|
426 | 426 | |
|
427 | 427 | When True: only those names in obj.__all__ will be included. |
|
428 | 428 | |
|
429 | 429 | When False [default]: the __all__ attribute is ignored |
|
430 | 430 | """ |
|
431 | 431 | ) |
|
432 | 432 | |
|
433 | 433 | def __init__(self, shell=None, namespace=None, global_namespace=None, |
|
434 |
|
|
|
435 | config=None, **kwargs): | |
|
434 | use_readline=True, config=None, **kwargs): | |
|
436 | 435 | """IPCompleter() -> completer |
|
437 | 436 | |
|
438 | 437 | Return a completer object suitable for use by the readline library |
|
439 | 438 | via readline.set_completer(). |
|
440 | 439 | |
|
441 | 440 | Inputs: |
|
442 | 441 | |
|
443 | 442 | - shell: a pointer to the ipython shell itself. This is needed |
|
444 | 443 | because this completer knows about magic functions, and those can |
|
445 | 444 | only be accessed via the ipython instance. |
|
446 | 445 | |
|
447 | 446 | - namespace: an optional dict where completions are performed. |
|
448 | 447 | |
|
449 | 448 | - global_namespace: secondary optional dict for completions, to |
|
450 | 449 | handle cases (such as IPython embedded inside functions) where |
|
451 | 450 | both Python scopes are visible. |
|
452 | 451 | |
|
453 | - If alias_table is supplied, it should be a dictionary of aliases | |
|
454 | to complete. | |
|
455 | ||
|
456 | 452 | use_readline : bool, optional |
|
457 | 453 | If true, use the readline library. This completer can still function |
|
458 | 454 | without readline, though in that case callers must provide some extra |
|
459 | 455 | information on each call about the current line.""" |
|
460 | 456 | |
|
461 | 457 | self.magic_escape = ESC_MAGIC |
|
462 | 458 | self.splitter = CompletionSplitter() |
|
463 | 459 | |
|
464 | 460 | # Readline configuration, only used by the rlcompleter method. |
|
465 | 461 | if use_readline: |
|
466 | 462 | # We store the right version of readline so that later code |
|
467 | 463 | import IPython.utils.rlineimpl as readline |
|
468 | 464 | self.readline = readline |
|
469 | 465 | else: |
|
470 | 466 | self.readline = None |
|
471 | 467 | |
|
472 | 468 | # _greedy_changed() depends on splitter and readline being defined: |
|
473 | 469 | Completer.__init__(self, namespace=namespace, global_namespace=global_namespace, |
|
474 | 470 | config=config, **kwargs) |
|
475 | 471 | |
|
476 | 472 | # List where completion matches will be stored |
|
477 | 473 | self.matches = [] |
|
478 | 474 | self.shell = shell |
|
479 | if alias_table is None: | |
|
480 | alias_table = {} | |
|
481 | self.alias_table = alias_table | |
|
482 | 475 | # Regexp to split filenames with spaces in them |
|
483 | 476 | self.space_name_re = re.compile(r'([^\\] )') |
|
484 | 477 | # Hold a local ref. to glob.glob for speed |
|
485 | 478 | self.glob = glob.glob |
|
486 | 479 | |
|
487 | 480 | # Determine if we are running on 'dumb' terminals, like (X)Emacs |
|
488 | 481 | # buffers, to avoid completion problems. |
|
489 | 482 | term = os.environ.get('TERM','xterm') |
|
490 | 483 | self.dumb_terminal = term in ['dumb','emacs'] |
|
491 | 484 | |
|
492 | 485 | # Special handling of backslashes needed in win32 platforms |
|
493 | 486 | if sys.platform == "win32": |
|
494 | 487 | self.clean_glob = self._clean_glob_win32 |
|
495 | 488 | else: |
|
496 | 489 | self.clean_glob = self._clean_glob |
|
497 | 490 | |
|
498 | 491 | #regexp to parse docstring for function signature |
|
499 | 492 | self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*') |
|
500 | 493 | self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)') |
|
501 | 494 | #use this if positional argument name is also needed |
|
502 | 495 | #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)') |
|
503 | 496 | |
|
504 | 497 | # All active matcher routines for completion |
|
505 | 498 | self.matchers = [self.python_matches, |
|
506 | 499 | self.file_matches, |
|
507 | 500 | self.magic_matches, |
|
508 | self.alias_matches, | |
|
509 | 501 | self.python_func_kw_matches, |
|
510 | 502 | ] |
|
511 | 503 | |
|
512 | 504 | def all_completions(self, text): |
|
513 | 505 | """ |
|
514 | 506 | Wrapper around the complete method for the benefit of emacs |
|
515 | 507 | and pydb. |
|
516 | 508 | """ |
|
517 | 509 | return self.complete(text)[1] |
|
518 | 510 | |
|
519 | 511 | def _clean_glob(self,text): |
|
520 | 512 | return self.glob("%s*" % text) |
|
521 | 513 | |
|
522 | 514 | def _clean_glob_win32(self,text): |
|
523 | 515 | return [f.replace("\\","/") |
|
524 | 516 | for f in self.glob("%s*" % text)] |
|
525 | 517 | |
|
526 | 518 | def file_matches(self, text): |
|
527 | 519 | """Match filenames, expanding ~USER type strings. |
|
528 | 520 | |
|
529 | 521 | Most of the seemingly convoluted logic in this completer is an |
|
530 | 522 | attempt to handle filenames with spaces in them. And yet it's not |
|
531 | 523 | quite perfect, because Python's readline doesn't expose all of the |
|
532 | 524 | GNU readline details needed for this to be done correctly. |
|
533 | 525 | |
|
534 | 526 | For a filename with a space in it, the printed completions will be |
|
535 | 527 | only the parts after what's already been typed (instead of the |
|
536 | 528 | full completions, as is normally done). I don't think with the |
|
537 | 529 | current (as of Python 2.3) Python readline it's possible to do |
|
538 | 530 | better.""" |
|
539 | 531 | |
|
540 | 532 | #io.rprint('Completer->file_matches: <%r>' % text) # dbg |
|
541 | 533 | |
|
542 | 534 | # chars that require escaping with backslash - i.e. chars |
|
543 | 535 | # that readline treats incorrectly as delimiters, but we |
|
544 | 536 | # don't want to treat as delimiters in filename matching |
|
545 | 537 | # when escaped with backslash |
|
546 | 538 | if text.startswith('!'): |
|
547 | 539 | text = text[1:] |
|
548 | 540 | text_prefix = '!' |
|
549 | 541 | else: |
|
550 | 542 | text_prefix = '' |
|
551 | 543 | |
|
552 | 544 | text_until_cursor = self.text_until_cursor |
|
553 | 545 | # track strings with open quotes |
|
554 | 546 | open_quotes = has_open_quotes(text_until_cursor) |
|
555 | 547 | |
|
556 | 548 | if '(' in text_until_cursor or '[' in text_until_cursor: |
|
557 | 549 | lsplit = text |
|
558 | 550 | else: |
|
559 | 551 | try: |
|
560 | 552 | # arg_split ~ shlex.split, but with unicode bugs fixed by us |
|
561 | 553 | lsplit = arg_split(text_until_cursor)[-1] |
|
562 | 554 | except ValueError: |
|
563 | 555 | # typically an unmatched ", or backslash without escaped char. |
|
564 | 556 | if open_quotes: |
|
565 | 557 | lsplit = text_until_cursor.split(open_quotes)[-1] |
|
566 | 558 | else: |
|
567 | 559 | return [] |
|
568 | 560 | except IndexError: |
|
569 | 561 | # tab pressed on empty line |
|
570 | 562 | lsplit = "" |
|
571 | 563 | |
|
572 | 564 | if not open_quotes and lsplit != protect_filename(lsplit): |
|
573 | 565 | # if protectables are found, do matching on the whole escaped name |
|
574 | 566 | has_protectables = True |
|
575 | 567 | text0,text = text,lsplit |
|
576 | 568 | else: |
|
577 | 569 | has_protectables = False |
|
578 | 570 | text = os.path.expanduser(text) |
|
579 | 571 | |
|
580 | 572 | if text == "": |
|
581 | 573 | return [text_prefix + protect_filename(f) for f in self.glob("*")] |
|
582 | 574 | |
|
583 | 575 | # Compute the matches from the filesystem |
|
584 | 576 | m0 = self.clean_glob(text.replace('\\','')) |
|
585 | 577 | |
|
586 | 578 | if has_protectables: |
|
587 | 579 | # If we had protectables, we need to revert our changes to the |
|
588 | 580 | # beginning of filename so that we don't double-write the part |
|
589 | 581 | # of the filename we have so far |
|
590 | 582 | len_lsplit = len(lsplit) |
|
591 | 583 | matches = [text_prefix + text0 + |
|
592 | 584 | protect_filename(f[len_lsplit:]) for f in m0] |
|
593 | 585 | else: |
|
594 | 586 | if open_quotes: |
|
595 | 587 | # if we have a string with an open quote, we don't need to |
|
596 | 588 | # protect the names at all (and we _shouldn't_, as it |
|
597 | 589 | # would cause bugs when the filesystem call is made). |
|
598 | 590 | matches = m0 |
|
599 | 591 | else: |
|
600 | 592 | matches = [text_prefix + |
|
601 | 593 | protect_filename(f) for f in m0] |
|
602 | 594 | |
|
603 | 595 | #io.rprint('mm', matches) # dbg |
|
604 | 596 | |
|
605 | 597 | # Mark directories in input list by appending '/' to their names. |
|
606 | 598 | matches = [x+'/' if os.path.isdir(x) else x for x in matches] |
|
607 | 599 | return matches |
|
608 | 600 | |
|
609 | 601 | def magic_matches(self, text): |
|
610 | 602 | """Match magics""" |
|
611 | 603 | #print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg |
|
612 | 604 | # Get all shell magics now rather than statically, so magics loaded at |
|
613 | 605 | # runtime show up too. |
|
614 | 606 | lsm = self.shell.magics_manager.lsmagic() |
|
615 | 607 | line_magics = lsm['line'] |
|
616 | 608 | cell_magics = lsm['cell'] |
|
617 | 609 | pre = self.magic_escape |
|
618 | 610 | pre2 = pre+pre |
|
619 | 611 | |
|
620 | 612 | # Completion logic: |
|
621 | 613 | # - user gives %%: only do cell magics |
|
622 | 614 | # - user gives %: do both line and cell magics |
|
623 | 615 | # - no prefix: do both |
|
624 | 616 | # In other words, line magics are skipped if the user gives %% explicitly |
|
625 | 617 | bare_text = text.lstrip(pre) |
|
626 | 618 | comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)] |
|
627 | 619 | if not text.startswith(pre2): |
|
628 | 620 | comp += [ pre+m for m in line_magics if m.startswith(bare_text)] |
|
629 | 621 | return comp |
|
630 | 622 | |
|
631 | def alias_matches(self, text): | |
|
632 | """Match internal system aliases""" | |
|
633 | #print 'Completer->alias_matches:',text,'lb',self.text_until_cursor # dbg | |
|
634 | ||
|
635 | # if we are not in the first 'item', alias matching | |
|
636 | # doesn't make sense - unless we are starting with 'sudo' command. | |
|
637 | main_text = self.text_until_cursor.lstrip() | |
|
638 | if ' ' in main_text and not main_text.startswith('sudo'): | |
|
639 | return [] | |
|
640 | text = os.path.expanduser(text) | |
|
641 | aliases = self.alias_table.keys() | |
|
642 | if text == '': | |
|
643 | return aliases | |
|
644 | else: | |
|
645 | return [a for a in aliases if a.startswith(text)] | |
|
646 | ||
|
647 | 623 | def python_matches(self,text): |
|
648 | 624 | """Match attributes or global python names""" |
|
649 | 625 | |
|
650 | 626 | #io.rprint('Completer->python_matches, txt=%r' % text) # dbg |
|
651 | 627 | if "." in text: |
|
652 | 628 | try: |
|
653 | 629 | matches = self.attr_matches(text) |
|
654 | 630 | if text.endswith('.') and self.omit__names: |
|
655 | 631 | if self.omit__names == 1: |
|
656 | 632 | # true if txt is _not_ a __ name, false otherwise: |
|
657 | 633 | no__name = (lambda txt: |
|
658 | 634 | re.match(r'.*\.__.*?__',txt) is None) |
|
659 | 635 | else: |
|
660 | 636 | # true if txt is _not_ a _ name, false otherwise: |
|
661 | 637 | no__name = (lambda txt: |
|
662 | 638 | re.match(r'.*\._.*?',txt) is None) |
|
663 | 639 | matches = filter(no__name, matches) |
|
664 | 640 | except NameError: |
|
665 | 641 | # catches <undefined attributes>.<tab> |
|
666 | 642 | matches = [] |
|
667 | 643 | else: |
|
668 | 644 | matches = self.global_matches(text) |
|
669 | 645 | |
|
670 | 646 | return matches |
|
671 | 647 | |
|
672 | 648 | def _default_arguments_from_docstring(self, doc): |
|
673 | 649 | """Parse the first line of docstring for call signature. |
|
674 | 650 | |
|
675 | 651 | Docstring should be of the form 'min(iterable[, key=func])\n'. |
|
676 | 652 | It can also parse cython docstring of the form |
|
677 | 653 | 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'. |
|
678 | 654 | """ |
|
679 | 655 | if doc is None: |
|
680 | 656 | return [] |
|
681 | 657 | |
|
682 | 658 | #care only the firstline |
|
683 | 659 | line = doc.lstrip().splitlines()[0] |
|
684 | 660 | |
|
685 | 661 | #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*') |
|
686 | 662 | #'min(iterable[, key=func])\n' -> 'iterable[, key=func]' |
|
687 | 663 | sig = self.docstring_sig_re.search(line) |
|
688 | 664 | if sig is None: |
|
689 | 665 | return [] |
|
690 | 666 | # iterable[, key=func]' -> ['iterable[' ,' key=func]'] |
|
691 | 667 | sig = sig.groups()[0].split(',') |
|
692 | 668 | ret = [] |
|
693 | 669 | for s in sig: |
|
694 | 670 | #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)') |
|
695 | 671 | ret += self.docstring_kwd_re.findall(s) |
|
696 | 672 | return ret |
|
697 | 673 | |
|
698 | 674 | def _default_arguments(self, obj): |
|
699 | 675 | """Return the list of default arguments of obj if it is callable, |
|
700 | 676 | or empty list otherwise.""" |
|
701 | 677 | call_obj = obj |
|
702 | 678 | ret = [] |
|
703 | 679 | if inspect.isbuiltin(obj): |
|
704 | 680 | pass |
|
705 | 681 | elif not (inspect.isfunction(obj) or inspect.ismethod(obj)): |
|
706 | 682 | if inspect.isclass(obj): |
|
707 | 683 | #for cython embededsignature=True the constructor docstring |
|
708 | 684 | #belongs to the object itself not __init__ |
|
709 | 685 | ret += self._default_arguments_from_docstring( |
|
710 | 686 | getattr(obj, '__doc__', '')) |
|
711 | 687 | # for classes, check for __init__,__new__ |
|
712 | 688 | call_obj = (getattr(obj, '__init__', None) or |
|
713 | 689 | getattr(obj, '__new__', None)) |
|
714 | 690 | # for all others, check if they are __call__able |
|
715 | 691 | elif hasattr(obj, '__call__'): |
|
716 | 692 | call_obj = obj.__call__ |
|
717 | 693 | |
|
718 | 694 | ret += self._default_arguments_from_docstring( |
|
719 | 695 | getattr(call_obj, '__doc__', '')) |
|
720 | 696 | |
|
721 | 697 | try: |
|
722 | 698 | args,_,_1,defaults = inspect.getargspec(call_obj) |
|
723 | 699 | if defaults: |
|
724 | 700 | ret+=args[-len(defaults):] |
|
725 | 701 | except TypeError: |
|
726 | 702 | pass |
|
727 | 703 | |
|
728 | 704 | return list(set(ret)) |
|
729 | 705 | |
|
730 | 706 | def python_func_kw_matches(self,text): |
|
731 | 707 | """Match named parameters (kwargs) of the last open function""" |
|
732 | 708 | |
|
733 | 709 | if "." in text: # a parameter cannot be dotted |
|
734 | 710 | return [] |
|
735 | 711 | try: regexp = self.__funcParamsRegex |
|
736 | 712 | except AttributeError: |
|
737 | 713 | regexp = self.__funcParamsRegex = re.compile(r''' |
|
738 | 714 | '.*?(?<!\\)' | # single quoted strings or |
|
739 | 715 | ".*?(?<!\\)" | # double quoted strings or |
|
740 | 716 | \w+ | # identifier |
|
741 | 717 | \S # other characters |
|
742 | 718 | ''', re.VERBOSE | re.DOTALL) |
|
743 | 719 | # 1. find the nearest identifier that comes before an unclosed |
|
744 | 720 | # parenthesis before the cursor |
|
745 | 721 | # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo" |
|
746 | 722 | tokens = regexp.findall(self.text_until_cursor) |
|
747 | 723 | tokens.reverse() |
|
748 | 724 | iterTokens = iter(tokens); openPar = 0 |
|
749 | 725 | |
|
750 | 726 | for token in iterTokens: |
|
751 | 727 | if token == ')': |
|
752 | 728 | openPar -= 1 |
|
753 | 729 | elif token == '(': |
|
754 | 730 | openPar += 1 |
|
755 | 731 | if openPar > 0: |
|
756 | 732 | # found the last unclosed parenthesis |
|
757 | 733 | break |
|
758 | 734 | else: |
|
759 | 735 | return [] |
|
760 | 736 | # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) |
|
761 | 737 | ids = [] |
|
762 | 738 | isId = re.compile(r'\w+$').match |
|
763 | 739 | |
|
764 | 740 | while True: |
|
765 | 741 | try: |
|
766 | 742 | ids.append(next(iterTokens)) |
|
767 | 743 | if not isId(ids[-1]): |
|
768 | 744 | ids.pop(); break |
|
769 | 745 | if not next(iterTokens) == '.': |
|
770 | 746 | break |
|
771 | 747 | except StopIteration: |
|
772 | 748 | break |
|
773 | 749 | # lookup the candidate callable matches either using global_matches |
|
774 | 750 | # or attr_matches for dotted names |
|
775 | 751 | if len(ids) == 1: |
|
776 | 752 | callableMatches = self.global_matches(ids[0]) |
|
777 | 753 | else: |
|
778 | 754 | callableMatches = self.attr_matches('.'.join(ids[::-1])) |
|
779 | 755 | argMatches = [] |
|
780 | 756 | for callableMatch in callableMatches: |
|
781 | 757 | try: |
|
782 | 758 | namedArgs = self._default_arguments(eval(callableMatch, |
|
783 | 759 | self.namespace)) |
|
784 | 760 | except: |
|
785 | 761 | continue |
|
786 | 762 | |
|
787 | 763 | for namedArg in namedArgs: |
|
788 | 764 | if namedArg.startswith(text): |
|
789 | 765 | argMatches.append("%s=" %namedArg) |
|
790 | 766 | return argMatches |
|
791 | 767 | |
|
792 | 768 | def dispatch_custom_completer(self, text): |
|
793 | 769 | #io.rprint("Custom! '%s' %s" % (text, self.custom_completers)) # dbg |
|
794 | 770 | line = self.line_buffer |
|
795 | 771 | if not line.strip(): |
|
796 | 772 | return None |
|
797 | 773 | |
|
798 | 774 | # Create a little structure to pass all the relevant information about |
|
799 | 775 | # the current completion to any custom completer. |
|
800 | 776 | event = Bunch() |
|
801 | 777 | event.line = line |
|
802 | 778 | event.symbol = text |
|
803 | 779 | cmd = line.split(None,1)[0] |
|
804 | 780 | event.command = cmd |
|
805 | 781 | event.text_until_cursor = self.text_until_cursor |
|
806 | 782 | |
|
807 | 783 | #print "\ncustom:{%s]\n" % event # dbg |
|
808 | 784 | |
|
809 | 785 | # for foo etc, try also to find completer for %foo |
|
810 | 786 | if not cmd.startswith(self.magic_escape): |
|
811 | 787 | try_magic = self.custom_completers.s_matches( |
|
812 | 788 | self.magic_escape + cmd) |
|
813 | 789 | else: |
|
814 | 790 | try_magic = [] |
|
815 | 791 | |
|
816 | 792 | for c in itertools.chain(self.custom_completers.s_matches(cmd), |
|
817 | 793 | try_magic, |
|
818 | 794 | self.custom_completers.flat_matches(self.text_until_cursor)): |
|
819 | 795 | #print "try",c # dbg |
|
820 | 796 | try: |
|
821 | 797 | res = c(event) |
|
822 | 798 | if res: |
|
823 | 799 | # first, try case sensitive match |
|
824 | 800 | withcase = [r for r in res if r.startswith(text)] |
|
825 | 801 | if withcase: |
|
826 | 802 | return withcase |
|
827 | 803 | # if none, then case insensitive ones are ok too |
|
828 | 804 | text_low = text.lower() |
|
829 | 805 | return [r for r in res if r.lower().startswith(text_low)] |
|
830 | 806 | except TryNext: |
|
831 | 807 | pass |
|
832 | 808 | |
|
833 | 809 | return None |
|
834 | 810 | |
|
835 | 811 | def complete(self, text=None, line_buffer=None, cursor_pos=None): |
|
836 | 812 | """Find completions for the given text and line context. |
|
837 | 813 | |
|
838 | 814 | This is called successively with state == 0, 1, 2, ... until it |
|
839 | 815 | returns None. The completion should begin with 'text'. |
|
840 | 816 | |
|
841 | 817 | Note that both the text and the line_buffer are optional, but at least |
|
842 | 818 | one of them must be given. |
|
843 | 819 | |
|
844 | 820 | Parameters |
|
845 | 821 | ---------- |
|
846 | 822 | text : string, optional |
|
847 | 823 | Text to perform the completion on. If not given, the line buffer |
|
848 | 824 | is split using the instance's CompletionSplitter object. |
|
849 | 825 | |
|
850 | 826 | line_buffer : string, optional |
|
851 | 827 | If not given, the completer attempts to obtain the current line |
|
852 | 828 | buffer via readline. This keyword allows clients which are |
|
853 | 829 | requesting for text completions in non-readline contexts to inform |
|
854 | 830 | the completer of the entire text. |
|
855 | 831 | |
|
856 | 832 | cursor_pos : int, optional |
|
857 | 833 | Index of the cursor in the full line buffer. Should be provided by |
|
858 | 834 | remote frontends where kernel has no access to frontend state. |
|
859 | 835 | |
|
860 | 836 | Returns |
|
861 | 837 | ------- |
|
862 | 838 | text : str |
|
863 | 839 | Text that was actually used in the completion. |
|
864 | 840 | |
|
865 | 841 | matches : list |
|
866 | 842 | A list of completion matches. |
|
867 | 843 | """ |
|
868 | 844 | #io.rprint('\nCOMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg |
|
869 | 845 | |
|
870 | 846 | # if the cursor position isn't given, the only sane assumption we can |
|
871 | 847 | # make is that it's at the end of the line (the common case) |
|
872 | 848 | if cursor_pos is None: |
|
873 | 849 | cursor_pos = len(line_buffer) if text is None else len(text) |
|
874 | 850 | |
|
875 | 851 | # if text is either None or an empty string, rely on the line buffer |
|
876 | 852 | if not text: |
|
877 | 853 | text = self.splitter.split_line(line_buffer, cursor_pos) |
|
878 | 854 | |
|
879 | 855 | # If no line buffer is given, assume the input text is all there was |
|
880 | 856 | if line_buffer is None: |
|
881 | 857 | line_buffer = text |
|
882 | 858 | |
|
883 | 859 | self.line_buffer = line_buffer |
|
884 | 860 | self.text_until_cursor = self.line_buffer[:cursor_pos] |
|
885 | 861 | #io.rprint('COMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg |
|
886 | 862 | |
|
887 | 863 | # Start with a clean slate of completions |
|
888 | 864 | self.matches[:] = [] |
|
889 | 865 | custom_res = self.dispatch_custom_completer(text) |
|
890 | 866 | if custom_res is not None: |
|
891 | 867 | # did custom completers produce something? |
|
892 | 868 | self.matches = custom_res |
|
893 | 869 | else: |
|
894 | 870 | # Extend the list of completions with the results of each |
|
895 | 871 | # matcher, so we return results to the user from all |
|
896 | 872 | # namespaces. |
|
897 | 873 | if self.merge_completions: |
|
898 | 874 | self.matches = [] |
|
899 | 875 | for matcher in self.matchers: |
|
900 | 876 | try: |
|
901 | 877 | self.matches.extend(matcher(text)) |
|
902 | 878 | except: |
|
903 | 879 | # Show the ugly traceback if the matcher causes an |
|
904 | 880 | # exception, but do NOT crash the kernel! |
|
905 | 881 | sys.excepthook(*sys.exc_info()) |
|
906 | 882 | else: |
|
907 | 883 | for matcher in self.matchers: |
|
908 | 884 | self.matches = matcher(text) |
|
909 | 885 | if self.matches: |
|
910 | 886 | break |
|
911 | 887 | # FIXME: we should extend our api to return a dict with completions for |
|
912 | 888 | # different types of objects. The rlcomplete() method could then |
|
913 | 889 | # simply collapse the dict into a list for readline, but we'd have |
|
914 | 890 | # richer completion semantics in other evironments. |
|
915 | 891 | self.matches = sorted(set(self.matches)) |
|
916 | 892 | #io.rprint('COMP TEXT, MATCHES: %r, %r' % (text, self.matches)) # dbg |
|
917 | 893 | return text, self.matches |
|
918 | 894 | |
|
919 | 895 | def rlcomplete(self, text, state): |
|
920 | 896 | """Return the state-th possible completion for 'text'. |
|
921 | 897 | |
|
922 | 898 | This is called successively with state == 0, 1, 2, ... until it |
|
923 | 899 | returns None. The completion should begin with 'text'. |
|
924 | 900 | |
|
925 | 901 | Parameters |
|
926 | 902 | ---------- |
|
927 | 903 | text : string |
|
928 | 904 | Text to perform the completion on. |
|
929 | 905 | |
|
930 | 906 | state : int |
|
931 | 907 | Counter used by readline. |
|
932 | 908 | """ |
|
933 | 909 | if state==0: |
|
934 | 910 | |
|
935 | 911 | self.line_buffer = line_buffer = self.readline.get_line_buffer() |
|
936 | 912 | cursor_pos = self.readline.get_endidx() |
|
937 | 913 | |
|
938 | 914 | #io.rprint("\nRLCOMPLETE: %r %r %r" % |
|
939 | 915 | # (text, line_buffer, cursor_pos) ) # dbg |
|
940 | 916 | |
|
941 | 917 | # if there is only a tab on a line with only whitespace, instead of |
|
942 | 918 | # the mostly useless 'do you want to see all million completions' |
|
943 | 919 | # message, just do the right thing and give the user his tab! |
|
944 | 920 | # Incidentally, this enables pasting of tabbed text from an editor |
|
945 | 921 | # (as long as autoindent is off). |
|
946 | 922 | |
|
947 | 923 | # It should be noted that at least pyreadline still shows file |
|
948 | 924 | # completions - is there a way around it? |
|
949 | 925 | |
|
950 | 926 | # don't apply this on 'dumb' terminals, such as emacs buffers, so |
|
951 | 927 | # we don't interfere with their own tab-completion mechanism. |
|
952 | 928 | if not (self.dumb_terminal or line_buffer.strip()): |
|
953 | 929 | self.readline.insert_text('\t') |
|
954 | 930 | sys.stdout.flush() |
|
955 | 931 | return None |
|
956 | 932 | |
|
957 | 933 | # Note: debugging exceptions that may occur in completion is very |
|
958 | 934 | # tricky, because readline unconditionally silences them. So if |
|
959 | 935 | # during development you suspect a bug in the completion code, turn |
|
960 | 936 | # this flag on temporarily by uncommenting the second form (don't |
|
961 | 937 | # flip the value in the first line, as the '# dbg' marker can be |
|
962 | 938 | # automatically detected and is used elsewhere). |
|
963 | 939 | DEBUG = False |
|
964 | 940 | #DEBUG = True # dbg |
|
965 | 941 | if DEBUG: |
|
966 | 942 | try: |
|
967 | 943 | self.complete(text, line_buffer, cursor_pos) |
|
968 | 944 | except: |
|
969 | 945 | import traceback; traceback.print_exc() |
|
970 | 946 | else: |
|
971 | 947 | # The normal production version is here |
|
972 | 948 | |
|
973 | 949 | # This method computes the self.matches array |
|
974 | 950 | self.complete(text, line_buffer, cursor_pos) |
|
975 | 951 | |
|
976 | 952 | try: |
|
977 | 953 | return self.matches[state] |
|
978 | 954 | except IndexError: |
|
979 | 955 | return None |
@@ -1,3160 +1,3154 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 absolute_import |
|
18 | 18 | from __future__ import print_function |
|
19 | 19 | |
|
20 | 20 | import __builtin__ as builtin_mod |
|
21 | 21 | import __future__ |
|
22 | 22 | import abc |
|
23 | 23 | import ast |
|
24 | 24 | import atexit |
|
25 | 25 | import functools |
|
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 | from io import open as io_open |
|
33 | 33 | |
|
34 | 34 | from IPython.config.configurable import SingletonConfigurable |
|
35 | 35 | from IPython.core import debugger, oinspect |
|
36 | 36 | from IPython.core import magic |
|
37 | 37 | from IPython.core import page |
|
38 | 38 | from IPython.core import prefilter |
|
39 | 39 | from IPython.core import shadowns |
|
40 | 40 | from IPython.core import ultratb |
|
41 | 41 | from IPython.core.alias import AliasManager, AliasError |
|
42 | 42 | from IPython.core.autocall import ExitAutocall |
|
43 | 43 | from IPython.core.builtin_trap import BuiltinTrap |
|
44 | 44 | from IPython.core.compilerop import CachingCompiler, check_linecache_ipython |
|
45 | 45 | from IPython.core.display_trap import DisplayTrap |
|
46 | 46 | from IPython.core.displayhook import DisplayHook |
|
47 | 47 | from IPython.core.displaypub import DisplayPublisher |
|
48 | 48 | from IPython.core.error import UsageError |
|
49 | 49 | from IPython.core.extensions import ExtensionManager |
|
50 | 50 | from IPython.core.formatters import DisplayFormatter |
|
51 | 51 | from IPython.core.history import HistoryManager |
|
52 | 52 | from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC, ESC_MAGIC2 |
|
53 | 53 | from IPython.core.logger import Logger |
|
54 | 54 | from IPython.core.macro import Macro |
|
55 | 55 | from IPython.core.payload import PayloadManager |
|
56 | 56 | from IPython.core.prefilter import PrefilterManager |
|
57 | 57 | from IPython.core.profiledir import ProfileDir |
|
58 | 58 | from IPython.core.prompts import PromptManager |
|
59 | 59 | from IPython.lib.latextools import LaTeXTool |
|
60 | 60 | from IPython.testing.skipdoctest import skip_doctest |
|
61 | 61 | from IPython.utils import PyColorize |
|
62 | 62 | from IPython.utils import io |
|
63 | 63 | from IPython.utils import py3compat |
|
64 | 64 | from IPython.utils import openpy |
|
65 | 65 | from IPython.utils.decorators import undoc |
|
66 | 66 | from IPython.utils.io import ask_yes_no |
|
67 | 67 | from IPython.utils.ipstruct import Struct |
|
68 | 68 | from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename |
|
69 | 69 | from IPython.utils.pickleshare import PickleShareDB |
|
70 | 70 | from IPython.utils.process import system, getoutput |
|
71 | 71 | from IPython.utils.strdispatch import StrDispatch |
|
72 | 72 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
73 | 73 | from IPython.utils.text import (format_screen, LSString, SList, |
|
74 | 74 | DollarFormatter) |
|
75 | 75 | from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum, |
|
76 | 76 | List, Unicode, Instance, Type) |
|
77 | 77 | from IPython.utils.warn import warn, error |
|
78 | 78 | import IPython.core.hooks |
|
79 | 79 | |
|
80 | 80 | #----------------------------------------------------------------------------- |
|
81 | 81 | # Globals |
|
82 | 82 | #----------------------------------------------------------------------------- |
|
83 | 83 | |
|
84 | 84 | # compiled regexps for autoindent management |
|
85 | 85 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
86 | 86 | |
|
87 | 87 | #----------------------------------------------------------------------------- |
|
88 | 88 | # Utilities |
|
89 | 89 | #----------------------------------------------------------------------------- |
|
90 | 90 | |
|
91 | 91 | @undoc |
|
92 | 92 | def softspace(file, newvalue): |
|
93 | 93 | """Copied from code.py, to remove the dependency""" |
|
94 | 94 | |
|
95 | 95 | oldvalue = 0 |
|
96 | 96 | try: |
|
97 | 97 | oldvalue = file.softspace |
|
98 | 98 | except AttributeError: |
|
99 | 99 | pass |
|
100 | 100 | try: |
|
101 | 101 | file.softspace = newvalue |
|
102 | 102 | except (AttributeError, TypeError): |
|
103 | 103 | # "attribute-less object" or "read-only attributes" |
|
104 | 104 | pass |
|
105 | 105 | return oldvalue |
|
106 | 106 | |
|
107 | 107 | @undoc |
|
108 | 108 | def no_op(*a, **kw): pass |
|
109 | 109 | |
|
110 | 110 | @undoc |
|
111 | 111 | class NoOpContext(object): |
|
112 | 112 | def __enter__(self): pass |
|
113 | 113 | def __exit__(self, type, value, traceback): pass |
|
114 | 114 | no_op_context = NoOpContext() |
|
115 | 115 | |
|
116 | 116 | class SpaceInInput(Exception): pass |
|
117 | 117 | |
|
118 | 118 | @undoc |
|
119 | 119 | class Bunch: pass |
|
120 | 120 | |
|
121 | 121 | |
|
122 | 122 | def get_default_colors(): |
|
123 | 123 | if sys.platform=='darwin': |
|
124 | 124 | return "LightBG" |
|
125 | 125 | elif os.name=='nt': |
|
126 | 126 | return 'Linux' |
|
127 | 127 | else: |
|
128 | 128 | return 'Linux' |
|
129 | 129 | |
|
130 | 130 | |
|
131 | 131 | class SeparateUnicode(Unicode): |
|
132 | 132 | """A Unicode subclass to validate separate_in, separate_out, etc. |
|
133 | 133 | |
|
134 | 134 | This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'. |
|
135 | 135 | """ |
|
136 | 136 | |
|
137 | 137 | def validate(self, obj, value): |
|
138 | 138 | if value == '0': value = '' |
|
139 | 139 | value = value.replace('\\n','\n') |
|
140 | 140 | return super(SeparateUnicode, self).validate(obj, value) |
|
141 | 141 | |
|
142 | 142 | |
|
143 | 143 | class ReadlineNoRecord(object): |
|
144 | 144 | """Context manager to execute some code, then reload readline history |
|
145 | 145 | so that interactive input to the code doesn't appear when pressing up.""" |
|
146 | 146 | def __init__(self, shell): |
|
147 | 147 | self.shell = shell |
|
148 | 148 | self._nested_level = 0 |
|
149 | 149 | |
|
150 | 150 | def __enter__(self): |
|
151 | 151 | if self._nested_level == 0: |
|
152 | 152 | try: |
|
153 | 153 | self.orig_length = self.current_length() |
|
154 | 154 | self.readline_tail = self.get_readline_tail() |
|
155 | 155 | except (AttributeError, IndexError): # Can fail with pyreadline |
|
156 | 156 | self.orig_length, self.readline_tail = 999999, [] |
|
157 | 157 | self._nested_level += 1 |
|
158 | 158 | |
|
159 | 159 | def __exit__(self, type, value, traceback): |
|
160 | 160 | self._nested_level -= 1 |
|
161 | 161 | if self._nested_level == 0: |
|
162 | 162 | # Try clipping the end if it's got longer |
|
163 | 163 | try: |
|
164 | 164 | e = self.current_length() - self.orig_length |
|
165 | 165 | if e > 0: |
|
166 | 166 | for _ in range(e): |
|
167 | 167 | self.shell.readline.remove_history_item(self.orig_length) |
|
168 | 168 | |
|
169 | 169 | # If it still doesn't match, just reload readline history. |
|
170 | 170 | if self.current_length() != self.orig_length \ |
|
171 | 171 | or self.get_readline_tail() != self.readline_tail: |
|
172 | 172 | self.shell.refill_readline_hist() |
|
173 | 173 | except (AttributeError, IndexError): |
|
174 | 174 | pass |
|
175 | 175 | # Returning False will cause exceptions to propagate |
|
176 | 176 | return False |
|
177 | 177 | |
|
178 | 178 | def current_length(self): |
|
179 | 179 | return self.shell.readline.get_current_history_length() |
|
180 | 180 | |
|
181 | 181 | def get_readline_tail(self, n=10): |
|
182 | 182 | """Get the last n items in readline history.""" |
|
183 | 183 | end = self.shell.readline.get_current_history_length() + 1 |
|
184 | 184 | start = max(end-n, 1) |
|
185 | 185 | ghi = self.shell.readline.get_history_item |
|
186 | 186 | return [ghi(x) for x in range(start, end)] |
|
187 | 187 | |
|
188 | 188 | |
|
189 | 189 | @undoc |
|
190 | 190 | class DummyMod(object): |
|
191 | 191 | """A dummy module used for IPython's interactive module when |
|
192 | 192 | a namespace must be assigned to the module's __dict__.""" |
|
193 | 193 | pass |
|
194 | 194 | |
|
195 | 195 | #----------------------------------------------------------------------------- |
|
196 | 196 | # Main IPython class |
|
197 | 197 | #----------------------------------------------------------------------------- |
|
198 | 198 | |
|
199 | 199 | class InteractiveShell(SingletonConfigurable): |
|
200 | 200 | """An enhanced, interactive shell for Python.""" |
|
201 | 201 | |
|
202 | 202 | _instance = None |
|
203 | 203 | |
|
204 | 204 | ast_transformers = List([], config=True, help= |
|
205 | 205 | """ |
|
206 | 206 | A list of ast.NodeTransformer subclass instances, which will be applied |
|
207 | 207 | to user input before code is run. |
|
208 | 208 | """ |
|
209 | 209 | ) |
|
210 | 210 | |
|
211 | 211 | autocall = Enum((0,1,2), default_value=0, config=True, help= |
|
212 | 212 | """ |
|
213 | 213 | Make IPython automatically call any callable object even if you didn't |
|
214 | 214 | type explicit parentheses. For example, 'str 43' becomes 'str(43)' |
|
215 | 215 | automatically. The value can be '0' to disable the feature, '1' for |
|
216 | 216 | 'smart' autocall, where it is not applied if there are no more |
|
217 | 217 | arguments on the line, and '2' for 'full' autocall, where all callable |
|
218 | 218 | objects are automatically called (even if no arguments are present). |
|
219 | 219 | """ |
|
220 | 220 | ) |
|
221 | 221 | # TODO: remove all autoindent logic and put into frontends. |
|
222 | 222 | # We can't do this yet because even runlines uses the autoindent. |
|
223 | 223 | autoindent = CBool(True, config=True, help= |
|
224 | 224 | """ |
|
225 | 225 | Autoindent IPython code entered interactively. |
|
226 | 226 | """ |
|
227 | 227 | ) |
|
228 | 228 | automagic = CBool(True, config=True, help= |
|
229 | 229 | """ |
|
230 | 230 | Enable magic commands to be called without the leading %. |
|
231 | 231 | """ |
|
232 | 232 | ) |
|
233 | 233 | cache_size = Integer(1000, config=True, help= |
|
234 | 234 | """ |
|
235 | 235 | Set the size of the output cache. The default is 1000, you can |
|
236 | 236 | change it permanently in your config file. Setting it to 0 completely |
|
237 | 237 | disables the caching system, and the minimum value accepted is 20 (if |
|
238 | 238 | you provide a value less than 20, it is reset to 0 and a warning is |
|
239 | 239 | issued). This limit is defined because otherwise you'll spend more |
|
240 | 240 | time re-flushing a too small cache than working |
|
241 | 241 | """ |
|
242 | 242 | ) |
|
243 | 243 | color_info = CBool(True, config=True, help= |
|
244 | 244 | """ |
|
245 | 245 | Use colors for displaying information about objects. Because this |
|
246 | 246 | information is passed through a pager (like 'less'), and some pagers |
|
247 | 247 | get confused with color codes, this capability can be turned off. |
|
248 | 248 | """ |
|
249 | 249 | ) |
|
250 | 250 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), |
|
251 | 251 | default_value=get_default_colors(), config=True, |
|
252 | 252 | help="Set the color scheme (NoColor, Linux, or LightBG)." |
|
253 | 253 | ) |
|
254 | 254 | colors_force = CBool(False, help= |
|
255 | 255 | """ |
|
256 | 256 | Force use of ANSI color codes, regardless of OS and readline |
|
257 | 257 | availability. |
|
258 | 258 | """ |
|
259 | 259 | # FIXME: This is essentially a hack to allow ZMQShell to show colors |
|
260 | 260 | # without readline on Win32. When the ZMQ formatting system is |
|
261 | 261 | # refactored, this should be removed. |
|
262 | 262 | ) |
|
263 | 263 | debug = CBool(False, config=True) |
|
264 | 264 | deep_reload = CBool(False, config=True, help= |
|
265 | 265 | """ |
|
266 | 266 | Enable deep (recursive) reloading by default. IPython can use the |
|
267 | 267 | deep_reload module which reloads changes in modules recursively (it |
|
268 | 268 | replaces the reload() function, so you don't need to change anything to |
|
269 | 269 | use it). deep_reload() forces a full reload of modules whose code may |
|
270 | 270 | have changed, which the default reload() function does not. When |
|
271 | 271 | deep_reload is off, IPython will use the normal reload(), but |
|
272 | 272 | deep_reload will still be available as dreload(). |
|
273 | 273 | """ |
|
274 | 274 | ) |
|
275 | 275 | disable_failing_post_execute = CBool(False, config=True, |
|
276 | 276 | help="Don't call post-execute functions that have failed in the past." |
|
277 | 277 | ) |
|
278 | 278 | display_formatter = Instance(DisplayFormatter) |
|
279 | 279 | displayhook_class = Type(DisplayHook) |
|
280 | 280 | display_pub_class = Type(DisplayPublisher) |
|
281 | 281 | data_pub_class = None |
|
282 | 282 | |
|
283 | 283 | exit_now = CBool(False) |
|
284 | 284 | exiter = Instance(ExitAutocall) |
|
285 | 285 | def _exiter_default(self): |
|
286 | 286 | return ExitAutocall(self) |
|
287 | 287 | # Monotonically increasing execution counter |
|
288 | 288 | execution_count = Integer(1) |
|
289 | 289 | filename = Unicode("<ipython console>") |
|
290 | 290 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ |
|
291 | 291 | |
|
292 | 292 | # Input splitter, to transform input line by line and detect when a block |
|
293 | 293 | # is ready to be executed. |
|
294 | 294 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', |
|
295 | 295 | (), {'line_input_checker': True}) |
|
296 | 296 | |
|
297 | 297 | # This InputSplitter instance is used to transform completed cells before |
|
298 | 298 | # running them. It allows cell magics to contain blank lines. |
|
299 | 299 | input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter', |
|
300 | 300 | (), {'line_input_checker': False}) |
|
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}".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 | readline_delims = Unicode() # set by init_readline() |
|
372 | 372 | # don't use \M- bindings by default, because they |
|
373 | 373 | # conflict with 8-bit encodings. See gh-58,gh-88 |
|
374 | 374 | readline_parse_and_bind = List([ |
|
375 | 375 | 'tab: complete', |
|
376 | 376 | '"\C-l": clear-screen', |
|
377 | 377 | 'set show-all-if-ambiguous on', |
|
378 | 378 | '"\C-o": tab-insert', |
|
379 | 379 | '"\C-r": reverse-search-history', |
|
380 | 380 | '"\C-s": forward-search-history', |
|
381 | 381 | '"\C-p": history-search-backward', |
|
382 | 382 | '"\C-n": history-search-forward', |
|
383 | 383 | '"\e[A": history-search-backward', |
|
384 | 384 | '"\e[B": history-search-forward', |
|
385 | 385 | '"\C-k": kill-line', |
|
386 | 386 | '"\C-u": unix-line-discard', |
|
387 | 387 | ], allow_none=False, config=True) |
|
388 | 388 | |
|
389 | 389 | ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'], |
|
390 | 390 | default_value='last_expr', config=True, |
|
391 | 391 | help=""" |
|
392 | 392 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be |
|
393 | 393 | run interactively (displaying output from expressions).""") |
|
394 | 394 | |
|
395 | 395 | # TODO: this part of prompt management should be moved to the frontends. |
|
396 | 396 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' |
|
397 | 397 | separate_in = SeparateUnicode('\n', config=True) |
|
398 | 398 | separate_out = SeparateUnicode('', config=True) |
|
399 | 399 | separate_out2 = SeparateUnicode('', config=True) |
|
400 | 400 | wildcards_case_sensitive = CBool(True, config=True) |
|
401 | 401 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
402 | 402 | default_value='Context', config=True) |
|
403 | 403 | |
|
404 | 404 | # Subcomponents of InteractiveShell |
|
405 | 405 | alias_manager = Instance('IPython.core.alias.AliasManager') |
|
406 | 406 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
407 | 407 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') |
|
408 | 408 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') |
|
409 | 409 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') |
|
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 | # Tracks any GUI loop loaded for pylab |
|
426 | 426 | pylab_gui_select = None |
|
427 | 427 | |
|
428 | 428 | def __init__(self, ipython_dir=None, profile_dir=None, |
|
429 | 429 | user_module=None, user_ns=None, |
|
430 | 430 | custom_exceptions=((), None), **kwargs): |
|
431 | 431 | |
|
432 | 432 | # This is where traits with a config_key argument are updated |
|
433 | 433 | # from the values on config. |
|
434 | 434 | super(InteractiveShell, self).__init__(**kwargs) |
|
435 | 435 | self.configurables = [self] |
|
436 | 436 | |
|
437 | 437 | # These are relatively independent and stateless |
|
438 | 438 | self.init_ipython_dir(ipython_dir) |
|
439 | 439 | self.init_profile_dir(profile_dir) |
|
440 | 440 | self.init_instance_attrs() |
|
441 | 441 | self.init_environment() |
|
442 | 442 | |
|
443 | 443 | # Check if we're in a virtualenv, and set up sys.path. |
|
444 | 444 | self.init_virtualenv() |
|
445 | 445 | |
|
446 | 446 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
447 | 447 | self.init_create_namespaces(user_module, user_ns) |
|
448 | 448 | # This has to be done after init_create_namespaces because it uses |
|
449 | 449 | # something in self.user_ns, but before init_sys_modules, which |
|
450 | 450 | # is the first thing to modify sys. |
|
451 | 451 | # TODO: When we override sys.stdout and sys.stderr before this class |
|
452 | 452 | # is created, we are saving the overridden ones here. Not sure if this |
|
453 | 453 | # is what we want to do. |
|
454 | 454 | self.save_sys_module_state() |
|
455 | 455 | self.init_sys_modules() |
|
456 | 456 | |
|
457 | 457 | # While we're trying to have each part of the code directly access what |
|
458 | 458 | # it needs without keeping redundant references to objects, we have too |
|
459 | 459 | # much legacy code that expects ip.db to exist. |
|
460 | 460 | self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db')) |
|
461 | 461 | |
|
462 | 462 | self.init_history() |
|
463 | 463 | self.init_encoding() |
|
464 | 464 | self.init_prefilter() |
|
465 | 465 | |
|
466 | 466 | self.init_syntax_highlighting() |
|
467 | 467 | self.init_hooks() |
|
468 | 468 | self.init_pushd_popd_magic() |
|
469 | 469 | # self.init_traceback_handlers use to be here, but we moved it below |
|
470 | 470 | # because it and init_io have to come after init_readline. |
|
471 | 471 | self.init_user_ns() |
|
472 | 472 | self.init_logger() |
|
473 | self.init_alias() | |
|
474 | 473 | self.init_builtins() |
|
475 | 474 | |
|
476 | 475 | # The following was in post_config_initialization |
|
477 | 476 | self.init_inspector() |
|
478 | 477 | # init_readline() must come before init_io(), because init_io uses |
|
479 | 478 | # readline related things. |
|
480 | 479 | self.init_readline() |
|
481 | 480 | # We save this here in case user code replaces raw_input, but it needs |
|
482 | 481 | # to be after init_readline(), because PyPy's readline works by replacing |
|
483 | 482 | # raw_input. |
|
484 | 483 | if py3compat.PY3: |
|
485 | 484 | self.raw_input_original = input |
|
486 | 485 | else: |
|
487 | 486 | self.raw_input_original = raw_input |
|
488 | 487 | # init_completer must come after init_readline, because it needs to |
|
489 | 488 | # know whether readline is present or not system-wide to configure the |
|
490 | 489 | # completers, since the completion machinery can now operate |
|
491 | 490 | # independently of readline (e.g. over the network) |
|
492 | 491 | self.init_completer() |
|
493 | 492 | # TODO: init_io() needs to happen before init_traceback handlers |
|
494 | 493 | # because the traceback handlers hardcode the stdout/stderr streams. |
|
495 | 494 | # This logic in in debugger.Pdb and should eventually be changed. |
|
496 | 495 | self.init_io() |
|
497 | 496 | self.init_traceback_handlers(custom_exceptions) |
|
498 | 497 | self.init_prompts() |
|
499 | 498 | self.init_display_formatter() |
|
500 | 499 | self.init_display_pub() |
|
501 | 500 | self.init_data_pub() |
|
502 | 501 | self.init_displayhook() |
|
503 | 502 | self.init_latextool() |
|
504 | 503 | self.init_magics() |
|
504 | self.init_alias() | |
|
505 | 505 | self.init_logstart() |
|
506 | 506 | self.init_pdb() |
|
507 | 507 | self.init_extension_manager() |
|
508 | 508 | self.init_payload() |
|
509 | 509 | self.hooks.late_startup_hook() |
|
510 | 510 | atexit.register(self.atexit_operations) |
|
511 | 511 | |
|
512 | 512 | def get_ipython(self): |
|
513 | 513 | """Return the currently running IPython instance.""" |
|
514 | 514 | return self |
|
515 | 515 | |
|
516 | 516 | #------------------------------------------------------------------------- |
|
517 | 517 | # Trait changed handlers |
|
518 | 518 | #------------------------------------------------------------------------- |
|
519 | 519 | |
|
520 | 520 | def _ipython_dir_changed(self, name, new): |
|
521 | 521 | if not os.path.isdir(new): |
|
522 | 522 | os.makedirs(new, mode = 0o777) |
|
523 | 523 | |
|
524 | 524 | def set_autoindent(self,value=None): |
|
525 | 525 | """Set the autoindent flag, checking for readline support. |
|
526 | 526 | |
|
527 | 527 | If called with no arguments, it acts as a toggle.""" |
|
528 | 528 | |
|
529 | 529 | if value != 0 and not self.has_readline: |
|
530 | 530 | if os.name == 'posix': |
|
531 | 531 | warn("The auto-indent feature requires the readline library") |
|
532 | 532 | self.autoindent = 0 |
|
533 | 533 | return |
|
534 | 534 | if value is None: |
|
535 | 535 | self.autoindent = not self.autoindent |
|
536 | 536 | else: |
|
537 | 537 | self.autoindent = value |
|
538 | 538 | |
|
539 | 539 | #------------------------------------------------------------------------- |
|
540 | 540 | # init_* methods called by __init__ |
|
541 | 541 | #------------------------------------------------------------------------- |
|
542 | 542 | |
|
543 | 543 | def init_ipython_dir(self, ipython_dir): |
|
544 | 544 | if ipython_dir is not None: |
|
545 | 545 | self.ipython_dir = ipython_dir |
|
546 | 546 | return |
|
547 | 547 | |
|
548 | 548 | self.ipython_dir = get_ipython_dir() |
|
549 | 549 | |
|
550 | 550 | def init_profile_dir(self, profile_dir): |
|
551 | 551 | if profile_dir is not None: |
|
552 | 552 | self.profile_dir = profile_dir |
|
553 | 553 | return |
|
554 | 554 | self.profile_dir =\ |
|
555 | 555 | ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default') |
|
556 | 556 | |
|
557 | 557 | def init_instance_attrs(self): |
|
558 | 558 | self.more = False |
|
559 | 559 | |
|
560 | 560 | # command compiler |
|
561 | 561 | self.compile = CachingCompiler() |
|
562 | 562 | |
|
563 | 563 | # Make an empty namespace, which extension writers can rely on both |
|
564 | 564 | # existing and NEVER being used by ipython itself. This gives them a |
|
565 | 565 | # convenient location for storing additional information and state |
|
566 | 566 | # their extensions may require, without fear of collisions with other |
|
567 | 567 | # ipython names that may develop later. |
|
568 | 568 | self.meta = Struct() |
|
569 | 569 | |
|
570 | 570 | # Temporary files used for various purposes. Deleted at exit. |
|
571 | 571 | self.tempfiles = [] |
|
572 | 572 | |
|
573 | 573 | # Keep track of readline usage (later set by init_readline) |
|
574 | 574 | self.has_readline = False |
|
575 | 575 | |
|
576 | 576 | # keep track of where we started running (mainly for crash post-mortem) |
|
577 | 577 | # This is not being used anywhere currently. |
|
578 | 578 | self.starting_dir = os.getcwdu() |
|
579 | 579 | |
|
580 | 580 | # Indentation management |
|
581 | 581 | self.indent_current_nsp = 0 |
|
582 | 582 | |
|
583 | 583 | # Dict to track post-execution functions that have been registered |
|
584 | 584 | self._post_execute = {} |
|
585 | 585 | |
|
586 | 586 | def init_environment(self): |
|
587 | 587 | """Any changes we need to make to the user's environment.""" |
|
588 | 588 | pass |
|
589 | 589 | |
|
590 | 590 | def init_encoding(self): |
|
591 | 591 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
592 | 592 | # under Win32 have it set to None, and we need to have a known valid |
|
593 | 593 | # encoding to use in the raw_input() method |
|
594 | 594 | try: |
|
595 | 595 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
596 | 596 | except AttributeError: |
|
597 | 597 | self.stdin_encoding = 'ascii' |
|
598 | 598 | |
|
599 | 599 | def init_syntax_highlighting(self): |
|
600 | 600 | # Python source parser/formatter for syntax highlighting |
|
601 | 601 | pyformat = PyColorize.Parser().format |
|
602 | 602 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) |
|
603 | 603 | |
|
604 | 604 | def init_pushd_popd_magic(self): |
|
605 | 605 | # for pushd/popd management |
|
606 | 606 | self.home_dir = get_home_dir() |
|
607 | 607 | |
|
608 | 608 | self.dir_stack = [] |
|
609 | 609 | |
|
610 | 610 | def init_logger(self): |
|
611 | 611 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', |
|
612 | 612 | logmode='rotate') |
|
613 | 613 | |
|
614 | 614 | def init_logstart(self): |
|
615 | 615 | """Initialize logging in case it was requested at the command line. |
|
616 | 616 | """ |
|
617 | 617 | if self.logappend: |
|
618 | 618 | self.magic('logstart %s append' % self.logappend) |
|
619 | 619 | elif self.logfile: |
|
620 | 620 | self.magic('logstart %s' % self.logfile) |
|
621 | 621 | elif self.logstart: |
|
622 | 622 | self.magic('logstart') |
|
623 | 623 | |
|
624 | 624 | def init_builtins(self): |
|
625 | 625 | # A single, static flag that we set to True. Its presence indicates |
|
626 | 626 | # that an IPython shell has been created, and we make no attempts at |
|
627 | 627 | # removing on exit or representing the existence of more than one |
|
628 | 628 | # IPython at a time. |
|
629 | 629 | builtin_mod.__dict__['__IPYTHON__'] = True |
|
630 | 630 | |
|
631 | 631 | # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to |
|
632 | 632 | # manage on enter/exit, but with all our shells it's virtually |
|
633 | 633 | # impossible to get all the cases right. We're leaving the name in for |
|
634 | 634 | # those who adapted their codes to check for this flag, but will |
|
635 | 635 | # eventually remove it after a few more releases. |
|
636 | 636 | builtin_mod.__dict__['__IPYTHON__active'] = \ |
|
637 | 637 | 'Deprecated, check for __IPYTHON__' |
|
638 | 638 | |
|
639 | 639 | self.builtin_trap = BuiltinTrap(shell=self) |
|
640 | 640 | |
|
641 | 641 | def init_inspector(self): |
|
642 | 642 | # Object inspector |
|
643 | 643 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
644 | 644 | PyColorize.ANSICodeColors, |
|
645 | 645 | 'NoColor', |
|
646 | 646 | self.object_info_string_level) |
|
647 | 647 | |
|
648 | 648 | def init_io(self): |
|
649 | 649 | # This will just use sys.stdout and sys.stderr. If you want to |
|
650 | 650 | # override sys.stdout and sys.stderr themselves, you need to do that |
|
651 | 651 | # *before* instantiating this class, because io holds onto |
|
652 | 652 | # references to the underlying streams. |
|
653 | 653 | if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline: |
|
654 | 654 | io.stdout = io.stderr = io.IOStream(self.readline._outputfile) |
|
655 | 655 | else: |
|
656 | 656 | io.stdout = io.IOStream(sys.stdout) |
|
657 | 657 | io.stderr = io.IOStream(sys.stderr) |
|
658 | 658 | |
|
659 | 659 | def init_prompts(self): |
|
660 | 660 | self.prompt_manager = PromptManager(shell=self, parent=self) |
|
661 | 661 | self.configurables.append(self.prompt_manager) |
|
662 | 662 | # Set system prompts, so that scripts can decide if they are running |
|
663 | 663 | # interactively. |
|
664 | 664 | sys.ps1 = 'In : ' |
|
665 | 665 | sys.ps2 = '...: ' |
|
666 | 666 | sys.ps3 = 'Out: ' |
|
667 | 667 | |
|
668 | 668 | def init_display_formatter(self): |
|
669 | 669 | self.display_formatter = DisplayFormatter(parent=self) |
|
670 | 670 | self.configurables.append(self.display_formatter) |
|
671 | 671 | |
|
672 | 672 | def init_display_pub(self): |
|
673 | 673 | self.display_pub = self.display_pub_class(parent=self) |
|
674 | 674 | self.configurables.append(self.display_pub) |
|
675 | 675 | |
|
676 | 676 | def init_data_pub(self): |
|
677 | 677 | if not self.data_pub_class: |
|
678 | 678 | self.data_pub = None |
|
679 | 679 | return |
|
680 | 680 | self.data_pub = self.data_pub_class(parent=self) |
|
681 | 681 | self.configurables.append(self.data_pub) |
|
682 | 682 | |
|
683 | 683 | def init_displayhook(self): |
|
684 | 684 | # Initialize displayhook, set in/out prompts and printing system |
|
685 | 685 | self.displayhook = self.displayhook_class( |
|
686 | 686 | parent=self, |
|
687 | 687 | shell=self, |
|
688 | 688 | cache_size=self.cache_size, |
|
689 | 689 | ) |
|
690 | 690 | self.configurables.append(self.displayhook) |
|
691 | 691 | # This is a context manager that installs/revmoes the displayhook at |
|
692 | 692 | # the appropriate time. |
|
693 | 693 | self.display_trap = DisplayTrap(hook=self.displayhook) |
|
694 | 694 | |
|
695 | 695 | def init_latextool(self): |
|
696 | 696 | """Configure LaTeXTool.""" |
|
697 | 697 | cfg = LaTeXTool.instance(parent=self) |
|
698 | 698 | if cfg not in self.configurables: |
|
699 | 699 | self.configurables.append(cfg) |
|
700 | 700 | |
|
701 | 701 | def init_virtualenv(self): |
|
702 | 702 | """Add a virtualenv to sys.path so the user can import modules from it. |
|
703 | 703 | This isn't perfect: it doesn't use the Python interpreter with which the |
|
704 | 704 | virtualenv was built, and it ignores the --no-site-packages option. A |
|
705 | 705 | warning will appear suggesting the user installs IPython in the |
|
706 | 706 | virtualenv, but for many cases, it probably works well enough. |
|
707 | 707 | |
|
708 | 708 | Adapted from code snippets online. |
|
709 | 709 | |
|
710 | 710 | http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv |
|
711 | 711 | """ |
|
712 | 712 | if 'VIRTUAL_ENV' not in os.environ: |
|
713 | 713 | # Not in a virtualenv |
|
714 | 714 | return |
|
715 | 715 | |
|
716 | 716 | if sys.executable.startswith(os.environ['VIRTUAL_ENV']): |
|
717 | 717 | # Running properly in the virtualenv, don't need to do anything |
|
718 | 718 | return |
|
719 | 719 | |
|
720 | 720 | warn("Attempting to work in a virtualenv. If you encounter problems, please " |
|
721 | 721 | "install IPython inside the virtualenv.") |
|
722 | 722 | if sys.platform == "win32": |
|
723 | 723 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages') |
|
724 | 724 | else: |
|
725 | 725 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib', |
|
726 | 726 | 'python%d.%d' % sys.version_info[:2], 'site-packages') |
|
727 | 727 | |
|
728 | 728 | import site |
|
729 | 729 | sys.path.insert(0, virtual_env) |
|
730 | 730 | site.addsitedir(virtual_env) |
|
731 | 731 | |
|
732 | 732 | #------------------------------------------------------------------------- |
|
733 | 733 | # Things related to injections into the sys module |
|
734 | 734 | #------------------------------------------------------------------------- |
|
735 | 735 | |
|
736 | 736 | def save_sys_module_state(self): |
|
737 | 737 | """Save the state of hooks in the sys module. |
|
738 | 738 | |
|
739 | 739 | This has to be called after self.user_module is created. |
|
740 | 740 | """ |
|
741 | 741 | self._orig_sys_module_state = {} |
|
742 | 742 | self._orig_sys_module_state['stdin'] = sys.stdin |
|
743 | 743 | self._orig_sys_module_state['stdout'] = sys.stdout |
|
744 | 744 | self._orig_sys_module_state['stderr'] = sys.stderr |
|
745 | 745 | self._orig_sys_module_state['excepthook'] = sys.excepthook |
|
746 | 746 | self._orig_sys_modules_main_name = self.user_module.__name__ |
|
747 | 747 | self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__) |
|
748 | 748 | |
|
749 | 749 | def restore_sys_module_state(self): |
|
750 | 750 | """Restore the state of the sys module.""" |
|
751 | 751 | try: |
|
752 | 752 | for k, v in self._orig_sys_module_state.iteritems(): |
|
753 | 753 | setattr(sys, k, v) |
|
754 | 754 | except AttributeError: |
|
755 | 755 | pass |
|
756 | 756 | # Reset what what done in self.init_sys_modules |
|
757 | 757 | if self._orig_sys_modules_main_mod is not None: |
|
758 | 758 | sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod |
|
759 | 759 | |
|
760 | 760 | #------------------------------------------------------------------------- |
|
761 | 761 | # Things related to hooks |
|
762 | 762 | #------------------------------------------------------------------------- |
|
763 | 763 | |
|
764 | 764 | def init_hooks(self): |
|
765 | 765 | # hooks holds pointers used for user-side customizations |
|
766 | 766 | self.hooks = Struct() |
|
767 | 767 | |
|
768 | 768 | self.strdispatchers = {} |
|
769 | 769 | |
|
770 | 770 | # Set all default hooks, defined in the IPython.hooks module. |
|
771 | 771 | hooks = IPython.core.hooks |
|
772 | 772 | for hook_name in hooks.__all__: |
|
773 | 773 | # default hooks have priority 100, i.e. low; user hooks should have |
|
774 | 774 | # 0-100 priority |
|
775 | 775 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
776 | 776 | |
|
777 | 777 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
778 | 778 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
779 | 779 | |
|
780 | 780 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
781 | 781 | adding your function to one of these hooks, you can modify IPython's |
|
782 | 782 | behavior to call at runtime your own routines.""" |
|
783 | 783 | |
|
784 | 784 | # At some point in the future, this should validate the hook before it |
|
785 | 785 | # accepts it. Probably at least check that the hook takes the number |
|
786 | 786 | # of args it's supposed to. |
|
787 | 787 | |
|
788 | 788 | f = types.MethodType(hook,self) |
|
789 | 789 | |
|
790 | 790 | # check if the hook is for strdispatcher first |
|
791 | 791 | if str_key is not None: |
|
792 | 792 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
793 | 793 | sdp.add_s(str_key, f, priority ) |
|
794 | 794 | self.strdispatchers[name] = sdp |
|
795 | 795 | return |
|
796 | 796 | if re_key is not None: |
|
797 | 797 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
798 | 798 | sdp.add_re(re.compile(re_key), f, priority ) |
|
799 | 799 | self.strdispatchers[name] = sdp |
|
800 | 800 | return |
|
801 | 801 | |
|
802 | 802 | dp = getattr(self.hooks, name, None) |
|
803 | 803 | if name not in IPython.core.hooks.__all__: |
|
804 | 804 | print("Warning! Hook '%s' is not one of %s" % \ |
|
805 | 805 | (name, IPython.core.hooks.__all__ )) |
|
806 | 806 | if not dp: |
|
807 | 807 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
808 | 808 | |
|
809 | 809 | try: |
|
810 | 810 | dp.add(f,priority) |
|
811 | 811 | except AttributeError: |
|
812 | 812 | # it was not commandchain, plain old func - replace |
|
813 | 813 | dp = f |
|
814 | 814 | |
|
815 | 815 | setattr(self.hooks,name, dp) |
|
816 | 816 | |
|
817 | 817 | def register_post_execute(self, func): |
|
818 | 818 | """Register a function for calling after code execution. |
|
819 | 819 | """ |
|
820 | 820 | if not callable(func): |
|
821 | 821 | raise ValueError('argument %s must be callable' % func) |
|
822 | 822 | self._post_execute[func] = True |
|
823 | 823 | |
|
824 | 824 | #------------------------------------------------------------------------- |
|
825 | 825 | # Things related to the "main" module |
|
826 | 826 | #------------------------------------------------------------------------- |
|
827 | 827 | |
|
828 | 828 | def new_main_mod(self, filename, modname): |
|
829 | 829 | """Return a new 'main' module object for user code execution. |
|
830 | 830 | |
|
831 | 831 | ``filename`` should be the path of the script which will be run in the |
|
832 | 832 | module. Requests with the same filename will get the same module, with |
|
833 | 833 | its namespace cleared. |
|
834 | 834 | |
|
835 | 835 | ``modname`` should be the module name - normally either '__main__' or |
|
836 | 836 | the basename of the file without the extension. |
|
837 | 837 | |
|
838 | 838 | When scripts are executed via %run, we must keep a reference to their |
|
839 | 839 | __main__ module around so that Python doesn't |
|
840 | 840 | clear it, rendering references to module globals useless. |
|
841 | 841 | |
|
842 | 842 | This method keeps said reference in a private dict, keyed by the |
|
843 | 843 | absolute path of the script. This way, for multiple executions of the |
|
844 | 844 | same script we only keep one copy of the namespace (the last one), |
|
845 | 845 | thus preventing memory leaks from old references while allowing the |
|
846 | 846 | objects from the last execution to be accessible. |
|
847 | 847 | """ |
|
848 | 848 | filename = os.path.abspath(filename) |
|
849 | 849 | try: |
|
850 | 850 | main_mod = self._main_mod_cache[filename] |
|
851 | 851 | except KeyError: |
|
852 | 852 | main_mod = self._main_mod_cache[filename] = types.ModuleType(modname, |
|
853 | 853 | doc="Module created for script run in IPython") |
|
854 | 854 | else: |
|
855 | 855 | main_mod.__dict__.clear() |
|
856 | 856 | main_mod.__name__ = modname |
|
857 | 857 | |
|
858 | 858 | main_mod.__file__ = filename |
|
859 | 859 | # It seems pydoc (and perhaps others) needs any module instance to |
|
860 | 860 | # implement a __nonzero__ method |
|
861 | 861 | main_mod.__nonzero__ = lambda : True |
|
862 | 862 | |
|
863 | 863 | return main_mod |
|
864 | 864 | |
|
865 | 865 | def clear_main_mod_cache(self): |
|
866 | 866 | """Clear the cache of main modules. |
|
867 | 867 | |
|
868 | 868 | Mainly for use by utilities like %reset. |
|
869 | 869 | |
|
870 | 870 | Examples |
|
871 | 871 | -------- |
|
872 | 872 | |
|
873 | 873 | In [15]: import IPython |
|
874 | 874 | |
|
875 | 875 | In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython') |
|
876 | 876 | |
|
877 | 877 | In [17]: len(_ip._main_mod_cache) > 0 |
|
878 | 878 | Out[17]: True |
|
879 | 879 | |
|
880 | 880 | In [18]: _ip.clear_main_mod_cache() |
|
881 | 881 | |
|
882 | 882 | In [19]: len(_ip._main_mod_cache) == 0 |
|
883 | 883 | Out[19]: True |
|
884 | 884 | """ |
|
885 | 885 | self._main_mod_cache.clear() |
|
886 | 886 | |
|
887 | 887 | #------------------------------------------------------------------------- |
|
888 | 888 | # Things related to debugging |
|
889 | 889 | #------------------------------------------------------------------------- |
|
890 | 890 | |
|
891 | 891 | def init_pdb(self): |
|
892 | 892 | # Set calling of pdb on exceptions |
|
893 | 893 | # self.call_pdb is a property |
|
894 | 894 | self.call_pdb = self.pdb |
|
895 | 895 | |
|
896 | 896 | def _get_call_pdb(self): |
|
897 | 897 | return self._call_pdb |
|
898 | 898 | |
|
899 | 899 | def _set_call_pdb(self,val): |
|
900 | 900 | |
|
901 | 901 | if val not in (0,1,False,True): |
|
902 | 902 | raise ValueError('new call_pdb value must be boolean') |
|
903 | 903 | |
|
904 | 904 | # store value in instance |
|
905 | 905 | self._call_pdb = val |
|
906 | 906 | |
|
907 | 907 | # notify the actual exception handlers |
|
908 | 908 | self.InteractiveTB.call_pdb = val |
|
909 | 909 | |
|
910 | 910 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
911 | 911 | 'Control auto-activation of pdb at exceptions') |
|
912 | 912 | |
|
913 | 913 | def debugger(self,force=False): |
|
914 | 914 | """Call the pydb/pdb debugger. |
|
915 | 915 | |
|
916 | 916 | Keywords: |
|
917 | 917 | |
|
918 | 918 | - force(False): by default, this routine checks the instance call_pdb |
|
919 | 919 | flag and does not actually invoke the debugger if the flag is false. |
|
920 | 920 | The 'force' option forces the debugger to activate even if the flag |
|
921 | 921 | is false. |
|
922 | 922 | """ |
|
923 | 923 | |
|
924 | 924 | if not (force or self.call_pdb): |
|
925 | 925 | return |
|
926 | 926 | |
|
927 | 927 | if not hasattr(sys,'last_traceback'): |
|
928 | 928 | error('No traceback has been produced, nothing to debug.') |
|
929 | 929 | return |
|
930 | 930 | |
|
931 | 931 | # use pydb if available |
|
932 | 932 | if debugger.has_pydb: |
|
933 | 933 | from pydb import pm |
|
934 | 934 | else: |
|
935 | 935 | # fallback to our internal debugger |
|
936 | 936 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
937 | 937 | |
|
938 | 938 | with self.readline_no_record: |
|
939 | 939 | pm() |
|
940 | 940 | |
|
941 | 941 | #------------------------------------------------------------------------- |
|
942 | 942 | # Things related to IPython's various namespaces |
|
943 | 943 | #------------------------------------------------------------------------- |
|
944 | 944 | default_user_namespaces = True |
|
945 | 945 | |
|
946 | 946 | def init_create_namespaces(self, user_module=None, user_ns=None): |
|
947 | 947 | # Create the namespace where the user will operate. user_ns is |
|
948 | 948 | # normally the only one used, and it is passed to the exec calls as |
|
949 | 949 | # the locals argument. But we do carry a user_global_ns namespace |
|
950 | 950 | # given as the exec 'globals' argument, This is useful in embedding |
|
951 | 951 | # situations where the ipython shell opens in a context where the |
|
952 | 952 | # distinction between locals and globals is meaningful. For |
|
953 | 953 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
954 | 954 | |
|
955 | 955 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
956 | 956 | # level as a dict instead of a module. This is a manual fix, but I |
|
957 | 957 | # should really track down where the problem is coming from. Alex |
|
958 | 958 | # Schmolck reported this problem first. |
|
959 | 959 | |
|
960 | 960 | # A useful post by Alex Martelli on this topic: |
|
961 | 961 | # Re: inconsistent value from __builtins__ |
|
962 | 962 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
963 | 963 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
964 | 964 | # Gruppen: comp.lang.python |
|
965 | 965 | |
|
966 | 966 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
967 | 967 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
968 | 968 | # > <type 'dict'> |
|
969 | 969 | # > >>> print type(__builtins__) |
|
970 | 970 | # > <type 'module'> |
|
971 | 971 | # > Is this difference in return value intentional? |
|
972 | 972 | |
|
973 | 973 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
974 | 974 | # or a module, and it's been that way for a long time. Whether it's |
|
975 | 975 | # intentional (or sensible), I don't know. In any case, the idea is |
|
976 | 976 | # that if you need to access the built-in namespace directly, you |
|
977 | 977 | # should start with "import __builtin__" (note, no 's') which will |
|
978 | 978 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
979 | 979 | |
|
980 | 980 | # These routines return a properly built module and dict as needed by |
|
981 | 981 | # the rest of the code, and can also be used by extension writers to |
|
982 | 982 | # generate properly initialized namespaces. |
|
983 | 983 | if (user_ns is not None) or (user_module is not None): |
|
984 | 984 | self.default_user_namespaces = False |
|
985 | 985 | self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns) |
|
986 | 986 | |
|
987 | 987 | # A record of hidden variables we have added to the user namespace, so |
|
988 | 988 | # we can list later only variables defined in actual interactive use. |
|
989 | 989 | self.user_ns_hidden = {} |
|
990 | 990 | |
|
991 | 991 | # Now that FakeModule produces a real module, we've run into a nasty |
|
992 | 992 | # problem: after script execution (via %run), the module where the user |
|
993 | 993 | # code ran is deleted. Now that this object is a true module (needed |
|
994 | 994 | # so docetst and other tools work correctly), the Python module |
|
995 | 995 | # teardown mechanism runs over it, and sets to None every variable |
|
996 | 996 | # present in that module. Top-level references to objects from the |
|
997 | 997 | # script survive, because the user_ns is updated with them. However, |
|
998 | 998 | # calling functions defined in the script that use other things from |
|
999 | 999 | # the script will fail, because the function's closure had references |
|
1000 | 1000 | # to the original objects, which are now all None. So we must protect |
|
1001 | 1001 | # these modules from deletion by keeping a cache. |
|
1002 | 1002 | # |
|
1003 | 1003 | # To avoid keeping stale modules around (we only need the one from the |
|
1004 | 1004 | # last run), we use a dict keyed with the full path to the script, so |
|
1005 | 1005 | # only the last version of the module is held in the cache. Note, |
|
1006 | 1006 | # however, that we must cache the module *namespace contents* (their |
|
1007 | 1007 | # __dict__). Because if we try to cache the actual modules, old ones |
|
1008 | 1008 | # (uncached) could be destroyed while still holding references (such as |
|
1009 | 1009 | # those held by GUI objects that tend to be long-lived)> |
|
1010 | 1010 | # |
|
1011 | 1011 | # The %reset command will flush this cache. See the cache_main_mod() |
|
1012 | 1012 | # and clear_main_mod_cache() methods for details on use. |
|
1013 | 1013 | |
|
1014 | 1014 | # This is the cache used for 'main' namespaces |
|
1015 | 1015 | self._main_mod_cache = {} |
|
1016 | 1016 | |
|
1017 | 1017 | # A table holding all the namespaces IPython deals with, so that |
|
1018 | 1018 | # introspection facilities can search easily. |
|
1019 | 1019 | self.ns_table = {'user_global':self.user_module.__dict__, |
|
1020 | 1020 | 'user_local':self.user_ns, |
|
1021 | 1021 | 'builtin':builtin_mod.__dict__ |
|
1022 | 1022 | } |
|
1023 | 1023 | |
|
1024 | 1024 | @property |
|
1025 | 1025 | def user_global_ns(self): |
|
1026 | 1026 | return self.user_module.__dict__ |
|
1027 | 1027 | |
|
1028 | 1028 | def prepare_user_module(self, user_module=None, user_ns=None): |
|
1029 | 1029 | """Prepare the module and namespace in which user code will be run. |
|
1030 | 1030 | |
|
1031 | 1031 | When IPython is started normally, both parameters are None: a new module |
|
1032 | 1032 | is created automatically, and its __dict__ used as the namespace. |
|
1033 | 1033 | |
|
1034 | 1034 | If only user_module is provided, its __dict__ is used as the namespace. |
|
1035 | 1035 | If only user_ns is provided, a dummy module is created, and user_ns |
|
1036 | 1036 | becomes the global namespace. If both are provided (as they may be |
|
1037 | 1037 | when embedding), user_ns is the local namespace, and user_module |
|
1038 | 1038 | provides the global namespace. |
|
1039 | 1039 | |
|
1040 | 1040 | Parameters |
|
1041 | 1041 | ---------- |
|
1042 | 1042 | user_module : module, optional |
|
1043 | 1043 | The current user module in which IPython is being run. If None, |
|
1044 | 1044 | a clean module will be created. |
|
1045 | 1045 | user_ns : dict, optional |
|
1046 | 1046 | A namespace in which to run interactive commands. |
|
1047 | 1047 | |
|
1048 | 1048 | Returns |
|
1049 | 1049 | ------- |
|
1050 | 1050 | A tuple of user_module and user_ns, each properly initialised. |
|
1051 | 1051 | """ |
|
1052 | 1052 | if user_module is None and user_ns is not None: |
|
1053 | 1053 | user_ns.setdefault("__name__", "__main__") |
|
1054 | 1054 | user_module = DummyMod() |
|
1055 | 1055 | user_module.__dict__ = user_ns |
|
1056 | 1056 | |
|
1057 | 1057 | if user_module is None: |
|
1058 | 1058 | user_module = types.ModuleType("__main__", |
|
1059 | 1059 | doc="Automatically created module for IPython interactive environment") |
|
1060 | 1060 | |
|
1061 | 1061 | # We must ensure that __builtin__ (without the final 's') is always |
|
1062 | 1062 | # available and pointing to the __builtin__ *module*. For more details: |
|
1063 | 1063 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
1064 | 1064 | user_module.__dict__.setdefault('__builtin__', builtin_mod) |
|
1065 | 1065 | user_module.__dict__.setdefault('__builtins__', builtin_mod) |
|
1066 | 1066 | |
|
1067 | 1067 | if user_ns is None: |
|
1068 | 1068 | user_ns = user_module.__dict__ |
|
1069 | 1069 | |
|
1070 | 1070 | return user_module, user_ns |
|
1071 | 1071 | |
|
1072 | 1072 | def init_sys_modules(self): |
|
1073 | 1073 | # We need to insert into sys.modules something that looks like a |
|
1074 | 1074 | # module but which accesses the IPython namespace, for shelve and |
|
1075 | 1075 | # pickle to work interactively. Normally they rely on getting |
|
1076 | 1076 | # everything out of __main__, but for embedding purposes each IPython |
|
1077 | 1077 | # instance has its own private namespace, so we can't go shoving |
|
1078 | 1078 | # everything into __main__. |
|
1079 | 1079 | |
|
1080 | 1080 | # note, however, that we should only do this for non-embedded |
|
1081 | 1081 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
1082 | 1082 | # namespace. Embedded instances, on the other hand, should not do |
|
1083 | 1083 | # this because they need to manage the user local/global namespaces |
|
1084 | 1084 | # only, but they live within a 'normal' __main__ (meaning, they |
|
1085 | 1085 | # shouldn't overtake the execution environment of the script they're |
|
1086 | 1086 | # embedded in). |
|
1087 | 1087 | |
|
1088 | 1088 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
1089 | 1089 | main_name = self.user_module.__name__ |
|
1090 | 1090 | sys.modules[main_name] = self.user_module |
|
1091 | 1091 | |
|
1092 | 1092 | def init_user_ns(self): |
|
1093 | 1093 | """Initialize all user-visible namespaces to their minimum defaults. |
|
1094 | 1094 | |
|
1095 | 1095 | Certain history lists are also initialized here, as they effectively |
|
1096 | 1096 | act as user namespaces. |
|
1097 | 1097 | |
|
1098 | 1098 | Notes |
|
1099 | 1099 | ----- |
|
1100 | 1100 | All data structures here are only filled in, they are NOT reset by this |
|
1101 | 1101 | method. If they were not empty before, data will simply be added to |
|
1102 | 1102 | therm. |
|
1103 | 1103 | """ |
|
1104 | 1104 | # This function works in two parts: first we put a few things in |
|
1105 | 1105 | # user_ns, and we sync that contents into user_ns_hidden so that these |
|
1106 | 1106 | # initial variables aren't shown by %who. After the sync, we add the |
|
1107 | 1107 | # rest of what we *do* want the user to see with %who even on a new |
|
1108 | 1108 | # session (probably nothing, so theye really only see their own stuff) |
|
1109 | 1109 | |
|
1110 | 1110 | # The user dict must *always* have a __builtin__ reference to the |
|
1111 | 1111 | # Python standard __builtin__ namespace, which must be imported. |
|
1112 | 1112 | # This is so that certain operations in prompt evaluation can be |
|
1113 | 1113 | # reliably executed with builtins. Note that we can NOT use |
|
1114 | 1114 | # __builtins__ (note the 's'), because that can either be a dict or a |
|
1115 | 1115 | # module, and can even mutate at runtime, depending on the context |
|
1116 | 1116 | # (Python makes no guarantees on it). In contrast, __builtin__ is |
|
1117 | 1117 | # always a module object, though it must be explicitly imported. |
|
1118 | 1118 | |
|
1119 | 1119 | # For more details: |
|
1120 | 1120 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
1121 | 1121 | ns = dict() |
|
1122 | 1122 | |
|
1123 | 1123 | # Put 'help' in the user namespace |
|
1124 | 1124 | try: |
|
1125 | 1125 | from site import _Helper |
|
1126 | 1126 | ns['help'] = _Helper() |
|
1127 | 1127 | except ImportError: |
|
1128 | 1128 | warn('help() not available - check site.py') |
|
1129 | 1129 | |
|
1130 | 1130 | # make global variables for user access to the histories |
|
1131 | 1131 | ns['_ih'] = self.history_manager.input_hist_parsed |
|
1132 | 1132 | ns['_oh'] = self.history_manager.output_hist |
|
1133 | 1133 | ns['_dh'] = self.history_manager.dir_hist |
|
1134 | 1134 | |
|
1135 | 1135 | ns['_sh'] = shadowns |
|
1136 | 1136 | |
|
1137 | 1137 | # user aliases to input and output histories. These shouldn't show up |
|
1138 | 1138 | # in %who, as they can have very large reprs. |
|
1139 | 1139 | ns['In'] = self.history_manager.input_hist_parsed |
|
1140 | 1140 | ns['Out'] = self.history_manager.output_hist |
|
1141 | 1141 | |
|
1142 | 1142 | # Store myself as the public api!!! |
|
1143 | 1143 | ns['get_ipython'] = self.get_ipython |
|
1144 | 1144 | |
|
1145 | 1145 | ns['exit'] = self.exiter |
|
1146 | 1146 | ns['quit'] = self.exiter |
|
1147 | 1147 | |
|
1148 | 1148 | # Sync what we've added so far to user_ns_hidden so these aren't seen |
|
1149 | 1149 | # by %who |
|
1150 | 1150 | self.user_ns_hidden.update(ns) |
|
1151 | 1151 | |
|
1152 | 1152 | # Anything put into ns now would show up in %who. Think twice before |
|
1153 | 1153 | # putting anything here, as we really want %who to show the user their |
|
1154 | 1154 | # stuff, not our variables. |
|
1155 | 1155 | |
|
1156 | 1156 | # Finally, update the real user's namespace |
|
1157 | 1157 | self.user_ns.update(ns) |
|
1158 | 1158 | |
|
1159 | 1159 | @property |
|
1160 | 1160 | def all_ns_refs(self): |
|
1161 | 1161 | """Get a list of references to all the namespace dictionaries in which |
|
1162 | 1162 | IPython might store a user-created object. |
|
1163 | 1163 | |
|
1164 | 1164 | Note that this does not include the displayhook, which also caches |
|
1165 | 1165 | objects from the output.""" |
|
1166 | 1166 | return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \ |
|
1167 | 1167 | [m.__dict__ for m in self._main_mod_cache.values()] |
|
1168 | 1168 | |
|
1169 | 1169 | def reset(self, new_session=True): |
|
1170 | 1170 | """Clear all internal namespaces, and attempt to release references to |
|
1171 | 1171 | user objects. |
|
1172 | 1172 | |
|
1173 | 1173 | If new_session is True, a new history session will be opened. |
|
1174 | 1174 | """ |
|
1175 | 1175 | # Clear histories |
|
1176 | 1176 | self.history_manager.reset(new_session) |
|
1177 | 1177 | # Reset counter used to index all histories |
|
1178 | 1178 | if new_session: |
|
1179 | 1179 | self.execution_count = 1 |
|
1180 | 1180 | |
|
1181 | 1181 | # Flush cached output items |
|
1182 | 1182 | if self.displayhook.do_full_cache: |
|
1183 | 1183 | self.displayhook.flush() |
|
1184 | 1184 | |
|
1185 | 1185 | # The main execution namespaces must be cleared very carefully, |
|
1186 | 1186 | # skipping the deletion of the builtin-related keys, because doing so |
|
1187 | 1187 | # would cause errors in many object's __del__ methods. |
|
1188 | 1188 | if self.user_ns is not self.user_global_ns: |
|
1189 | 1189 | self.user_ns.clear() |
|
1190 | 1190 | ns = self.user_global_ns |
|
1191 | 1191 | drop_keys = set(ns.keys()) |
|
1192 | 1192 | drop_keys.discard('__builtin__') |
|
1193 | 1193 | drop_keys.discard('__builtins__') |
|
1194 | 1194 | drop_keys.discard('__name__') |
|
1195 | 1195 | for k in drop_keys: |
|
1196 | 1196 | del ns[k] |
|
1197 | 1197 | |
|
1198 | 1198 | self.user_ns_hidden.clear() |
|
1199 | 1199 | |
|
1200 | 1200 | # Restore the user namespaces to minimal usability |
|
1201 | 1201 | self.init_user_ns() |
|
1202 | 1202 | |
|
1203 | 1203 | # Restore the default and user aliases |
|
1204 | 1204 | self.alias_manager.clear_aliases() |
|
1205 | 1205 | self.alias_manager.init_aliases() |
|
1206 | 1206 | |
|
1207 | 1207 | # Flush the private list of module references kept for script |
|
1208 | 1208 | # execution protection |
|
1209 | 1209 | self.clear_main_mod_cache() |
|
1210 | 1210 | |
|
1211 | 1211 | def del_var(self, varname, by_name=False): |
|
1212 | 1212 | """Delete a variable from the various namespaces, so that, as |
|
1213 | 1213 | far as possible, we're not keeping any hidden references to it. |
|
1214 | 1214 | |
|
1215 | 1215 | Parameters |
|
1216 | 1216 | ---------- |
|
1217 | 1217 | varname : str |
|
1218 | 1218 | The name of the variable to delete. |
|
1219 | 1219 | by_name : bool |
|
1220 | 1220 | If True, delete variables with the given name in each |
|
1221 | 1221 | namespace. If False (default), find the variable in the user |
|
1222 | 1222 | namespace, and delete references to it. |
|
1223 | 1223 | """ |
|
1224 | 1224 | if varname in ('__builtin__', '__builtins__'): |
|
1225 | 1225 | raise ValueError("Refusing to delete %s" % varname) |
|
1226 | 1226 | |
|
1227 | 1227 | ns_refs = self.all_ns_refs |
|
1228 | 1228 | |
|
1229 | 1229 | if by_name: # Delete by name |
|
1230 | 1230 | for ns in ns_refs: |
|
1231 | 1231 | try: |
|
1232 | 1232 | del ns[varname] |
|
1233 | 1233 | except KeyError: |
|
1234 | 1234 | pass |
|
1235 | 1235 | else: # Delete by object |
|
1236 | 1236 | try: |
|
1237 | 1237 | obj = self.user_ns[varname] |
|
1238 | 1238 | except KeyError: |
|
1239 | 1239 | raise NameError("name '%s' is not defined" % varname) |
|
1240 | 1240 | # Also check in output history |
|
1241 | 1241 | ns_refs.append(self.history_manager.output_hist) |
|
1242 | 1242 | for ns in ns_refs: |
|
1243 | 1243 | to_delete = [n for n, o in ns.iteritems() if o is obj] |
|
1244 | 1244 | for name in to_delete: |
|
1245 | 1245 | del ns[name] |
|
1246 | 1246 | |
|
1247 | 1247 | # displayhook keeps extra references, but not in a dictionary |
|
1248 | 1248 | for name in ('_', '__', '___'): |
|
1249 | 1249 | if getattr(self.displayhook, name) is obj: |
|
1250 | 1250 | setattr(self.displayhook, name, None) |
|
1251 | 1251 | |
|
1252 | 1252 | def reset_selective(self, regex=None): |
|
1253 | 1253 | """Clear selective variables from internal namespaces based on a |
|
1254 | 1254 | specified regular expression. |
|
1255 | 1255 | |
|
1256 | 1256 | Parameters |
|
1257 | 1257 | ---------- |
|
1258 | 1258 | regex : string or compiled pattern, optional |
|
1259 | 1259 | A regular expression pattern that will be used in searching |
|
1260 | 1260 | variable names in the users namespaces. |
|
1261 | 1261 | """ |
|
1262 | 1262 | if regex is not None: |
|
1263 | 1263 | try: |
|
1264 | 1264 | m = re.compile(regex) |
|
1265 | 1265 | except TypeError: |
|
1266 | 1266 | raise TypeError('regex must be a string or compiled pattern') |
|
1267 | 1267 | # Search for keys in each namespace that match the given regex |
|
1268 | 1268 | # If a match is found, delete the key/value pair. |
|
1269 | 1269 | for ns in self.all_ns_refs: |
|
1270 | 1270 | for var in ns: |
|
1271 | 1271 | if m.search(var): |
|
1272 | 1272 | del ns[var] |
|
1273 | 1273 | |
|
1274 | 1274 | def push(self, variables, interactive=True): |
|
1275 | 1275 | """Inject a group of variables into the IPython user namespace. |
|
1276 | 1276 | |
|
1277 | 1277 | Parameters |
|
1278 | 1278 | ---------- |
|
1279 | 1279 | variables : dict, str or list/tuple of str |
|
1280 | 1280 | The variables to inject into the user's namespace. If a dict, a |
|
1281 | 1281 | simple update is done. If a str, the string is assumed to have |
|
1282 | 1282 | variable names separated by spaces. A list/tuple of str can also |
|
1283 | 1283 | be used to give the variable names. If just the variable names are |
|
1284 | 1284 | give (list/tuple/str) then the variable values looked up in the |
|
1285 | 1285 | callers frame. |
|
1286 | 1286 | interactive : bool |
|
1287 | 1287 | If True (default), the variables will be listed with the ``who`` |
|
1288 | 1288 | magic. |
|
1289 | 1289 | """ |
|
1290 | 1290 | vdict = None |
|
1291 | 1291 | |
|
1292 | 1292 | # We need a dict of name/value pairs to do namespace updates. |
|
1293 | 1293 | if isinstance(variables, dict): |
|
1294 | 1294 | vdict = variables |
|
1295 | 1295 | elif isinstance(variables, (basestring, list, tuple)): |
|
1296 | 1296 | if isinstance(variables, basestring): |
|
1297 | 1297 | vlist = variables.split() |
|
1298 | 1298 | else: |
|
1299 | 1299 | vlist = variables |
|
1300 | 1300 | vdict = {} |
|
1301 | 1301 | cf = sys._getframe(1) |
|
1302 | 1302 | for name in vlist: |
|
1303 | 1303 | try: |
|
1304 | 1304 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1305 | 1305 | except: |
|
1306 | 1306 | print('Could not get variable %s from %s' % |
|
1307 | 1307 | (name,cf.f_code.co_name)) |
|
1308 | 1308 | else: |
|
1309 | 1309 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1310 | 1310 | |
|
1311 | 1311 | # Propagate variables to user namespace |
|
1312 | 1312 | self.user_ns.update(vdict) |
|
1313 | 1313 | |
|
1314 | 1314 | # And configure interactive visibility |
|
1315 | 1315 | user_ns_hidden = self.user_ns_hidden |
|
1316 | 1316 | if interactive: |
|
1317 | 1317 | for name in vdict: |
|
1318 | 1318 | user_ns_hidden.pop(name, None) |
|
1319 | 1319 | else: |
|
1320 | 1320 | user_ns_hidden.update(vdict) |
|
1321 | 1321 | |
|
1322 | 1322 | def drop_by_id(self, variables): |
|
1323 | 1323 | """Remove a dict of variables from the user namespace, if they are the |
|
1324 | 1324 | same as the values in the dictionary. |
|
1325 | 1325 | |
|
1326 | 1326 | This is intended for use by extensions: variables that they've added can |
|
1327 | 1327 | be taken back out if they are unloaded, without removing any that the |
|
1328 | 1328 | user has overwritten. |
|
1329 | 1329 | |
|
1330 | 1330 | Parameters |
|
1331 | 1331 | ---------- |
|
1332 | 1332 | variables : dict |
|
1333 | 1333 | A dictionary mapping object names (as strings) to the objects. |
|
1334 | 1334 | """ |
|
1335 | 1335 | for name, obj in variables.iteritems(): |
|
1336 | 1336 | if name in self.user_ns and self.user_ns[name] is obj: |
|
1337 | 1337 | del self.user_ns[name] |
|
1338 | 1338 | self.user_ns_hidden.pop(name, None) |
|
1339 | 1339 | |
|
1340 | 1340 | #------------------------------------------------------------------------- |
|
1341 | 1341 | # Things related to object introspection |
|
1342 | 1342 | #------------------------------------------------------------------------- |
|
1343 | 1343 | |
|
1344 | 1344 | def _ofind(self, oname, namespaces=None): |
|
1345 | 1345 | """Find an object in the available namespaces. |
|
1346 | 1346 | |
|
1347 | 1347 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
1348 | 1348 | |
|
1349 | 1349 | Has special code to detect magic functions. |
|
1350 | 1350 | """ |
|
1351 | 1351 | oname = oname.strip() |
|
1352 | 1352 | #print '1- oname: <%r>' % oname # dbg |
|
1353 | 1353 | if not oname.startswith(ESC_MAGIC) and \ |
|
1354 | 1354 | not oname.startswith(ESC_MAGIC2) and \ |
|
1355 | 1355 | not py3compat.isidentifier(oname, dotted=True): |
|
1356 | 1356 | return dict(found=False) |
|
1357 | 1357 | |
|
1358 | 1358 | alias_ns = None |
|
1359 | 1359 | if namespaces is None: |
|
1360 | 1360 | # Namespaces to search in: |
|
1361 | 1361 | # Put them in a list. The order is important so that we |
|
1362 | 1362 | # find things in the same order that Python finds them. |
|
1363 | 1363 | namespaces = [ ('Interactive', self.user_ns), |
|
1364 | 1364 | ('Interactive (global)', self.user_global_ns), |
|
1365 | 1365 | ('Python builtin', builtin_mod.__dict__), |
|
1366 | ('Alias', self.alias_manager.alias_table), | |
|
1367 | 1366 | ] |
|
1368 | alias_ns = self.alias_manager.alias_table | |
|
1369 | 1367 | |
|
1370 | 1368 | # initialize results to 'null' |
|
1371 | 1369 | found = False; obj = None; ospace = None; ds = None; |
|
1372 | 1370 | ismagic = False; isalias = False; parent = None |
|
1373 | 1371 | |
|
1374 | 1372 | # We need to special-case 'print', which as of python2.6 registers as a |
|
1375 | 1373 | # function but should only be treated as one if print_function was |
|
1376 | 1374 | # loaded with a future import. In this case, just bail. |
|
1377 | 1375 | if (oname == 'print' and not py3compat.PY3 and not \ |
|
1378 | 1376 | (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)): |
|
1379 | 1377 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1380 | 1378 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1381 | 1379 | |
|
1382 | 1380 | # Look for the given name by splitting it in parts. If the head is |
|
1383 | 1381 | # found, then we look for all the remaining parts as members, and only |
|
1384 | 1382 | # declare success if we can find them all. |
|
1385 | 1383 | oname_parts = oname.split('.') |
|
1386 | 1384 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
1387 | 1385 | for nsname,ns in namespaces: |
|
1388 | 1386 | try: |
|
1389 | 1387 | obj = ns[oname_head] |
|
1390 | 1388 | except KeyError: |
|
1391 | 1389 | continue |
|
1392 | 1390 | else: |
|
1393 | 1391 | #print 'oname_rest:', oname_rest # dbg |
|
1394 | 1392 | for part in oname_rest: |
|
1395 | 1393 | try: |
|
1396 | 1394 | parent = obj |
|
1397 | 1395 | obj = getattr(obj,part) |
|
1398 | 1396 | except: |
|
1399 | 1397 | # Blanket except b/c some badly implemented objects |
|
1400 | 1398 | # allow __getattr__ to raise exceptions other than |
|
1401 | 1399 | # AttributeError, which then crashes IPython. |
|
1402 | 1400 | break |
|
1403 | 1401 | else: |
|
1404 | 1402 | # If we finish the for loop (no break), we got all members |
|
1405 | 1403 | found = True |
|
1406 | 1404 | ospace = nsname |
|
1407 | if ns == alias_ns: | |
|
1408 | isalias = True | |
|
1409 | 1405 | break # namespace loop |
|
1410 | 1406 | |
|
1411 | 1407 | # Try to see if it's magic |
|
1412 | 1408 | if not found: |
|
1413 | 1409 | obj = None |
|
1414 | 1410 | if oname.startswith(ESC_MAGIC2): |
|
1415 | 1411 | oname = oname.lstrip(ESC_MAGIC2) |
|
1416 | 1412 | obj = self.find_cell_magic(oname) |
|
1417 | 1413 | elif oname.startswith(ESC_MAGIC): |
|
1418 | 1414 | oname = oname.lstrip(ESC_MAGIC) |
|
1419 | 1415 | obj = self.find_line_magic(oname) |
|
1420 | 1416 | else: |
|
1421 | 1417 | # search without prefix, so run? will find %run? |
|
1422 | 1418 | obj = self.find_line_magic(oname) |
|
1423 | 1419 | if obj is None: |
|
1424 | 1420 | obj = self.find_cell_magic(oname) |
|
1425 | 1421 | if obj is not None: |
|
1426 | 1422 | found = True |
|
1427 | 1423 | ospace = 'IPython internal' |
|
1428 | 1424 | ismagic = True |
|
1429 | 1425 | |
|
1430 | 1426 | # Last try: special-case some literals like '', [], {}, etc: |
|
1431 | 1427 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
1432 | 1428 | obj = eval(oname_head) |
|
1433 | 1429 | found = True |
|
1434 | 1430 | ospace = 'Interactive' |
|
1435 | 1431 | |
|
1436 | 1432 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1437 | 1433 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1438 | 1434 | |
|
1439 | 1435 | def _ofind_property(self, oname, info): |
|
1440 | 1436 | """Second part of object finding, to look for property details.""" |
|
1441 | 1437 | if info.found: |
|
1442 | 1438 | # Get the docstring of the class property if it exists. |
|
1443 | 1439 | path = oname.split('.') |
|
1444 | 1440 | root = '.'.join(path[:-1]) |
|
1445 | 1441 | if info.parent is not None: |
|
1446 | 1442 | try: |
|
1447 | 1443 | target = getattr(info.parent, '__class__') |
|
1448 | 1444 | # The object belongs to a class instance. |
|
1449 | 1445 | try: |
|
1450 | 1446 | target = getattr(target, path[-1]) |
|
1451 | 1447 | # The class defines the object. |
|
1452 | 1448 | if isinstance(target, property): |
|
1453 | 1449 | oname = root + '.__class__.' + path[-1] |
|
1454 | 1450 | info = Struct(self._ofind(oname)) |
|
1455 | 1451 | except AttributeError: pass |
|
1456 | 1452 | except AttributeError: pass |
|
1457 | 1453 | |
|
1458 | 1454 | # We return either the new info or the unmodified input if the object |
|
1459 | 1455 | # hadn't been found |
|
1460 | 1456 | return info |
|
1461 | 1457 | |
|
1462 | 1458 | def _object_find(self, oname, namespaces=None): |
|
1463 | 1459 | """Find an object and return a struct with info about it.""" |
|
1464 | 1460 | inf = Struct(self._ofind(oname, namespaces)) |
|
1465 | 1461 | return Struct(self._ofind_property(oname, inf)) |
|
1466 | 1462 | |
|
1467 | 1463 | def _inspect(self, meth, oname, namespaces=None, **kw): |
|
1468 | 1464 | """Generic interface to the inspector system. |
|
1469 | 1465 | |
|
1470 | 1466 | This function is meant to be called by pdef, pdoc & friends.""" |
|
1471 | 1467 | info = self._object_find(oname, namespaces) |
|
1472 | 1468 | if info.found: |
|
1473 | 1469 | pmethod = getattr(self.inspector, meth) |
|
1474 | 1470 | formatter = format_screen if info.ismagic else None |
|
1475 | 1471 | if meth == 'pdoc': |
|
1476 | 1472 | pmethod(info.obj, oname, formatter) |
|
1477 | 1473 | elif meth == 'pinfo': |
|
1478 | 1474 | pmethod(info.obj, oname, formatter, info, **kw) |
|
1479 | 1475 | else: |
|
1480 | 1476 | pmethod(info.obj, oname) |
|
1481 | 1477 | else: |
|
1482 | 1478 | print('Object `%s` not found.' % oname) |
|
1483 | 1479 | return 'not found' # so callers can take other action |
|
1484 | 1480 | |
|
1485 | 1481 | def object_inspect(self, oname, detail_level=0): |
|
1486 | 1482 | with self.builtin_trap: |
|
1487 | 1483 | info = self._object_find(oname) |
|
1488 | 1484 | if info.found: |
|
1489 | 1485 | return self.inspector.info(info.obj, oname, info=info, |
|
1490 | 1486 | detail_level=detail_level |
|
1491 | 1487 | ) |
|
1492 | 1488 | else: |
|
1493 | 1489 | return oinspect.object_info(name=oname, found=False) |
|
1494 | 1490 | |
|
1495 | 1491 | #------------------------------------------------------------------------- |
|
1496 | 1492 | # Things related to history management |
|
1497 | 1493 | #------------------------------------------------------------------------- |
|
1498 | 1494 | |
|
1499 | 1495 | def init_history(self): |
|
1500 | 1496 | """Sets up the command history, and starts regular autosaves.""" |
|
1501 | 1497 | self.history_manager = HistoryManager(shell=self, parent=self) |
|
1502 | 1498 | self.configurables.append(self.history_manager) |
|
1503 | 1499 | |
|
1504 | 1500 | #------------------------------------------------------------------------- |
|
1505 | 1501 | # Things related to exception handling and tracebacks (not debugging) |
|
1506 | 1502 | #------------------------------------------------------------------------- |
|
1507 | 1503 | |
|
1508 | 1504 | def init_traceback_handlers(self, custom_exceptions): |
|
1509 | 1505 | # Syntax error handler. |
|
1510 | 1506 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') |
|
1511 | 1507 | |
|
1512 | 1508 | # The interactive one is initialized with an offset, meaning we always |
|
1513 | 1509 | # want to remove the topmost item in the traceback, which is our own |
|
1514 | 1510 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1515 | 1511 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1516 | 1512 | color_scheme='NoColor', |
|
1517 | 1513 | tb_offset = 1, |
|
1518 | 1514 | check_cache=check_linecache_ipython) |
|
1519 | 1515 | |
|
1520 | 1516 | # The instance will store a pointer to the system-wide exception hook, |
|
1521 | 1517 | # so that runtime code (such as magics) can access it. This is because |
|
1522 | 1518 | # during the read-eval loop, it may get temporarily overwritten. |
|
1523 | 1519 | self.sys_excepthook = sys.excepthook |
|
1524 | 1520 | |
|
1525 | 1521 | # and add any custom exception handlers the user may have specified |
|
1526 | 1522 | self.set_custom_exc(*custom_exceptions) |
|
1527 | 1523 | |
|
1528 | 1524 | # Set the exception mode |
|
1529 | 1525 | self.InteractiveTB.set_mode(mode=self.xmode) |
|
1530 | 1526 | |
|
1531 | 1527 | def set_custom_exc(self, exc_tuple, handler): |
|
1532 | 1528 | """set_custom_exc(exc_tuple,handler) |
|
1533 | 1529 | |
|
1534 | 1530 | Set a custom exception handler, which will be called if any of the |
|
1535 | 1531 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1536 | 1532 | run_code() method). |
|
1537 | 1533 | |
|
1538 | 1534 | Parameters |
|
1539 | 1535 | ---------- |
|
1540 | 1536 | |
|
1541 | 1537 | exc_tuple : tuple of exception classes |
|
1542 | 1538 | A *tuple* of exception classes, for which to call the defined |
|
1543 | 1539 | handler. It is very important that you use a tuple, and NOT A |
|
1544 | 1540 | LIST here, because of the way Python's except statement works. If |
|
1545 | 1541 | you only want to trap a single exception, use a singleton tuple:: |
|
1546 | 1542 | |
|
1547 | 1543 | exc_tuple == (MyCustomException,) |
|
1548 | 1544 | |
|
1549 | 1545 | handler : callable |
|
1550 | 1546 | handler must have the following signature:: |
|
1551 | 1547 | |
|
1552 | 1548 | def my_handler(self, etype, value, tb, tb_offset=None): |
|
1553 | 1549 | ... |
|
1554 | 1550 | return structured_traceback |
|
1555 | 1551 | |
|
1556 | 1552 | Your handler must return a structured traceback (a list of strings), |
|
1557 | 1553 | or None. |
|
1558 | 1554 | |
|
1559 | 1555 | This will be made into an instance method (via types.MethodType) |
|
1560 | 1556 | of IPython itself, and it will be called if any of the exceptions |
|
1561 | 1557 | listed in the exc_tuple are caught. If the handler is None, an |
|
1562 | 1558 | internal basic one is used, which just prints basic info. |
|
1563 | 1559 | |
|
1564 | 1560 | To protect IPython from crashes, if your handler ever raises an |
|
1565 | 1561 | exception or returns an invalid result, it will be immediately |
|
1566 | 1562 | disabled. |
|
1567 | 1563 | |
|
1568 | 1564 | WARNING: by putting in your own exception handler into IPython's main |
|
1569 | 1565 | execution loop, you run a very good chance of nasty crashes. This |
|
1570 | 1566 | facility should only be used if you really know what you are doing.""" |
|
1571 | 1567 | |
|
1572 | 1568 | assert type(exc_tuple)==type(()) , \ |
|
1573 | 1569 | "The custom exceptions must be given AS A TUPLE." |
|
1574 | 1570 | |
|
1575 | 1571 | def dummy_handler(self,etype,value,tb,tb_offset=None): |
|
1576 | 1572 | print('*** Simple custom exception handler ***') |
|
1577 | 1573 | print('Exception type :',etype) |
|
1578 | 1574 | print('Exception value:',value) |
|
1579 | 1575 | print('Traceback :',tb) |
|
1580 | 1576 | #print 'Source code :','\n'.join(self.buffer) |
|
1581 | 1577 | |
|
1582 | 1578 | def validate_stb(stb): |
|
1583 | 1579 | """validate structured traceback return type |
|
1584 | 1580 | |
|
1585 | 1581 | return type of CustomTB *should* be a list of strings, but allow |
|
1586 | 1582 | single strings or None, which are harmless. |
|
1587 | 1583 | |
|
1588 | 1584 | This function will *always* return a list of strings, |
|
1589 | 1585 | and will raise a TypeError if stb is inappropriate. |
|
1590 | 1586 | """ |
|
1591 | 1587 | msg = "CustomTB must return list of strings, not %r" % stb |
|
1592 | 1588 | if stb is None: |
|
1593 | 1589 | return [] |
|
1594 | 1590 | elif isinstance(stb, basestring): |
|
1595 | 1591 | return [stb] |
|
1596 | 1592 | elif not isinstance(stb, list): |
|
1597 | 1593 | raise TypeError(msg) |
|
1598 | 1594 | # it's a list |
|
1599 | 1595 | for line in stb: |
|
1600 | 1596 | # check every element |
|
1601 | 1597 | if not isinstance(line, basestring): |
|
1602 | 1598 | raise TypeError(msg) |
|
1603 | 1599 | return stb |
|
1604 | 1600 | |
|
1605 | 1601 | if handler is None: |
|
1606 | 1602 | wrapped = dummy_handler |
|
1607 | 1603 | else: |
|
1608 | 1604 | def wrapped(self,etype,value,tb,tb_offset=None): |
|
1609 | 1605 | """wrap CustomTB handler, to protect IPython from user code |
|
1610 | 1606 | |
|
1611 | 1607 | This makes it harder (but not impossible) for custom exception |
|
1612 | 1608 | handlers to crash IPython. |
|
1613 | 1609 | """ |
|
1614 | 1610 | try: |
|
1615 | 1611 | stb = handler(self,etype,value,tb,tb_offset=tb_offset) |
|
1616 | 1612 | return validate_stb(stb) |
|
1617 | 1613 | except: |
|
1618 | 1614 | # clear custom handler immediately |
|
1619 | 1615 | self.set_custom_exc((), None) |
|
1620 | 1616 | print("Custom TB Handler failed, unregistering", file=io.stderr) |
|
1621 | 1617 | # show the exception in handler first |
|
1622 | 1618 | stb = self.InteractiveTB.structured_traceback(*sys.exc_info()) |
|
1623 | 1619 | print(self.InteractiveTB.stb2text(stb), file=io.stdout) |
|
1624 | 1620 | print("The original exception:", file=io.stdout) |
|
1625 | 1621 | stb = self.InteractiveTB.structured_traceback( |
|
1626 | 1622 | (etype,value,tb), tb_offset=tb_offset |
|
1627 | 1623 | ) |
|
1628 | 1624 | return stb |
|
1629 | 1625 | |
|
1630 | 1626 | self.CustomTB = types.MethodType(wrapped,self) |
|
1631 | 1627 | self.custom_exceptions = exc_tuple |
|
1632 | 1628 | |
|
1633 | 1629 | def excepthook(self, etype, value, tb): |
|
1634 | 1630 | """One more defense for GUI apps that call sys.excepthook. |
|
1635 | 1631 | |
|
1636 | 1632 | GUI frameworks like wxPython trap exceptions and call |
|
1637 | 1633 | sys.excepthook themselves. I guess this is a feature that |
|
1638 | 1634 | enables them to keep running after exceptions that would |
|
1639 | 1635 | otherwise kill their mainloop. This is a bother for IPython |
|
1640 | 1636 | which excepts to catch all of the program exceptions with a try: |
|
1641 | 1637 | except: statement. |
|
1642 | 1638 | |
|
1643 | 1639 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1644 | 1640 | any app directly invokes sys.excepthook, it will look to the user like |
|
1645 | 1641 | IPython crashed. In order to work around this, we can disable the |
|
1646 | 1642 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1647 | 1643 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1648 | 1644 | call sys.excepthook will generate a regular-looking exception from |
|
1649 | 1645 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1650 | 1646 | crashes. |
|
1651 | 1647 | |
|
1652 | 1648 | This hook should be used sparingly, only in places which are not likely |
|
1653 | 1649 | to be true IPython errors. |
|
1654 | 1650 | """ |
|
1655 | 1651 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1656 | 1652 | |
|
1657 | 1653 | def _get_exc_info(self, exc_tuple=None): |
|
1658 | 1654 | """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc. |
|
1659 | 1655 | |
|
1660 | 1656 | Ensures sys.last_type,value,traceback hold the exc_info we found, |
|
1661 | 1657 | from whichever source. |
|
1662 | 1658 | |
|
1663 | 1659 | raises ValueError if none of these contain any information |
|
1664 | 1660 | """ |
|
1665 | 1661 | if exc_tuple is None: |
|
1666 | 1662 | etype, value, tb = sys.exc_info() |
|
1667 | 1663 | else: |
|
1668 | 1664 | etype, value, tb = exc_tuple |
|
1669 | 1665 | |
|
1670 | 1666 | if etype is None: |
|
1671 | 1667 | if hasattr(sys, 'last_type'): |
|
1672 | 1668 | etype, value, tb = sys.last_type, sys.last_value, \ |
|
1673 | 1669 | sys.last_traceback |
|
1674 | 1670 | |
|
1675 | 1671 | if etype is None: |
|
1676 | 1672 | raise ValueError("No exception to find") |
|
1677 | 1673 | |
|
1678 | 1674 | # Now store the exception info in sys.last_type etc. |
|
1679 | 1675 | # WARNING: these variables are somewhat deprecated and not |
|
1680 | 1676 | # necessarily safe to use in a threaded environment, but tools |
|
1681 | 1677 | # like pdb depend on their existence, so let's set them. If we |
|
1682 | 1678 | # find problems in the field, we'll need to revisit their use. |
|
1683 | 1679 | sys.last_type = etype |
|
1684 | 1680 | sys.last_value = value |
|
1685 | 1681 | sys.last_traceback = tb |
|
1686 | 1682 | |
|
1687 | 1683 | return etype, value, tb |
|
1688 | 1684 | |
|
1689 | 1685 | def show_usage_error(self, exc): |
|
1690 | 1686 | """Show a short message for UsageErrors |
|
1691 | 1687 | |
|
1692 | 1688 | These are special exceptions that shouldn't show a traceback. |
|
1693 | 1689 | """ |
|
1694 | 1690 | self.write_err("UsageError: %s" % exc) |
|
1695 | 1691 | |
|
1696 | 1692 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, |
|
1697 | 1693 | exception_only=False): |
|
1698 | 1694 | """Display the exception that just occurred. |
|
1699 | 1695 | |
|
1700 | 1696 | If nothing is known about the exception, this is the method which |
|
1701 | 1697 | should be used throughout the code for presenting user tracebacks, |
|
1702 | 1698 | rather than directly invoking the InteractiveTB object. |
|
1703 | 1699 | |
|
1704 | 1700 | A specific showsyntaxerror() also exists, but this method can take |
|
1705 | 1701 | care of calling it if needed, so unless you are explicitly catching a |
|
1706 | 1702 | SyntaxError exception, don't try to analyze the stack manually and |
|
1707 | 1703 | simply call this method.""" |
|
1708 | 1704 | |
|
1709 | 1705 | try: |
|
1710 | 1706 | try: |
|
1711 | 1707 | etype, value, tb = self._get_exc_info(exc_tuple) |
|
1712 | 1708 | except ValueError: |
|
1713 | 1709 | self.write_err('No traceback available to show.\n') |
|
1714 | 1710 | return |
|
1715 | 1711 | |
|
1716 | 1712 | if issubclass(etype, SyntaxError): |
|
1717 | 1713 | # Though this won't be called by syntax errors in the input |
|
1718 | 1714 | # line, there may be SyntaxError cases with imported code. |
|
1719 | 1715 | self.showsyntaxerror(filename) |
|
1720 | 1716 | elif etype is UsageError: |
|
1721 | 1717 | self.show_usage_error(value) |
|
1722 | 1718 | else: |
|
1723 | 1719 | if exception_only: |
|
1724 | 1720 | stb = ['An exception has occurred, use %tb to see ' |
|
1725 | 1721 | 'the full traceback.\n'] |
|
1726 | 1722 | stb.extend(self.InteractiveTB.get_exception_only(etype, |
|
1727 | 1723 | value)) |
|
1728 | 1724 | else: |
|
1729 | 1725 | try: |
|
1730 | 1726 | # Exception classes can customise their traceback - we |
|
1731 | 1727 | # use this in IPython.parallel for exceptions occurring |
|
1732 | 1728 | # in the engines. This should return a list of strings. |
|
1733 | 1729 | stb = value._render_traceback_() |
|
1734 | 1730 | except Exception: |
|
1735 | 1731 | stb = self.InteractiveTB.structured_traceback(etype, |
|
1736 | 1732 | value, tb, tb_offset=tb_offset) |
|
1737 | 1733 | |
|
1738 | 1734 | self._showtraceback(etype, value, stb) |
|
1739 | 1735 | if self.call_pdb: |
|
1740 | 1736 | # drop into debugger |
|
1741 | 1737 | self.debugger(force=True) |
|
1742 | 1738 | return |
|
1743 | 1739 | |
|
1744 | 1740 | # Actually show the traceback |
|
1745 | 1741 | self._showtraceback(etype, value, stb) |
|
1746 | 1742 | |
|
1747 | 1743 | except KeyboardInterrupt: |
|
1748 | 1744 | self.write_err("\nKeyboardInterrupt\n") |
|
1749 | 1745 | |
|
1750 | 1746 | def _showtraceback(self, etype, evalue, stb): |
|
1751 | 1747 | """Actually show a traceback. |
|
1752 | 1748 | |
|
1753 | 1749 | Subclasses may override this method to put the traceback on a different |
|
1754 | 1750 | place, like a side channel. |
|
1755 | 1751 | """ |
|
1756 | 1752 | print(self.InteractiveTB.stb2text(stb), file=io.stdout) |
|
1757 | 1753 | |
|
1758 | 1754 | def showsyntaxerror(self, filename=None): |
|
1759 | 1755 | """Display the syntax error that just occurred. |
|
1760 | 1756 | |
|
1761 | 1757 | This doesn't display a stack trace because there isn't one. |
|
1762 | 1758 | |
|
1763 | 1759 | If a filename is given, it is stuffed in the exception instead |
|
1764 | 1760 | of what was there before (because Python's parser always uses |
|
1765 | 1761 | "<string>" when reading from a string). |
|
1766 | 1762 | """ |
|
1767 | 1763 | etype, value, last_traceback = self._get_exc_info() |
|
1768 | 1764 | |
|
1769 | 1765 | if filename and issubclass(etype, SyntaxError): |
|
1770 | 1766 | try: |
|
1771 | 1767 | value.filename = filename |
|
1772 | 1768 | except: |
|
1773 | 1769 | # Not the format we expect; leave it alone |
|
1774 | 1770 | pass |
|
1775 | 1771 | |
|
1776 | 1772 | stb = self.SyntaxTB.structured_traceback(etype, value, []) |
|
1777 | 1773 | self._showtraceback(etype, value, stb) |
|
1778 | 1774 | |
|
1779 | 1775 | # This is overridden in TerminalInteractiveShell to show a message about |
|
1780 | 1776 | # the %paste magic. |
|
1781 | 1777 | def showindentationerror(self): |
|
1782 | 1778 | """Called by run_cell when there's an IndentationError in code entered |
|
1783 | 1779 | at the prompt. |
|
1784 | 1780 | |
|
1785 | 1781 | This is overridden in TerminalInteractiveShell to show a message about |
|
1786 | 1782 | the %paste magic.""" |
|
1787 | 1783 | self.showsyntaxerror() |
|
1788 | 1784 | |
|
1789 | 1785 | #------------------------------------------------------------------------- |
|
1790 | 1786 | # Things related to readline |
|
1791 | 1787 | #------------------------------------------------------------------------- |
|
1792 | 1788 | |
|
1793 | 1789 | def init_readline(self): |
|
1794 | 1790 | """Command history completion/saving/reloading.""" |
|
1795 | 1791 | |
|
1796 | 1792 | if self.readline_use: |
|
1797 | 1793 | import IPython.utils.rlineimpl as readline |
|
1798 | 1794 | |
|
1799 | 1795 | self.rl_next_input = None |
|
1800 | 1796 | self.rl_do_indent = False |
|
1801 | 1797 | |
|
1802 | 1798 | if not self.readline_use or not readline.have_readline: |
|
1803 | 1799 | self.has_readline = False |
|
1804 | 1800 | self.readline = None |
|
1805 | 1801 | # Set a number of methods that depend on readline to be no-op |
|
1806 | 1802 | self.readline_no_record = no_op_context |
|
1807 | 1803 | self.set_readline_completer = no_op |
|
1808 | 1804 | self.set_custom_completer = no_op |
|
1809 | 1805 | if self.readline_use: |
|
1810 | 1806 | warn('Readline services not available or not loaded.') |
|
1811 | 1807 | else: |
|
1812 | 1808 | self.has_readline = True |
|
1813 | 1809 | self.readline = readline |
|
1814 | 1810 | sys.modules['readline'] = readline |
|
1815 | 1811 | |
|
1816 | 1812 | # Platform-specific configuration |
|
1817 | 1813 | if os.name == 'nt': |
|
1818 | 1814 | # FIXME - check with Frederick to see if we can harmonize |
|
1819 | 1815 | # naming conventions with pyreadline to avoid this |
|
1820 | 1816 | # platform-dependent check |
|
1821 | 1817 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1822 | 1818 | else: |
|
1823 | 1819 | self.readline_startup_hook = readline.set_startup_hook |
|
1824 | 1820 | |
|
1825 | 1821 | # Load user's initrc file (readline config) |
|
1826 | 1822 | # Or if libedit is used, load editrc. |
|
1827 | 1823 | inputrc_name = os.environ.get('INPUTRC') |
|
1828 | 1824 | if inputrc_name is None: |
|
1829 | 1825 | inputrc_name = '.inputrc' |
|
1830 | 1826 | if readline.uses_libedit: |
|
1831 | 1827 | inputrc_name = '.editrc' |
|
1832 | 1828 | inputrc_name = os.path.join(self.home_dir, inputrc_name) |
|
1833 | 1829 | if os.path.isfile(inputrc_name): |
|
1834 | 1830 | try: |
|
1835 | 1831 | readline.read_init_file(inputrc_name) |
|
1836 | 1832 | except: |
|
1837 | 1833 | warn('Problems reading readline initialization file <%s>' |
|
1838 | 1834 | % inputrc_name) |
|
1839 | 1835 | |
|
1840 | 1836 | # Configure readline according to user's prefs |
|
1841 | 1837 | # This is only done if GNU readline is being used. If libedit |
|
1842 | 1838 | # is being used (as on Leopard) the readline config is |
|
1843 | 1839 | # not run as the syntax for libedit is different. |
|
1844 | 1840 | if not readline.uses_libedit: |
|
1845 | 1841 | for rlcommand in self.readline_parse_and_bind: |
|
1846 | 1842 | #print "loading rl:",rlcommand # dbg |
|
1847 | 1843 | readline.parse_and_bind(rlcommand) |
|
1848 | 1844 | |
|
1849 | 1845 | # Remove some chars from the delimiters list. If we encounter |
|
1850 | 1846 | # unicode chars, discard them. |
|
1851 | 1847 | delims = readline.get_completer_delims() |
|
1852 | 1848 | if not py3compat.PY3: |
|
1853 | 1849 | delims = delims.encode("ascii", "ignore") |
|
1854 | 1850 | for d in self.readline_remove_delims: |
|
1855 | 1851 | delims = delims.replace(d, "") |
|
1856 | 1852 | delims = delims.replace(ESC_MAGIC, '') |
|
1857 | 1853 | readline.set_completer_delims(delims) |
|
1858 | 1854 | # Store these so we can restore them if something like rpy2 modifies |
|
1859 | 1855 | # them. |
|
1860 | 1856 | self.readline_delims = delims |
|
1861 | 1857 | # otherwise we end up with a monster history after a while: |
|
1862 | 1858 | readline.set_history_length(self.history_length) |
|
1863 | 1859 | |
|
1864 | 1860 | self.refill_readline_hist() |
|
1865 | 1861 | self.readline_no_record = ReadlineNoRecord(self) |
|
1866 | 1862 | |
|
1867 | 1863 | # Configure auto-indent for all platforms |
|
1868 | 1864 | self.set_autoindent(self.autoindent) |
|
1869 | 1865 | |
|
1870 | 1866 | def refill_readline_hist(self): |
|
1871 | 1867 | # Load the last 1000 lines from history |
|
1872 | 1868 | self.readline.clear_history() |
|
1873 | 1869 | stdin_encoding = sys.stdin.encoding or "utf-8" |
|
1874 | 1870 | last_cell = u"" |
|
1875 | 1871 | for _, _, cell in self.history_manager.get_tail(1000, |
|
1876 | 1872 | include_latest=True): |
|
1877 | 1873 | # Ignore blank lines and consecutive duplicates |
|
1878 | 1874 | cell = cell.rstrip() |
|
1879 | 1875 | if cell and (cell != last_cell): |
|
1880 | 1876 | try: |
|
1881 | 1877 | if self.multiline_history: |
|
1882 | 1878 | self.readline.add_history(py3compat.unicode_to_str(cell, |
|
1883 | 1879 | stdin_encoding)) |
|
1884 | 1880 | else: |
|
1885 | 1881 | for line in cell.splitlines(): |
|
1886 | 1882 | self.readline.add_history(py3compat.unicode_to_str(line, |
|
1887 | 1883 | stdin_encoding)) |
|
1888 | 1884 | last_cell = cell |
|
1889 | 1885 | |
|
1890 | 1886 | except TypeError: |
|
1891 | 1887 | # The history DB can get corrupted so it returns strings |
|
1892 | 1888 | # containing null bytes, which readline objects to. |
|
1893 | 1889 | continue |
|
1894 | 1890 | |
|
1895 | 1891 | @skip_doctest |
|
1896 | 1892 | def set_next_input(self, s): |
|
1897 | 1893 | """ Sets the 'default' input string for the next command line. |
|
1898 | 1894 | |
|
1899 | 1895 | Requires readline. |
|
1900 | 1896 | |
|
1901 | 1897 | Example:: |
|
1902 | 1898 | |
|
1903 | 1899 | In [1]: _ip.set_next_input("Hello Word") |
|
1904 | 1900 | In [2]: Hello Word_ # cursor is here |
|
1905 | 1901 | """ |
|
1906 | 1902 | self.rl_next_input = py3compat.cast_bytes_py2(s) |
|
1907 | 1903 | |
|
1908 | 1904 | # Maybe move this to the terminal subclass? |
|
1909 | 1905 | def pre_readline(self): |
|
1910 | 1906 | """readline hook to be used at the start of each line. |
|
1911 | 1907 | |
|
1912 | 1908 | Currently it handles auto-indent only.""" |
|
1913 | 1909 | |
|
1914 | 1910 | if self.rl_do_indent: |
|
1915 | 1911 | self.readline.insert_text(self._indent_current_str()) |
|
1916 | 1912 | if self.rl_next_input is not None: |
|
1917 | 1913 | self.readline.insert_text(self.rl_next_input) |
|
1918 | 1914 | self.rl_next_input = None |
|
1919 | 1915 | |
|
1920 | 1916 | def _indent_current_str(self): |
|
1921 | 1917 | """return the current level of indentation as a string""" |
|
1922 | 1918 | return self.input_splitter.indent_spaces * ' ' |
|
1923 | 1919 | |
|
1924 | 1920 | #------------------------------------------------------------------------- |
|
1925 | 1921 | # Things related to text completion |
|
1926 | 1922 | #------------------------------------------------------------------------- |
|
1927 | 1923 | |
|
1928 | 1924 | def init_completer(self): |
|
1929 | 1925 | """Initialize the completion machinery. |
|
1930 | 1926 | |
|
1931 | 1927 | This creates completion machinery that can be used by client code, |
|
1932 | 1928 | either interactively in-process (typically triggered by the readline |
|
1933 | 1929 | library), programatically (such as in test suites) or out-of-prcess |
|
1934 | 1930 | (typically over the network by remote frontends). |
|
1935 | 1931 | """ |
|
1936 | 1932 | from IPython.core.completer import IPCompleter |
|
1937 | 1933 | from IPython.core.completerlib import (module_completer, |
|
1938 | 1934 | magic_run_completer, cd_completer, reset_completer) |
|
1939 | 1935 | |
|
1940 | 1936 | self.Completer = IPCompleter(shell=self, |
|
1941 | 1937 | namespace=self.user_ns, |
|
1942 | 1938 | global_namespace=self.user_global_ns, |
|
1943 | alias_table=self.alias_manager.alias_table, | |
|
1944 | 1939 | use_readline=self.has_readline, |
|
1945 | 1940 | parent=self, |
|
1946 | 1941 | ) |
|
1947 | 1942 | self.configurables.append(self.Completer) |
|
1948 | 1943 | |
|
1949 | 1944 | # Add custom completers to the basic ones built into IPCompleter |
|
1950 | 1945 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1951 | 1946 | self.strdispatchers['complete_command'] = sdisp |
|
1952 | 1947 | self.Completer.custom_completers = sdisp |
|
1953 | 1948 | |
|
1954 | 1949 | self.set_hook('complete_command', module_completer, str_key = 'import') |
|
1955 | 1950 | self.set_hook('complete_command', module_completer, str_key = 'from') |
|
1956 | 1951 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') |
|
1957 | 1952 | self.set_hook('complete_command', cd_completer, str_key = '%cd') |
|
1958 | 1953 | self.set_hook('complete_command', reset_completer, str_key = '%reset') |
|
1959 | 1954 | |
|
1960 | 1955 | # Only configure readline if we truly are using readline. IPython can |
|
1961 | 1956 | # do tab-completion over the network, in GUIs, etc, where readline |
|
1962 | 1957 | # itself may be absent |
|
1963 | 1958 | if self.has_readline: |
|
1964 | 1959 | self.set_readline_completer() |
|
1965 | 1960 | |
|
1966 | 1961 | def complete(self, text, line=None, cursor_pos=None): |
|
1967 | 1962 | """Return the completed text and a list of completions. |
|
1968 | 1963 | |
|
1969 | 1964 | Parameters |
|
1970 | 1965 | ---------- |
|
1971 | 1966 | |
|
1972 | 1967 | text : string |
|
1973 | 1968 | A string of text to be completed on. It can be given as empty and |
|
1974 | 1969 | instead a line/position pair are given. In this case, the |
|
1975 | 1970 | completer itself will split the line like readline does. |
|
1976 | 1971 | |
|
1977 | 1972 | line : string, optional |
|
1978 | 1973 | The complete line that text is part of. |
|
1979 | 1974 | |
|
1980 | 1975 | cursor_pos : int, optional |
|
1981 | 1976 | The position of the cursor on the input line. |
|
1982 | 1977 | |
|
1983 | 1978 | Returns |
|
1984 | 1979 | ------- |
|
1985 | 1980 | text : string |
|
1986 | 1981 | The actual text that was completed. |
|
1987 | 1982 | |
|
1988 | 1983 | matches : list |
|
1989 | 1984 | A sorted list with all possible completions. |
|
1990 | 1985 | |
|
1991 | 1986 | The optional arguments allow the completion to take more context into |
|
1992 | 1987 | account, and are part of the low-level completion API. |
|
1993 | 1988 | |
|
1994 | 1989 | This is a wrapper around the completion mechanism, similar to what |
|
1995 | 1990 | readline does at the command line when the TAB key is hit. By |
|
1996 | 1991 | exposing it as a method, it can be used by other non-readline |
|
1997 | 1992 | environments (such as GUIs) for text completion. |
|
1998 | 1993 | |
|
1999 | 1994 | Simple usage example: |
|
2000 | 1995 | |
|
2001 | 1996 | In [1]: x = 'hello' |
|
2002 | 1997 | |
|
2003 | 1998 | In [2]: _ip.complete('x.l') |
|
2004 | 1999 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) |
|
2005 | 2000 | """ |
|
2006 | 2001 | |
|
2007 | 2002 | # Inject names into __builtin__ so we can complete on the added names. |
|
2008 | 2003 | with self.builtin_trap: |
|
2009 | 2004 | return self.Completer.complete(text, line, cursor_pos) |
|
2010 | 2005 | |
|
2011 | 2006 | def set_custom_completer(self, completer, pos=0): |
|
2012 | 2007 | """Adds a new custom completer function. |
|
2013 | 2008 | |
|
2014 | 2009 | The position argument (defaults to 0) is the index in the completers |
|
2015 | 2010 | list where you want the completer to be inserted.""" |
|
2016 | 2011 | |
|
2017 | 2012 | newcomp = types.MethodType(completer,self.Completer) |
|
2018 | 2013 | self.Completer.matchers.insert(pos,newcomp) |
|
2019 | 2014 | |
|
2020 | 2015 | def set_readline_completer(self): |
|
2021 | 2016 | """Reset readline's completer to be our own.""" |
|
2022 | 2017 | self.readline.set_completer(self.Completer.rlcomplete) |
|
2023 | 2018 | |
|
2024 | 2019 | def set_completer_frame(self, frame=None): |
|
2025 | 2020 | """Set the frame of the completer.""" |
|
2026 | 2021 | if frame: |
|
2027 | 2022 | self.Completer.namespace = frame.f_locals |
|
2028 | 2023 | self.Completer.global_namespace = frame.f_globals |
|
2029 | 2024 | else: |
|
2030 | 2025 | self.Completer.namespace = self.user_ns |
|
2031 | 2026 | self.Completer.global_namespace = self.user_global_ns |
|
2032 | 2027 | |
|
2033 | 2028 | #------------------------------------------------------------------------- |
|
2034 | 2029 | # Things related to magics |
|
2035 | 2030 | #------------------------------------------------------------------------- |
|
2036 | 2031 | |
|
2037 | 2032 | def init_magics(self): |
|
2038 | 2033 | from IPython.core import magics as m |
|
2039 | 2034 | self.magics_manager = magic.MagicsManager(shell=self, |
|
2040 | 2035 | parent=self, |
|
2041 | 2036 | user_magics=m.UserMagics(self)) |
|
2042 | 2037 | self.configurables.append(self.magics_manager) |
|
2043 | 2038 | |
|
2044 | 2039 | # Expose as public API from the magics manager |
|
2045 | 2040 | self.register_magics = self.magics_manager.register |
|
2046 | 2041 | self.define_magic = self.magics_manager.define_magic |
|
2047 | 2042 | |
|
2048 | 2043 | self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics, |
|
2049 | 2044 | m.ConfigMagics, m.DeprecatedMagics, m.DisplayMagics, m.ExecutionMagics, |
|
2050 | 2045 | m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics, |
|
2051 | 2046 | m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics, |
|
2052 | 2047 | ) |
|
2053 | 2048 | |
|
2054 | 2049 | # Register Magic Aliases |
|
2055 | 2050 | mman = self.magics_manager |
|
2056 | 2051 | # FIXME: magic aliases should be defined by the Magics classes |
|
2057 | 2052 | # or in MagicsManager, not here |
|
2058 | 2053 | mman.register_alias('ed', 'edit') |
|
2059 | 2054 | mman.register_alias('hist', 'history') |
|
2060 | 2055 | mman.register_alias('rep', 'recall') |
|
2061 | 2056 | mman.register_alias('SVG', 'svg', 'cell') |
|
2062 | 2057 | mman.register_alias('HTML', 'html', 'cell') |
|
2063 | 2058 | mman.register_alias('file', 'writefile', 'cell') |
|
2064 | 2059 | |
|
2065 | 2060 | # FIXME: Move the color initialization to the DisplayHook, which |
|
2066 | 2061 | # should be split into a prompt manager and displayhook. We probably |
|
2067 | 2062 | # even need a centralize colors management object. |
|
2068 | 2063 | self.magic('colors %s' % self.colors) |
|
2069 | 2064 | |
|
2070 | 2065 | # Defined here so that it's included in the documentation |
|
2071 | 2066 | @functools.wraps(magic.MagicsManager.register_function) |
|
2072 | 2067 | def register_magic_function(self, func, magic_kind='line', magic_name=None): |
|
2073 | 2068 | self.magics_manager.register_function(func, |
|
2074 | 2069 | magic_kind=magic_kind, magic_name=magic_name) |
|
2075 | 2070 | |
|
2076 | 2071 | def run_line_magic(self, magic_name, line): |
|
2077 | 2072 | """Execute the given line magic. |
|
2078 | 2073 | |
|
2079 | 2074 | Parameters |
|
2080 | 2075 | ---------- |
|
2081 | 2076 | magic_name : str |
|
2082 | 2077 | Name of the desired magic function, without '%' prefix. |
|
2083 | 2078 | |
|
2084 | 2079 | line : str |
|
2085 | 2080 | The rest of the input line as a single string. |
|
2086 | 2081 | """ |
|
2087 | 2082 | fn = self.find_line_magic(magic_name) |
|
2088 | 2083 | if fn is None: |
|
2089 | 2084 | cm = self.find_cell_magic(magic_name) |
|
2090 | 2085 | etpl = "Line magic function `%%%s` not found%s." |
|
2091 | 2086 | extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, ' |
|
2092 | 2087 | 'did you mean that instead?)' % magic_name ) |
|
2093 | 2088 | error(etpl % (magic_name, extra)) |
|
2094 | 2089 | else: |
|
2095 | 2090 | # Note: this is the distance in the stack to the user's frame. |
|
2096 | 2091 | # This will need to be updated if the internal calling logic gets |
|
2097 | 2092 | # refactored, or else we'll be expanding the wrong variables. |
|
2098 | 2093 | stack_depth = 2 |
|
2099 | 2094 | magic_arg_s = self.var_expand(line, stack_depth) |
|
2100 | 2095 | # Put magic args in a list so we can call with f(*a) syntax |
|
2101 | 2096 | args = [magic_arg_s] |
|
2102 | 2097 | kwargs = {} |
|
2103 | 2098 | # Grab local namespace if we need it: |
|
2104 | 2099 | if getattr(fn, "needs_local_scope", False): |
|
2105 | 2100 | kwargs['local_ns'] = sys._getframe(stack_depth).f_locals |
|
2106 | 2101 | with self.builtin_trap: |
|
2107 | 2102 | result = fn(*args,**kwargs) |
|
2108 | 2103 | return result |
|
2109 | 2104 | |
|
2110 | 2105 | def run_cell_magic(self, magic_name, line, cell): |
|
2111 | 2106 | """Execute the given cell magic. |
|
2112 | 2107 | |
|
2113 | 2108 | Parameters |
|
2114 | 2109 | ---------- |
|
2115 | 2110 | magic_name : str |
|
2116 | 2111 | Name of the desired magic function, without '%' prefix. |
|
2117 | 2112 | |
|
2118 | 2113 | line : str |
|
2119 | 2114 | The rest of the first input line as a single string. |
|
2120 | 2115 | |
|
2121 | 2116 | cell : str |
|
2122 | 2117 | The body of the cell as a (possibly multiline) string. |
|
2123 | 2118 | """ |
|
2124 | 2119 | fn = self.find_cell_magic(magic_name) |
|
2125 | 2120 | if fn is None: |
|
2126 | 2121 | lm = self.find_line_magic(magic_name) |
|
2127 | 2122 | etpl = "Cell magic `%%{0}` not found{1}." |
|
2128 | 2123 | extra = '' if lm is None else (' (But line magic `%{0}` exists, ' |
|
2129 | 2124 | 'did you mean that instead?)'.format(magic_name)) |
|
2130 | 2125 | error(etpl.format(magic_name, extra)) |
|
2131 | 2126 | elif cell == '': |
|
2132 | 2127 | message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name) |
|
2133 | 2128 | if self.find_line_magic(magic_name) is not None: |
|
2134 | 2129 | message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name) |
|
2135 | 2130 | raise UsageError(message) |
|
2136 | 2131 | else: |
|
2137 | 2132 | # Note: this is the distance in the stack to the user's frame. |
|
2138 | 2133 | # This will need to be updated if the internal calling logic gets |
|
2139 | 2134 | # refactored, or else we'll be expanding the wrong variables. |
|
2140 | 2135 | stack_depth = 2 |
|
2141 | 2136 | magic_arg_s = self.var_expand(line, stack_depth) |
|
2142 | 2137 | with self.builtin_trap: |
|
2143 | 2138 | result = fn(magic_arg_s, cell) |
|
2144 | 2139 | return result |
|
2145 | 2140 | |
|
2146 | 2141 | def find_line_magic(self, magic_name): |
|
2147 | 2142 | """Find and return a line magic by name. |
|
2148 | 2143 | |
|
2149 | 2144 | Returns None if the magic isn't found.""" |
|
2150 | 2145 | return self.magics_manager.magics['line'].get(magic_name) |
|
2151 | 2146 | |
|
2152 | 2147 | def find_cell_magic(self, magic_name): |
|
2153 | 2148 | """Find and return a cell magic by name. |
|
2154 | 2149 | |
|
2155 | 2150 | Returns None if the magic isn't found.""" |
|
2156 | 2151 | return self.magics_manager.magics['cell'].get(magic_name) |
|
2157 | 2152 | |
|
2158 | 2153 | def find_magic(self, magic_name, magic_kind='line'): |
|
2159 | 2154 | """Find and return a magic of the given type by name. |
|
2160 | 2155 | |
|
2161 | 2156 | Returns None if the magic isn't found.""" |
|
2162 | 2157 | return self.magics_manager.magics[magic_kind].get(magic_name) |
|
2163 | 2158 | |
|
2164 | 2159 | def magic(self, arg_s): |
|
2165 | 2160 | """DEPRECATED. Use run_line_magic() instead. |
|
2166 | 2161 | |
|
2167 | 2162 | Call a magic function by name. |
|
2168 | 2163 | |
|
2169 | 2164 | Input: a string containing the name of the magic function to call and |
|
2170 | 2165 | any additional arguments to be passed to the magic. |
|
2171 | 2166 | |
|
2172 | 2167 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
2173 | 2168 | prompt: |
|
2174 | 2169 | |
|
2175 | 2170 | In[1]: %name -opt foo bar |
|
2176 | 2171 | |
|
2177 | 2172 | To call a magic without arguments, simply use magic('name'). |
|
2178 | 2173 | |
|
2179 | 2174 | This provides a proper Python function to call IPython's magics in any |
|
2180 | 2175 | valid Python code you can type at the interpreter, including loops and |
|
2181 | 2176 | compound statements. |
|
2182 | 2177 | """ |
|
2183 | 2178 | # TODO: should we issue a loud deprecation warning here? |
|
2184 | 2179 | magic_name, _, magic_arg_s = arg_s.partition(' ') |
|
2185 | 2180 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
2186 | 2181 | return self.run_line_magic(magic_name, magic_arg_s) |
|
2187 | 2182 | |
|
2188 | 2183 | #------------------------------------------------------------------------- |
|
2189 | 2184 | # Things related to macros |
|
2190 | 2185 | #------------------------------------------------------------------------- |
|
2191 | 2186 | |
|
2192 | 2187 | def define_macro(self, name, themacro): |
|
2193 | 2188 | """Define a new macro |
|
2194 | 2189 | |
|
2195 | 2190 | Parameters |
|
2196 | 2191 | ---------- |
|
2197 | 2192 | name : str |
|
2198 | 2193 | The name of the macro. |
|
2199 | 2194 | themacro : str or Macro |
|
2200 | 2195 | The action to do upon invoking the macro. If a string, a new |
|
2201 | 2196 | Macro object is created by passing the string to it. |
|
2202 | 2197 | """ |
|
2203 | 2198 | |
|
2204 | 2199 | from IPython.core import macro |
|
2205 | 2200 | |
|
2206 | 2201 | if isinstance(themacro, basestring): |
|
2207 | 2202 | themacro = macro.Macro(themacro) |
|
2208 | 2203 | if not isinstance(themacro, macro.Macro): |
|
2209 | 2204 | raise ValueError('A macro must be a string or a Macro instance.') |
|
2210 | 2205 | self.user_ns[name] = themacro |
|
2211 | 2206 | |
|
2212 | 2207 | #------------------------------------------------------------------------- |
|
2213 | 2208 | # Things related to the running of system commands |
|
2214 | 2209 | #------------------------------------------------------------------------- |
|
2215 | 2210 | |
|
2216 | 2211 | def system_piped(self, cmd): |
|
2217 | 2212 | """Call the given cmd in a subprocess, piping stdout/err |
|
2218 | 2213 | |
|
2219 | 2214 | Parameters |
|
2220 | 2215 | ---------- |
|
2221 | 2216 | cmd : str |
|
2222 | 2217 | Command to execute (can not end in '&', as background processes are |
|
2223 | 2218 | not supported. Should not be a command that expects input |
|
2224 | 2219 | other than simple text. |
|
2225 | 2220 | """ |
|
2226 | 2221 | if cmd.rstrip().endswith('&'): |
|
2227 | 2222 | # this is *far* from a rigorous test |
|
2228 | 2223 | # We do not support backgrounding processes because we either use |
|
2229 | 2224 | # pexpect or pipes to read from. Users can always just call |
|
2230 | 2225 | # os.system() or use ip.system=ip.system_raw |
|
2231 | 2226 | # if they really want a background process. |
|
2232 | 2227 | raise OSError("Background processes not supported.") |
|
2233 | 2228 | |
|
2234 | 2229 | # we explicitly do NOT return the subprocess status code, because |
|
2235 | 2230 | # a non-None value would trigger :func:`sys.displayhook` calls. |
|
2236 | 2231 | # Instead, we store the exit_code in user_ns. |
|
2237 | 2232 | self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1)) |
|
2238 | 2233 | |
|
2239 | 2234 | def system_raw(self, cmd): |
|
2240 | 2235 | """Call the given cmd in a subprocess using os.system |
|
2241 | 2236 | |
|
2242 | 2237 | Parameters |
|
2243 | 2238 | ---------- |
|
2244 | 2239 | cmd : str |
|
2245 | 2240 | Command to execute. |
|
2246 | 2241 | """ |
|
2247 | 2242 | cmd = self.var_expand(cmd, depth=1) |
|
2248 | 2243 | # protect os.system from UNC paths on Windows, which it can't handle: |
|
2249 | 2244 | if sys.platform == 'win32': |
|
2250 | 2245 | from IPython.utils._process_win32 import AvoidUNCPath |
|
2251 | 2246 | with AvoidUNCPath() as path: |
|
2252 | 2247 | if path is not None: |
|
2253 | 2248 | cmd = '"pushd %s &&"%s' % (path, cmd) |
|
2254 | 2249 | cmd = py3compat.unicode_to_str(cmd) |
|
2255 | 2250 | ec = os.system(cmd) |
|
2256 | 2251 | else: |
|
2257 | 2252 | cmd = py3compat.unicode_to_str(cmd) |
|
2258 | 2253 | ec = os.system(cmd) |
|
2259 | 2254 | # The high byte is the exit code, the low byte is a signal number |
|
2260 | 2255 | # that we discard for now. See the docs for os.wait() |
|
2261 | 2256 | if ec > 255: |
|
2262 | 2257 | ec >>= 8 |
|
2263 | 2258 | |
|
2264 | 2259 | # We explicitly do NOT return the subprocess status code, because |
|
2265 | 2260 | # a non-None value would trigger :func:`sys.displayhook` calls. |
|
2266 | 2261 | # Instead, we store the exit_code in user_ns. |
|
2267 | 2262 | self.user_ns['_exit_code'] = ec |
|
2268 | 2263 | |
|
2269 | 2264 | # use piped system by default, because it is better behaved |
|
2270 | 2265 | system = system_piped |
|
2271 | 2266 | |
|
2272 | 2267 | def getoutput(self, cmd, split=True, depth=0): |
|
2273 | 2268 | """Get output (possibly including stderr) from a subprocess. |
|
2274 | 2269 | |
|
2275 | 2270 | Parameters |
|
2276 | 2271 | ---------- |
|
2277 | 2272 | cmd : str |
|
2278 | 2273 | Command to execute (can not end in '&', as background processes are |
|
2279 | 2274 | not supported. |
|
2280 | 2275 | split : bool, optional |
|
2281 | 2276 | If True, split the output into an IPython SList. Otherwise, an |
|
2282 | 2277 | IPython LSString is returned. These are objects similar to normal |
|
2283 | 2278 | lists and strings, with a few convenience attributes for easier |
|
2284 | 2279 | manipulation of line-based output. You can use '?' on them for |
|
2285 | 2280 | details. |
|
2286 | 2281 | depth : int, optional |
|
2287 | 2282 | How many frames above the caller are the local variables which should |
|
2288 | 2283 | be expanded in the command string? The default (0) assumes that the |
|
2289 | 2284 | expansion variables are in the stack frame calling this function. |
|
2290 | 2285 | """ |
|
2291 | 2286 | if cmd.rstrip().endswith('&'): |
|
2292 | 2287 | # this is *far* from a rigorous test |
|
2293 | 2288 | raise OSError("Background processes not supported.") |
|
2294 | 2289 | out = getoutput(self.var_expand(cmd, depth=depth+1)) |
|
2295 | 2290 | if split: |
|
2296 | 2291 | out = SList(out.splitlines()) |
|
2297 | 2292 | else: |
|
2298 | 2293 | out = LSString(out) |
|
2299 | 2294 | return out |
|
2300 | 2295 | |
|
2301 | 2296 | #------------------------------------------------------------------------- |
|
2302 | 2297 | # Things related to aliases |
|
2303 | 2298 | #------------------------------------------------------------------------- |
|
2304 | 2299 | |
|
2305 | 2300 | def init_alias(self): |
|
2306 | 2301 | self.alias_manager = AliasManager(shell=self, parent=self) |
|
2307 | 2302 | self.configurables.append(self.alias_manager) |
|
2308 | self.ns_table['alias'] = self.alias_manager.alias_table, | |
|
2309 | 2303 | |
|
2310 | 2304 | #------------------------------------------------------------------------- |
|
2311 | 2305 | # Things related to extensions |
|
2312 | 2306 | #------------------------------------------------------------------------- |
|
2313 | 2307 | |
|
2314 | 2308 | def init_extension_manager(self): |
|
2315 | 2309 | self.extension_manager = ExtensionManager(shell=self, parent=self) |
|
2316 | 2310 | self.configurables.append(self.extension_manager) |
|
2317 | 2311 | |
|
2318 | 2312 | #------------------------------------------------------------------------- |
|
2319 | 2313 | # Things related to payloads |
|
2320 | 2314 | #------------------------------------------------------------------------- |
|
2321 | 2315 | |
|
2322 | 2316 | def init_payload(self): |
|
2323 | 2317 | self.payload_manager = PayloadManager(parent=self) |
|
2324 | 2318 | self.configurables.append(self.payload_manager) |
|
2325 | 2319 | |
|
2326 | 2320 | #------------------------------------------------------------------------- |
|
2327 | 2321 | # Things related to the prefilter |
|
2328 | 2322 | #------------------------------------------------------------------------- |
|
2329 | 2323 | |
|
2330 | 2324 | def init_prefilter(self): |
|
2331 | 2325 | self.prefilter_manager = PrefilterManager(shell=self, parent=self) |
|
2332 | 2326 | self.configurables.append(self.prefilter_manager) |
|
2333 | 2327 | # Ultimately this will be refactored in the new interpreter code, but |
|
2334 | 2328 | # for now, we should expose the main prefilter method (there's legacy |
|
2335 | 2329 | # code out there that may rely on this). |
|
2336 | 2330 | self.prefilter = self.prefilter_manager.prefilter_lines |
|
2337 | 2331 | |
|
2338 | 2332 | def auto_rewrite_input(self, cmd): |
|
2339 | 2333 | """Print to the screen the rewritten form of the user's command. |
|
2340 | 2334 | |
|
2341 | 2335 | This shows visual feedback by rewriting input lines that cause |
|
2342 | 2336 | automatic calling to kick in, like:: |
|
2343 | 2337 | |
|
2344 | 2338 | /f x |
|
2345 | 2339 | |
|
2346 | 2340 | into:: |
|
2347 | 2341 | |
|
2348 | 2342 | ------> f(x) |
|
2349 | 2343 | |
|
2350 | 2344 | after the user's input prompt. This helps the user understand that the |
|
2351 | 2345 | input line was transformed automatically by IPython. |
|
2352 | 2346 | """ |
|
2353 | 2347 | if not self.show_rewritten_input: |
|
2354 | 2348 | return |
|
2355 | 2349 | |
|
2356 | 2350 | rw = self.prompt_manager.render('rewrite') + cmd |
|
2357 | 2351 | |
|
2358 | 2352 | try: |
|
2359 | 2353 | # plain ascii works better w/ pyreadline, on some machines, so |
|
2360 | 2354 | # we use it and only print uncolored rewrite if we have unicode |
|
2361 | 2355 | rw = str(rw) |
|
2362 | 2356 | print(rw, file=io.stdout) |
|
2363 | 2357 | except UnicodeEncodeError: |
|
2364 | 2358 | print("------> " + cmd) |
|
2365 | 2359 | |
|
2366 | 2360 | #------------------------------------------------------------------------- |
|
2367 | 2361 | # Things related to extracting values/expressions from kernel and user_ns |
|
2368 | 2362 | #------------------------------------------------------------------------- |
|
2369 | 2363 | |
|
2370 | 2364 | def _user_obj_error(self): |
|
2371 | 2365 | """return simple exception dict |
|
2372 | 2366 | |
|
2373 | 2367 | for use in user_variables / expressions |
|
2374 | 2368 | """ |
|
2375 | 2369 | |
|
2376 | 2370 | etype, evalue, tb = self._get_exc_info() |
|
2377 | 2371 | stb = self.InteractiveTB.get_exception_only(etype, evalue) |
|
2378 | 2372 | |
|
2379 | 2373 | exc_info = { |
|
2380 | 2374 | u'status' : 'error', |
|
2381 | 2375 | u'traceback' : stb, |
|
2382 | 2376 | u'ename' : unicode(etype.__name__), |
|
2383 | 2377 | u'evalue' : py3compat.safe_unicode(evalue), |
|
2384 | 2378 | } |
|
2385 | 2379 | |
|
2386 | 2380 | return exc_info |
|
2387 | 2381 | |
|
2388 | 2382 | def _format_user_obj(self, obj): |
|
2389 | 2383 | """format a user object to display dict |
|
2390 | 2384 | |
|
2391 | 2385 | for use in user_expressions / variables |
|
2392 | 2386 | """ |
|
2393 | 2387 | |
|
2394 | 2388 | data, md = self.display_formatter.format(obj) |
|
2395 | 2389 | value = { |
|
2396 | 2390 | 'status' : 'ok', |
|
2397 | 2391 | 'data' : data, |
|
2398 | 2392 | 'metadata' : md, |
|
2399 | 2393 | } |
|
2400 | 2394 | return value |
|
2401 | 2395 | |
|
2402 | 2396 | def user_variables(self, names): |
|
2403 | 2397 | """Get a list of variable names from the user's namespace. |
|
2404 | 2398 | |
|
2405 | 2399 | Parameters |
|
2406 | 2400 | ---------- |
|
2407 | 2401 | names : list of strings |
|
2408 | 2402 | A list of names of variables to be read from the user namespace. |
|
2409 | 2403 | |
|
2410 | 2404 | Returns |
|
2411 | 2405 | ------- |
|
2412 | 2406 | A dict, keyed by the input names and with the rich mime-type repr(s) of each value. |
|
2413 | 2407 | Each element will be a sub-dict of the same form as a display_data message. |
|
2414 | 2408 | """ |
|
2415 | 2409 | out = {} |
|
2416 | 2410 | user_ns = self.user_ns |
|
2417 | 2411 | |
|
2418 | 2412 | for varname in names: |
|
2419 | 2413 | try: |
|
2420 | 2414 | value = self._format_user_obj(user_ns[varname]) |
|
2421 | 2415 | except: |
|
2422 | 2416 | value = self._user_obj_error() |
|
2423 | 2417 | out[varname] = value |
|
2424 | 2418 | return out |
|
2425 | 2419 | |
|
2426 | 2420 | def user_expressions(self, expressions): |
|
2427 | 2421 | """Evaluate a dict of expressions in the user's namespace. |
|
2428 | 2422 | |
|
2429 | 2423 | Parameters |
|
2430 | 2424 | ---------- |
|
2431 | 2425 | expressions : dict |
|
2432 | 2426 | A dict with string keys and string values. The expression values |
|
2433 | 2427 | should be valid Python expressions, each of which will be evaluated |
|
2434 | 2428 | in the user namespace. |
|
2435 | 2429 | |
|
2436 | 2430 | Returns |
|
2437 | 2431 | ------- |
|
2438 | 2432 | A dict, keyed like the input expressions dict, with the rich mime-typed |
|
2439 | 2433 | display_data of each value. |
|
2440 | 2434 | """ |
|
2441 | 2435 | out = {} |
|
2442 | 2436 | user_ns = self.user_ns |
|
2443 | 2437 | global_ns = self.user_global_ns |
|
2444 | 2438 | |
|
2445 | 2439 | for key, expr in expressions.iteritems(): |
|
2446 | 2440 | try: |
|
2447 | 2441 | value = self._format_user_obj(eval(expr, global_ns, user_ns)) |
|
2448 | 2442 | except: |
|
2449 | 2443 | value = self._user_obj_error() |
|
2450 | 2444 | out[key] = value |
|
2451 | 2445 | return out |
|
2452 | 2446 | |
|
2453 | 2447 | #------------------------------------------------------------------------- |
|
2454 | 2448 | # Things related to the running of code |
|
2455 | 2449 | #------------------------------------------------------------------------- |
|
2456 | 2450 | |
|
2457 | 2451 | def ex(self, cmd): |
|
2458 | 2452 | """Execute a normal python statement in user namespace.""" |
|
2459 | 2453 | with self.builtin_trap: |
|
2460 | 2454 | exec cmd in self.user_global_ns, self.user_ns |
|
2461 | 2455 | |
|
2462 | 2456 | def ev(self, expr): |
|
2463 | 2457 | """Evaluate python expression expr in user namespace. |
|
2464 | 2458 | |
|
2465 | 2459 | Returns the result of evaluation |
|
2466 | 2460 | """ |
|
2467 | 2461 | with self.builtin_trap: |
|
2468 | 2462 | return eval(expr, self.user_global_ns, self.user_ns) |
|
2469 | 2463 | |
|
2470 | 2464 | def safe_execfile(self, fname, *where, **kw): |
|
2471 | 2465 | """A safe version of the builtin execfile(). |
|
2472 | 2466 | |
|
2473 | 2467 | This version will never throw an exception, but instead print |
|
2474 | 2468 | helpful error messages to the screen. This only works on pure |
|
2475 | 2469 | Python files with the .py extension. |
|
2476 | 2470 | |
|
2477 | 2471 | Parameters |
|
2478 | 2472 | ---------- |
|
2479 | 2473 | fname : string |
|
2480 | 2474 | The name of the file to be executed. |
|
2481 | 2475 | where : tuple |
|
2482 | 2476 | One or two namespaces, passed to execfile() as (globals,locals). |
|
2483 | 2477 | If only one is given, it is passed as both. |
|
2484 | 2478 | exit_ignore : bool (False) |
|
2485 | 2479 | If True, then silence SystemExit for non-zero status (it is always |
|
2486 | 2480 | silenced for zero status, as it is so common). |
|
2487 | 2481 | raise_exceptions : bool (False) |
|
2488 | 2482 | If True raise exceptions everywhere. Meant for testing. |
|
2489 | 2483 | |
|
2490 | 2484 | """ |
|
2491 | 2485 | kw.setdefault('exit_ignore', False) |
|
2492 | 2486 | kw.setdefault('raise_exceptions', False) |
|
2493 | 2487 | |
|
2494 | 2488 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2495 | 2489 | |
|
2496 | 2490 | # Make sure we can open the file |
|
2497 | 2491 | try: |
|
2498 | 2492 | with open(fname) as thefile: |
|
2499 | 2493 | pass |
|
2500 | 2494 | except: |
|
2501 | 2495 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2502 | 2496 | return |
|
2503 | 2497 | |
|
2504 | 2498 | # Find things also in current directory. This is needed to mimic the |
|
2505 | 2499 | # behavior of running a script from the system command line, where |
|
2506 | 2500 | # Python inserts the script's directory into sys.path |
|
2507 | 2501 | dname = os.path.dirname(fname) |
|
2508 | 2502 | |
|
2509 | 2503 | with prepended_to_syspath(dname): |
|
2510 | 2504 | try: |
|
2511 | 2505 | py3compat.execfile(fname,*where) |
|
2512 | 2506 | except SystemExit as status: |
|
2513 | 2507 | # If the call was made with 0 or None exit status (sys.exit(0) |
|
2514 | 2508 | # or sys.exit() ), don't bother showing a traceback, as both of |
|
2515 | 2509 | # these are considered normal by the OS: |
|
2516 | 2510 | # > python -c'import sys;sys.exit(0)'; echo $? |
|
2517 | 2511 | # 0 |
|
2518 | 2512 | # > python -c'import sys;sys.exit()'; echo $? |
|
2519 | 2513 | # 0 |
|
2520 | 2514 | # For other exit status, we show the exception unless |
|
2521 | 2515 | # explicitly silenced, but only in short form. |
|
2522 | 2516 | if kw['raise_exceptions']: |
|
2523 | 2517 | raise |
|
2524 | 2518 | if status.code and not kw['exit_ignore']: |
|
2525 | 2519 | self.showtraceback(exception_only=True) |
|
2526 | 2520 | except: |
|
2527 | 2521 | if kw['raise_exceptions']: |
|
2528 | 2522 | raise |
|
2529 | 2523 | self.showtraceback() |
|
2530 | 2524 | |
|
2531 | 2525 | def safe_execfile_ipy(self, fname): |
|
2532 | 2526 | """Like safe_execfile, but for .ipy files with IPython syntax. |
|
2533 | 2527 | |
|
2534 | 2528 | Parameters |
|
2535 | 2529 | ---------- |
|
2536 | 2530 | fname : str |
|
2537 | 2531 | The name of the file to execute. The filename must have a |
|
2538 | 2532 | .ipy extension. |
|
2539 | 2533 | """ |
|
2540 | 2534 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2541 | 2535 | |
|
2542 | 2536 | # Make sure we can open the file |
|
2543 | 2537 | try: |
|
2544 | 2538 | with open(fname) as thefile: |
|
2545 | 2539 | pass |
|
2546 | 2540 | except: |
|
2547 | 2541 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2548 | 2542 | return |
|
2549 | 2543 | |
|
2550 | 2544 | # Find things also in current directory. This is needed to mimic the |
|
2551 | 2545 | # behavior of running a script from the system command line, where |
|
2552 | 2546 | # Python inserts the script's directory into sys.path |
|
2553 | 2547 | dname = os.path.dirname(fname) |
|
2554 | 2548 | |
|
2555 | 2549 | with prepended_to_syspath(dname): |
|
2556 | 2550 | try: |
|
2557 | 2551 | with open(fname) as thefile: |
|
2558 | 2552 | # self.run_cell currently captures all exceptions |
|
2559 | 2553 | # raised in user code. It would be nice if there were |
|
2560 | 2554 | # versions of runlines, execfile that did raise, so |
|
2561 | 2555 | # we could catch the errors. |
|
2562 | 2556 | self.run_cell(thefile.read(), store_history=False, shell_futures=False) |
|
2563 | 2557 | except: |
|
2564 | 2558 | self.showtraceback() |
|
2565 | 2559 | warn('Unknown failure executing file: <%s>' % fname) |
|
2566 | 2560 | |
|
2567 | 2561 | def safe_run_module(self, mod_name, where): |
|
2568 | 2562 | """A safe version of runpy.run_module(). |
|
2569 | 2563 | |
|
2570 | 2564 | This version will never throw an exception, but instead print |
|
2571 | 2565 | helpful error messages to the screen. |
|
2572 | 2566 | |
|
2573 | 2567 | `SystemExit` exceptions with status code 0 or None are ignored. |
|
2574 | 2568 | |
|
2575 | 2569 | Parameters |
|
2576 | 2570 | ---------- |
|
2577 | 2571 | mod_name : string |
|
2578 | 2572 | The name of the module to be executed. |
|
2579 | 2573 | where : dict |
|
2580 | 2574 | The globals namespace. |
|
2581 | 2575 | """ |
|
2582 | 2576 | try: |
|
2583 | 2577 | try: |
|
2584 | 2578 | where.update( |
|
2585 | 2579 | runpy.run_module(str(mod_name), run_name="__main__", |
|
2586 | 2580 | alter_sys=True) |
|
2587 | 2581 | ) |
|
2588 | 2582 | except SystemExit as status: |
|
2589 | 2583 | if status.code: |
|
2590 | 2584 | raise |
|
2591 | 2585 | except: |
|
2592 | 2586 | self.showtraceback() |
|
2593 | 2587 | warn('Unknown failure executing module: <%s>' % mod_name) |
|
2594 | 2588 | |
|
2595 | 2589 | def _run_cached_cell_magic(self, magic_name, line): |
|
2596 | 2590 | """Special method to call a cell magic with the data stored in self. |
|
2597 | 2591 | """ |
|
2598 | 2592 | cell = self._current_cell_magic_body |
|
2599 | 2593 | self._current_cell_magic_body = None |
|
2600 | 2594 | return self.run_cell_magic(magic_name, line, cell) |
|
2601 | 2595 | |
|
2602 | 2596 | def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True): |
|
2603 | 2597 | """Run a complete IPython cell. |
|
2604 | 2598 | |
|
2605 | 2599 | Parameters |
|
2606 | 2600 | ---------- |
|
2607 | 2601 | raw_cell : str |
|
2608 | 2602 | The code (including IPython code such as %magic functions) to run. |
|
2609 | 2603 | store_history : bool |
|
2610 | 2604 | If True, the raw and translated cell will be stored in IPython's |
|
2611 | 2605 | history. For user code calling back into IPython's machinery, this |
|
2612 | 2606 | should be set to False. |
|
2613 | 2607 | silent : bool |
|
2614 | 2608 | If True, avoid side-effects, such as implicit displayhooks and |
|
2615 | 2609 | and logging. silent=True forces store_history=False. |
|
2616 | 2610 | shell_futures : bool |
|
2617 | 2611 | If True, the code will share future statements with the interactive |
|
2618 | 2612 | shell. It will both be affected by previous __future__ imports, and |
|
2619 | 2613 | any __future__ imports in the code will affect the shell. If False, |
|
2620 | 2614 | __future__ imports are not shared in either direction. |
|
2621 | 2615 | """ |
|
2622 | 2616 | if (not raw_cell) or raw_cell.isspace(): |
|
2623 | 2617 | return |
|
2624 | 2618 | |
|
2625 | 2619 | if silent: |
|
2626 | 2620 | store_history = False |
|
2627 | 2621 | |
|
2628 | 2622 | self.input_transformer_manager.push(raw_cell) |
|
2629 | 2623 | cell = self.input_transformer_manager.source_reset() |
|
2630 | 2624 | |
|
2631 | 2625 | # Our own compiler remembers the __future__ environment. If we want to |
|
2632 | 2626 | # run code with a separate __future__ environment, use the default |
|
2633 | 2627 | # compiler |
|
2634 | 2628 | compiler = self.compile if shell_futures else CachingCompiler() |
|
2635 | 2629 | |
|
2636 | 2630 | with self.builtin_trap: |
|
2637 | 2631 | prefilter_failed = False |
|
2638 | 2632 | if len(cell.splitlines()) == 1: |
|
2639 | 2633 | try: |
|
2640 | 2634 | # use prefilter_lines to handle trailing newlines |
|
2641 | 2635 | # restore trailing newline for ast.parse |
|
2642 | 2636 | cell = self.prefilter_manager.prefilter_lines(cell) + '\n' |
|
2643 | 2637 | except AliasError as e: |
|
2644 | 2638 | error(e) |
|
2645 | 2639 | prefilter_failed = True |
|
2646 | 2640 | except Exception: |
|
2647 | 2641 | # don't allow prefilter errors to crash IPython |
|
2648 | 2642 | self.showtraceback() |
|
2649 | 2643 | prefilter_failed = True |
|
2650 | 2644 | |
|
2651 | 2645 | # Store raw and processed history |
|
2652 | 2646 | if store_history: |
|
2653 | 2647 | self.history_manager.store_inputs(self.execution_count, |
|
2654 | 2648 | cell, raw_cell) |
|
2655 | 2649 | if not silent: |
|
2656 | 2650 | self.logger.log(cell, raw_cell) |
|
2657 | 2651 | |
|
2658 | 2652 | if not prefilter_failed: |
|
2659 | 2653 | # don't run if prefilter failed |
|
2660 | 2654 | cell_name = self.compile.cache(cell, self.execution_count) |
|
2661 | 2655 | |
|
2662 | 2656 | with self.display_trap: |
|
2663 | 2657 | try: |
|
2664 | 2658 | code_ast = compiler.ast_parse(cell, filename=cell_name) |
|
2665 | 2659 | except IndentationError: |
|
2666 | 2660 | self.showindentationerror() |
|
2667 | 2661 | if store_history: |
|
2668 | 2662 | self.execution_count += 1 |
|
2669 | 2663 | return None |
|
2670 | 2664 | except (OverflowError, SyntaxError, ValueError, TypeError, |
|
2671 | 2665 | MemoryError): |
|
2672 | 2666 | self.showsyntaxerror() |
|
2673 | 2667 | if store_history: |
|
2674 | 2668 | self.execution_count += 1 |
|
2675 | 2669 | return None |
|
2676 | 2670 | |
|
2677 | 2671 | code_ast = self.transform_ast(code_ast) |
|
2678 | 2672 | |
|
2679 | 2673 | interactivity = "none" if silent else self.ast_node_interactivity |
|
2680 | 2674 | self.run_ast_nodes(code_ast.body, cell_name, |
|
2681 | 2675 | interactivity=interactivity, compiler=compiler) |
|
2682 | 2676 | |
|
2683 | 2677 | # Execute any registered post-execution functions. |
|
2684 | 2678 | # unless we are silent |
|
2685 | 2679 | post_exec = [] if silent else self._post_execute.iteritems() |
|
2686 | 2680 | |
|
2687 | 2681 | for func, status in post_exec: |
|
2688 | 2682 | if self.disable_failing_post_execute and not status: |
|
2689 | 2683 | continue |
|
2690 | 2684 | try: |
|
2691 | 2685 | func() |
|
2692 | 2686 | except KeyboardInterrupt: |
|
2693 | 2687 | print("\nKeyboardInterrupt", file=io.stderr) |
|
2694 | 2688 | except Exception: |
|
2695 | 2689 | # register as failing: |
|
2696 | 2690 | self._post_execute[func] = False |
|
2697 | 2691 | self.showtraceback() |
|
2698 | 2692 | print('\n'.join([ |
|
2699 | 2693 | "post-execution function %r produced an error." % func, |
|
2700 | 2694 | "If this problem persists, you can disable failing post-exec functions with:", |
|
2701 | 2695 | "", |
|
2702 | 2696 | " get_ipython().disable_failing_post_execute = True" |
|
2703 | 2697 | ]), file=io.stderr) |
|
2704 | 2698 | |
|
2705 | 2699 | if store_history: |
|
2706 | 2700 | # Write output to the database. Does nothing unless |
|
2707 | 2701 | # history output logging is enabled. |
|
2708 | 2702 | self.history_manager.store_output(self.execution_count) |
|
2709 | 2703 | # Each cell is a *single* input, regardless of how many lines it has |
|
2710 | 2704 | self.execution_count += 1 |
|
2711 | 2705 | |
|
2712 | 2706 | def transform_ast(self, node): |
|
2713 | 2707 | """Apply the AST transformations from self.ast_transformers |
|
2714 | 2708 | |
|
2715 | 2709 | Parameters |
|
2716 | 2710 | ---------- |
|
2717 | 2711 | node : ast.Node |
|
2718 | 2712 | The root node to be transformed. Typically called with the ast.Module |
|
2719 | 2713 | produced by parsing user input. |
|
2720 | 2714 | |
|
2721 | 2715 | Returns |
|
2722 | 2716 | ------- |
|
2723 | 2717 | An ast.Node corresponding to the node it was called with. Note that it |
|
2724 | 2718 | may also modify the passed object, so don't rely on references to the |
|
2725 | 2719 | original AST. |
|
2726 | 2720 | """ |
|
2727 | 2721 | for transformer in self.ast_transformers: |
|
2728 | 2722 | try: |
|
2729 | 2723 | node = transformer.visit(node) |
|
2730 | 2724 | except Exception: |
|
2731 | 2725 | warn("AST transformer %r threw an error. It will be unregistered." % transformer) |
|
2732 | 2726 | self.ast_transformers.remove(transformer) |
|
2733 | 2727 | |
|
2734 | 2728 | if self.ast_transformers: |
|
2735 | 2729 | ast.fix_missing_locations(node) |
|
2736 | 2730 | return node |
|
2737 | 2731 | |
|
2738 | 2732 | |
|
2739 | 2733 | def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr', |
|
2740 | 2734 | compiler=compile): |
|
2741 | 2735 | """Run a sequence of AST nodes. The execution mode depends on the |
|
2742 | 2736 | interactivity parameter. |
|
2743 | 2737 | |
|
2744 | 2738 | Parameters |
|
2745 | 2739 | ---------- |
|
2746 | 2740 | nodelist : list |
|
2747 | 2741 | A sequence of AST nodes to run. |
|
2748 | 2742 | cell_name : str |
|
2749 | 2743 | Will be passed to the compiler as the filename of the cell. Typically |
|
2750 | 2744 | the value returned by ip.compile.cache(cell). |
|
2751 | 2745 | interactivity : str |
|
2752 | 2746 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be |
|
2753 | 2747 | run interactively (displaying output from expressions). 'last_expr' |
|
2754 | 2748 | will run the last node interactively only if it is an expression (i.e. |
|
2755 | 2749 | expressions in loops or other blocks are not displayed. Other values |
|
2756 | 2750 | for this parameter will raise a ValueError. |
|
2757 | 2751 | compiler : callable |
|
2758 | 2752 | A function with the same interface as the built-in compile(), to turn |
|
2759 | 2753 | the AST nodes into code objects. Default is the built-in compile(). |
|
2760 | 2754 | """ |
|
2761 | 2755 | if not nodelist: |
|
2762 | 2756 | return |
|
2763 | 2757 | |
|
2764 | 2758 | if interactivity == 'last_expr': |
|
2765 | 2759 | if isinstance(nodelist[-1], ast.Expr): |
|
2766 | 2760 | interactivity = "last" |
|
2767 | 2761 | else: |
|
2768 | 2762 | interactivity = "none" |
|
2769 | 2763 | |
|
2770 | 2764 | if interactivity == 'none': |
|
2771 | 2765 | to_run_exec, to_run_interactive = nodelist, [] |
|
2772 | 2766 | elif interactivity == 'last': |
|
2773 | 2767 | to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:] |
|
2774 | 2768 | elif interactivity == 'all': |
|
2775 | 2769 | to_run_exec, to_run_interactive = [], nodelist |
|
2776 | 2770 | else: |
|
2777 | 2771 | raise ValueError("Interactivity was %r" % interactivity) |
|
2778 | 2772 | |
|
2779 | 2773 | exec_count = self.execution_count |
|
2780 | 2774 | |
|
2781 | 2775 | try: |
|
2782 | 2776 | for i, node in enumerate(to_run_exec): |
|
2783 | 2777 | mod = ast.Module([node]) |
|
2784 | 2778 | code = compiler(mod, cell_name, "exec") |
|
2785 | 2779 | if self.run_code(code): |
|
2786 | 2780 | return True |
|
2787 | 2781 | |
|
2788 | 2782 | for i, node in enumerate(to_run_interactive): |
|
2789 | 2783 | mod = ast.Interactive([node]) |
|
2790 | 2784 | code = compiler(mod, cell_name, "single") |
|
2791 | 2785 | if self.run_code(code): |
|
2792 | 2786 | return True |
|
2793 | 2787 | |
|
2794 | 2788 | # Flush softspace |
|
2795 | 2789 | if softspace(sys.stdout, 0): |
|
2796 | 2790 | print() |
|
2797 | 2791 | |
|
2798 | 2792 | except: |
|
2799 | 2793 | # It's possible to have exceptions raised here, typically by |
|
2800 | 2794 | # compilation of odd code (such as a naked 'return' outside a |
|
2801 | 2795 | # function) that did parse but isn't valid. Typically the exception |
|
2802 | 2796 | # is a SyntaxError, but it's safest just to catch anything and show |
|
2803 | 2797 | # the user a traceback. |
|
2804 | 2798 | |
|
2805 | 2799 | # We do only one try/except outside the loop to minimize the impact |
|
2806 | 2800 | # on runtime, and also because if any node in the node list is |
|
2807 | 2801 | # broken, we should stop execution completely. |
|
2808 | 2802 | self.showtraceback() |
|
2809 | 2803 | |
|
2810 | 2804 | return False |
|
2811 | 2805 | |
|
2812 | 2806 | def run_code(self, code_obj): |
|
2813 | 2807 | """Execute a code object. |
|
2814 | 2808 | |
|
2815 | 2809 | When an exception occurs, self.showtraceback() is called to display a |
|
2816 | 2810 | traceback. |
|
2817 | 2811 | |
|
2818 | 2812 | Parameters |
|
2819 | 2813 | ---------- |
|
2820 | 2814 | code_obj : code object |
|
2821 | 2815 | A compiled code object, to be executed |
|
2822 | 2816 | |
|
2823 | 2817 | Returns |
|
2824 | 2818 | ------- |
|
2825 | 2819 | False : successful execution. |
|
2826 | 2820 | True : an error occurred. |
|
2827 | 2821 | """ |
|
2828 | 2822 | |
|
2829 | 2823 | # Set our own excepthook in case the user code tries to call it |
|
2830 | 2824 | # directly, so that the IPython crash handler doesn't get triggered |
|
2831 | 2825 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2832 | 2826 | |
|
2833 | 2827 | # we save the original sys.excepthook in the instance, in case config |
|
2834 | 2828 | # code (such as magics) needs access to it. |
|
2835 | 2829 | self.sys_excepthook = old_excepthook |
|
2836 | 2830 | outflag = 1 # happens in more places, so it's easier as default |
|
2837 | 2831 | try: |
|
2838 | 2832 | try: |
|
2839 | 2833 | self.hooks.pre_run_code_hook() |
|
2840 | 2834 | #rprint('Running code', repr(code_obj)) # dbg |
|
2841 | 2835 | exec code_obj in self.user_global_ns, self.user_ns |
|
2842 | 2836 | finally: |
|
2843 | 2837 | # Reset our crash handler in place |
|
2844 | 2838 | sys.excepthook = old_excepthook |
|
2845 | 2839 | except SystemExit: |
|
2846 | 2840 | self.showtraceback(exception_only=True) |
|
2847 | 2841 | warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1) |
|
2848 | 2842 | except self.custom_exceptions: |
|
2849 | 2843 | etype,value,tb = sys.exc_info() |
|
2850 | 2844 | self.CustomTB(etype,value,tb) |
|
2851 | 2845 | except: |
|
2852 | 2846 | self.showtraceback() |
|
2853 | 2847 | else: |
|
2854 | 2848 | outflag = 0 |
|
2855 | 2849 | return outflag |
|
2856 | 2850 | |
|
2857 | 2851 | # For backwards compatibility |
|
2858 | 2852 | runcode = run_code |
|
2859 | 2853 | |
|
2860 | 2854 | #------------------------------------------------------------------------- |
|
2861 | 2855 | # Things related to GUI support and pylab |
|
2862 | 2856 | #------------------------------------------------------------------------- |
|
2863 | 2857 | |
|
2864 | 2858 | def enable_gui(self, gui=None): |
|
2865 | 2859 | raise NotImplementedError('Implement enable_gui in a subclass') |
|
2866 | 2860 | |
|
2867 | 2861 | def enable_matplotlib(self, gui=None): |
|
2868 | 2862 | """Enable interactive matplotlib and inline figure support. |
|
2869 | 2863 | |
|
2870 | 2864 | This takes the following steps: |
|
2871 | 2865 | |
|
2872 | 2866 | 1. select the appropriate eventloop and matplotlib backend |
|
2873 | 2867 | 2. set up matplotlib for interactive use with that backend |
|
2874 | 2868 | 3. configure formatters for inline figure display |
|
2875 | 2869 | 4. enable the selected gui eventloop |
|
2876 | 2870 | |
|
2877 | 2871 | Parameters |
|
2878 | 2872 | ---------- |
|
2879 | 2873 | gui : optional, string |
|
2880 | 2874 | If given, dictates the choice of matplotlib GUI backend to use |
|
2881 | 2875 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', |
|
2882 | 2876 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by |
|
2883 | 2877 | matplotlib (as dictated by the matplotlib build-time options plus the |
|
2884 | 2878 | user's matplotlibrc configuration file). Note that not all backends |
|
2885 | 2879 | make sense in all contexts, for example a terminal ipython can't |
|
2886 | 2880 | display figures inline. |
|
2887 | 2881 | """ |
|
2888 | 2882 | from IPython.core import pylabtools as pt |
|
2889 | 2883 | gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select) |
|
2890 | 2884 | |
|
2891 | 2885 | if gui != 'inline': |
|
2892 | 2886 | # If we have our first gui selection, store it |
|
2893 | 2887 | if self.pylab_gui_select is None: |
|
2894 | 2888 | self.pylab_gui_select = gui |
|
2895 | 2889 | # Otherwise if they are different |
|
2896 | 2890 | elif gui != self.pylab_gui_select: |
|
2897 | 2891 | print ('Warning: Cannot change to a different GUI toolkit: %s.' |
|
2898 | 2892 | ' Using %s instead.' % (gui, self.pylab_gui_select)) |
|
2899 | 2893 | gui, backend = pt.find_gui_and_backend(self.pylab_gui_select) |
|
2900 | 2894 | |
|
2901 | 2895 | pt.activate_matplotlib(backend) |
|
2902 | 2896 | pt.configure_inline_support(self, backend) |
|
2903 | 2897 | |
|
2904 | 2898 | # Now we must activate the gui pylab wants to use, and fix %run to take |
|
2905 | 2899 | # plot updates into account |
|
2906 | 2900 | self.enable_gui(gui) |
|
2907 | 2901 | self.magics_manager.registry['ExecutionMagics'].default_runner = \ |
|
2908 | 2902 | pt.mpl_runner(self.safe_execfile) |
|
2909 | 2903 | |
|
2910 | 2904 | return gui, backend |
|
2911 | 2905 | |
|
2912 | 2906 | def enable_pylab(self, gui=None, import_all=True, welcome_message=False): |
|
2913 | 2907 | """Activate pylab support at runtime. |
|
2914 | 2908 | |
|
2915 | 2909 | This turns on support for matplotlib, preloads into the interactive |
|
2916 | 2910 | namespace all of numpy and pylab, and configures IPython to correctly |
|
2917 | 2911 | interact with the GUI event loop. The GUI backend to be used can be |
|
2918 | 2912 | optionally selected with the optional ``gui`` argument. |
|
2919 | 2913 | |
|
2920 | 2914 | This method only adds preloading the namespace to InteractiveShell.enable_matplotlib. |
|
2921 | 2915 | |
|
2922 | 2916 | Parameters |
|
2923 | 2917 | ---------- |
|
2924 | 2918 | gui : optional, string |
|
2925 | 2919 | If given, dictates the choice of matplotlib GUI backend to use |
|
2926 | 2920 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', |
|
2927 | 2921 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by |
|
2928 | 2922 | matplotlib (as dictated by the matplotlib build-time options plus the |
|
2929 | 2923 | user's matplotlibrc configuration file). Note that not all backends |
|
2930 | 2924 | make sense in all contexts, for example a terminal ipython can't |
|
2931 | 2925 | display figures inline. |
|
2932 | 2926 | import_all : optional, bool, default: True |
|
2933 | 2927 | Whether to do `from numpy import *` and `from pylab import *` |
|
2934 | 2928 | in addition to module imports. |
|
2935 | 2929 | welcome_message : deprecated |
|
2936 | 2930 | This argument is ignored, no welcome message will be displayed. |
|
2937 | 2931 | """ |
|
2938 | 2932 | from IPython.core.pylabtools import import_pylab |
|
2939 | 2933 | |
|
2940 | 2934 | gui, backend = self.enable_matplotlib(gui) |
|
2941 | 2935 | |
|
2942 | 2936 | # We want to prevent the loading of pylab to pollute the user's |
|
2943 | 2937 | # namespace as shown by the %who* magics, so we execute the activation |
|
2944 | 2938 | # code in an empty namespace, and we update *both* user_ns and |
|
2945 | 2939 | # user_ns_hidden with this information. |
|
2946 | 2940 | ns = {} |
|
2947 | 2941 | import_pylab(ns, import_all) |
|
2948 | 2942 | # warn about clobbered names |
|
2949 | 2943 | ignored = set(["__builtins__"]) |
|
2950 | 2944 | both = set(ns).intersection(self.user_ns).difference(ignored) |
|
2951 | 2945 | clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ] |
|
2952 | 2946 | self.user_ns.update(ns) |
|
2953 | 2947 | self.user_ns_hidden.update(ns) |
|
2954 | 2948 | return gui, backend, clobbered |
|
2955 | 2949 | |
|
2956 | 2950 | #------------------------------------------------------------------------- |
|
2957 | 2951 | # Utilities |
|
2958 | 2952 | #------------------------------------------------------------------------- |
|
2959 | 2953 | |
|
2960 | 2954 | def var_expand(self, cmd, depth=0, formatter=DollarFormatter()): |
|
2961 | 2955 | """Expand python variables in a string. |
|
2962 | 2956 | |
|
2963 | 2957 | The depth argument indicates how many frames above the caller should |
|
2964 | 2958 | be walked to look for the local namespace where to expand variables. |
|
2965 | 2959 | |
|
2966 | 2960 | The global namespace for expansion is always the user's interactive |
|
2967 | 2961 | namespace. |
|
2968 | 2962 | """ |
|
2969 | 2963 | ns = self.user_ns.copy() |
|
2970 | 2964 | ns.update(sys._getframe(depth+1).f_locals) |
|
2971 | 2965 | try: |
|
2972 | 2966 | # We have to use .vformat() here, because 'self' is a valid and common |
|
2973 | 2967 | # name, and expanding **ns for .format() would make it collide with |
|
2974 | 2968 | # the 'self' argument of the method. |
|
2975 | 2969 | cmd = formatter.vformat(cmd, args=[], kwargs=ns) |
|
2976 | 2970 | except Exception: |
|
2977 | 2971 | # if formatter couldn't format, just let it go untransformed |
|
2978 | 2972 | pass |
|
2979 | 2973 | return cmd |
|
2980 | 2974 | |
|
2981 | 2975 | def mktempfile(self, data=None, prefix='ipython_edit_'): |
|
2982 | 2976 | """Make a new tempfile and return its filename. |
|
2983 | 2977 | |
|
2984 | 2978 | This makes a call to tempfile.mktemp, but it registers the created |
|
2985 | 2979 | filename internally so ipython cleans it up at exit time. |
|
2986 | 2980 | |
|
2987 | 2981 | Optional inputs: |
|
2988 | 2982 | |
|
2989 | 2983 | - data(None): if data is given, it gets written out to the temp file |
|
2990 | 2984 | immediately, and the file is closed again.""" |
|
2991 | 2985 | |
|
2992 | 2986 | filename = tempfile.mktemp('.py', prefix) |
|
2993 | 2987 | self.tempfiles.append(filename) |
|
2994 | 2988 | |
|
2995 | 2989 | if data: |
|
2996 | 2990 | tmp_file = open(filename,'w') |
|
2997 | 2991 | tmp_file.write(data) |
|
2998 | 2992 | tmp_file.close() |
|
2999 | 2993 | return filename |
|
3000 | 2994 | |
|
3001 | 2995 | # TODO: This should be removed when Term is refactored. |
|
3002 | 2996 | def write(self,data): |
|
3003 | 2997 | """Write a string to the default output""" |
|
3004 | 2998 | io.stdout.write(data) |
|
3005 | 2999 | |
|
3006 | 3000 | # TODO: This should be removed when Term is refactored. |
|
3007 | 3001 | def write_err(self,data): |
|
3008 | 3002 | """Write a string to the default error output""" |
|
3009 | 3003 | io.stderr.write(data) |
|
3010 | 3004 | |
|
3011 | 3005 | def ask_yes_no(self, prompt, default=None): |
|
3012 | 3006 | if self.quiet: |
|
3013 | 3007 | return True |
|
3014 | 3008 | return ask_yes_no(prompt,default) |
|
3015 | 3009 | |
|
3016 | 3010 | def show_usage(self): |
|
3017 | 3011 | """Show a usage message""" |
|
3018 | 3012 | page.page(IPython.core.usage.interactive_usage) |
|
3019 | 3013 | |
|
3020 | 3014 | def extract_input_lines(self, range_str, raw=False): |
|
3021 | 3015 | """Return as a string a set of input history slices. |
|
3022 | 3016 | |
|
3023 | 3017 | Parameters |
|
3024 | 3018 | ---------- |
|
3025 | 3019 | range_str : string |
|
3026 | 3020 | The set of slices is given as a string, like "~5/6-~4/2 4:8 9", |
|
3027 | 3021 | since this function is for use by magic functions which get their |
|
3028 | 3022 | arguments as strings. The number before the / is the session |
|
3029 | 3023 | number: ~n goes n back from the current session. |
|
3030 | 3024 | |
|
3031 | 3025 | Optional Parameters: |
|
3032 | 3026 | - raw(False): by default, the processed input is used. If this is |
|
3033 | 3027 | true, the raw input history is used instead. |
|
3034 | 3028 | |
|
3035 | 3029 | Note that slices can be called with two notations: |
|
3036 | 3030 | |
|
3037 | 3031 | N:M -> standard python form, means including items N...(M-1). |
|
3038 | 3032 | |
|
3039 | 3033 | N-M -> include items N..M (closed endpoint). |
|
3040 | 3034 | """ |
|
3041 | 3035 | lines = self.history_manager.get_range_by_str(range_str, raw=raw) |
|
3042 | 3036 | return "\n".join(x for _, _, x in lines) |
|
3043 | 3037 | |
|
3044 | 3038 | def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True): |
|
3045 | 3039 | """Get a code string from history, file, url, or a string or macro. |
|
3046 | 3040 | |
|
3047 | 3041 | This is mainly used by magic functions. |
|
3048 | 3042 | |
|
3049 | 3043 | Parameters |
|
3050 | 3044 | ---------- |
|
3051 | 3045 | |
|
3052 | 3046 | target : str |
|
3053 | 3047 | |
|
3054 | 3048 | A string specifying code to retrieve. This will be tried respectively |
|
3055 | 3049 | as: ranges of input history (see %history for syntax), url, |
|
3056 | 3050 | correspnding .py file, filename, or an expression evaluating to a |
|
3057 | 3051 | string or Macro in the user namespace. |
|
3058 | 3052 | |
|
3059 | 3053 | raw : bool |
|
3060 | 3054 | If true (default), retrieve raw history. Has no effect on the other |
|
3061 | 3055 | retrieval mechanisms. |
|
3062 | 3056 | |
|
3063 | 3057 | py_only : bool (default False) |
|
3064 | 3058 | Only try to fetch python code, do not try alternative methods to decode file |
|
3065 | 3059 | if unicode fails. |
|
3066 | 3060 | |
|
3067 | 3061 | Returns |
|
3068 | 3062 | ------- |
|
3069 | 3063 | A string of code. |
|
3070 | 3064 | |
|
3071 | 3065 | ValueError is raised if nothing is found, and TypeError if it evaluates |
|
3072 | 3066 | to an object of another type. In each case, .args[0] is a printable |
|
3073 | 3067 | message. |
|
3074 | 3068 | """ |
|
3075 | 3069 | code = self.extract_input_lines(target, raw=raw) # Grab history |
|
3076 | 3070 | if code: |
|
3077 | 3071 | return code |
|
3078 | 3072 | utarget = unquote_filename(target) |
|
3079 | 3073 | try: |
|
3080 | 3074 | if utarget.startswith(('http://', 'https://')): |
|
3081 | 3075 | return openpy.read_py_url(utarget, skip_encoding_cookie=skip_encoding_cookie) |
|
3082 | 3076 | except UnicodeDecodeError: |
|
3083 | 3077 | if not py_only : |
|
3084 | 3078 | from urllib import urlopen # Deferred import |
|
3085 | 3079 | response = urlopen(target) |
|
3086 | 3080 | return response.read().decode('latin1') |
|
3087 | 3081 | raise ValueError(("'%s' seem to be unreadable.") % utarget) |
|
3088 | 3082 | |
|
3089 | 3083 | potential_target = [target] |
|
3090 | 3084 | try : |
|
3091 | 3085 | potential_target.insert(0,get_py_filename(target)) |
|
3092 | 3086 | except IOError: |
|
3093 | 3087 | pass |
|
3094 | 3088 | |
|
3095 | 3089 | for tgt in potential_target : |
|
3096 | 3090 | if os.path.isfile(tgt): # Read file |
|
3097 | 3091 | try : |
|
3098 | 3092 | return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie) |
|
3099 | 3093 | except UnicodeDecodeError : |
|
3100 | 3094 | if not py_only : |
|
3101 | 3095 | with io_open(tgt,'r', encoding='latin1') as f : |
|
3102 | 3096 | return f.read() |
|
3103 | 3097 | raise ValueError(("'%s' seem to be unreadable.") % target) |
|
3104 | 3098 | elif os.path.isdir(os.path.expanduser(tgt)): |
|
3105 | 3099 | raise ValueError("'%s' is a directory, not a regular file." % target) |
|
3106 | 3100 | |
|
3107 | 3101 | try: # User namespace |
|
3108 | 3102 | codeobj = eval(target, self.user_ns) |
|
3109 | 3103 | except Exception: |
|
3110 | 3104 | raise ValueError(("'%s' was not found in history, as a file, url, " |
|
3111 | 3105 | "nor in the user namespace.") % target) |
|
3112 | 3106 | if isinstance(codeobj, basestring): |
|
3113 | 3107 | return codeobj |
|
3114 | 3108 | elif isinstance(codeobj, Macro): |
|
3115 | 3109 | return codeobj.value |
|
3116 | 3110 | |
|
3117 | 3111 | raise TypeError("%s is neither a string nor a macro." % target, |
|
3118 | 3112 | codeobj) |
|
3119 | 3113 | |
|
3120 | 3114 | #------------------------------------------------------------------------- |
|
3121 | 3115 | # Things related to IPython exiting |
|
3122 | 3116 | #------------------------------------------------------------------------- |
|
3123 | 3117 | def atexit_operations(self): |
|
3124 | 3118 | """This will be executed at the time of exit. |
|
3125 | 3119 | |
|
3126 | 3120 | Cleanup operations and saving of persistent data that is done |
|
3127 | 3121 | unconditionally by IPython should be performed here. |
|
3128 | 3122 | |
|
3129 | 3123 | For things that may depend on startup flags or platform specifics (such |
|
3130 | 3124 | as having readline or not), register a separate atexit function in the |
|
3131 | 3125 | code that has the appropriate information, rather than trying to |
|
3132 | 3126 | clutter |
|
3133 | 3127 | """ |
|
3134 | 3128 | # Close the history session (this stores the end time and line count) |
|
3135 | 3129 | # this must be *before* the tempfile cleanup, in case of temporary |
|
3136 | 3130 | # history db |
|
3137 | 3131 | self.history_manager.end_session() |
|
3138 | 3132 | |
|
3139 | 3133 | # Cleanup all tempfiles left around |
|
3140 | 3134 | for tfile in self.tempfiles: |
|
3141 | 3135 | try: |
|
3142 | 3136 | os.unlink(tfile) |
|
3143 | 3137 | except OSError: |
|
3144 | 3138 | pass |
|
3145 | 3139 | |
|
3146 | 3140 | # Clear all user namespaces to release all references cleanly. |
|
3147 | 3141 | self.reset(new_session=False) |
|
3148 | 3142 | |
|
3149 | 3143 | # Run user hooks |
|
3150 | 3144 | self.hooks.shutdown_hook() |
|
3151 | 3145 | |
|
3152 | 3146 | def cleanup(self): |
|
3153 | 3147 | self.restore_sys_module_state() |
|
3154 | 3148 | |
|
3155 | 3149 | |
|
3156 | 3150 | class InteractiveShellABC(object): |
|
3157 | 3151 | """An abstract base class for InteractiveShell.""" |
|
3158 | 3152 | __metaclass__ = abc.ABCMeta |
|
3159 | 3153 | |
|
3160 | 3154 | InteractiveShellABC.register(InteractiveShell) |
@@ -1,728 +1,738 b'' | |||
|
1 | 1 | """Implementation of magic functions for interaction with the OS. |
|
2 | 2 | |
|
3 | 3 | Note: this module is named 'osm' instead of 'os' to avoid a collision with the |
|
4 | 4 | builtin. |
|
5 | 5 | """ |
|
6 | 6 | #----------------------------------------------------------------------------- |
|
7 | 7 | # Copyright (c) 2012 The IPython Development Team. |
|
8 | 8 | # |
|
9 | 9 | # Distributed under the terms of the Modified BSD License. |
|
10 | 10 | # |
|
11 | 11 | # The full license is in the file COPYING.txt, distributed with this software. |
|
12 | 12 | #----------------------------------------------------------------------------- |
|
13 | 13 | |
|
14 | 14 | #----------------------------------------------------------------------------- |
|
15 | 15 | # Imports |
|
16 | 16 | #----------------------------------------------------------------------------- |
|
17 | 17 | |
|
18 | 18 | # Stdlib |
|
19 | 19 | import io |
|
20 | 20 | import os |
|
21 | 21 | import re |
|
22 | 22 | import sys |
|
23 | 23 | from pprint import pformat |
|
24 | 24 | |
|
25 | 25 | # Our own packages |
|
26 | 26 | from IPython.core import magic_arguments |
|
27 | 27 | from IPython.core import oinspect |
|
28 | 28 | from IPython.core import page |
|
29 | from IPython.core.alias import AliasError, Alias | |
|
29 | 30 | from IPython.core.error import UsageError |
|
30 | 31 | from IPython.core.magic import ( |
|
31 | 32 | Magics, compress_dhist, magics_class, line_magic, cell_magic, line_cell_magic |
|
32 | 33 | ) |
|
33 | 34 | from IPython.testing.skipdoctest import skip_doctest |
|
34 | 35 | from IPython.utils.openpy import source_to_unicode |
|
35 | 36 | from IPython.utils.path import unquote_filename |
|
36 | 37 | from IPython.utils.process import abbrev_cwd |
|
37 | 38 | from IPython.utils.terminal import set_term_title |
|
38 | 39 | |
|
39 | 40 | #----------------------------------------------------------------------------- |
|
40 | 41 | # Magic implementation classes |
|
41 | 42 | #----------------------------------------------------------------------------- |
|
42 | 43 | @magics_class |
|
43 | 44 | class OSMagics(Magics): |
|
44 | 45 | """Magics to interact with the underlying OS (shell-type functionality). |
|
45 | 46 | """ |
|
46 | 47 | |
|
47 | 48 | @skip_doctest |
|
48 | 49 | @line_magic |
|
49 | 50 | def alias(self, parameter_s=''): |
|
50 | 51 | """Define an alias for a system command. |
|
51 | 52 | |
|
52 | 53 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
53 | 54 | |
|
54 | 55 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
55 | 56 | params' (from your underlying operating system). |
|
56 | 57 | |
|
57 | 58 | Aliases have lower precedence than magic functions and Python normal |
|
58 | 59 | variables, so if 'foo' is both a Python variable and an alias, the |
|
59 | 60 | alias can not be executed until 'del foo' removes the Python variable. |
|
60 | 61 | |
|
61 | 62 | You can use the %l specifier in an alias definition to represent the |
|
62 | 63 | whole line when the alias is called. For example:: |
|
63 | 64 | |
|
64 | 65 | In [2]: alias bracket echo "Input in brackets: <%l>" |
|
65 | 66 | In [3]: bracket hello world |
|
66 | 67 | Input in brackets: <hello world> |
|
67 | 68 | |
|
68 | 69 | You can also define aliases with parameters using %s specifiers (one |
|
69 | 70 | per parameter):: |
|
70 | 71 | |
|
71 | 72 | In [1]: alias parts echo first %s second %s |
|
72 | 73 | In [2]: %parts A B |
|
73 | 74 | first A second B |
|
74 | 75 | In [3]: %parts A |
|
75 | 76 | Incorrect number of arguments: 2 expected. |
|
76 | 77 | parts is an alias to: 'echo first %s second %s' |
|
77 | 78 | |
|
78 | 79 | Note that %l and %s are mutually exclusive. You can only use one or |
|
79 | 80 | the other in your aliases. |
|
80 | 81 | |
|
81 | 82 | Aliases expand Python variables just like system calls using ! or !! |
|
82 | 83 | do: all expressions prefixed with '$' get expanded. For details of |
|
83 | 84 | the semantic rules, see PEP-215: |
|
84 | 85 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
85 | 86 | IPython for variable expansion. If you want to access a true shell |
|
86 | 87 | variable, an extra $ is necessary to prevent its expansion by |
|
87 | 88 | IPython:: |
|
88 | 89 | |
|
89 | 90 | In [6]: alias show echo |
|
90 | 91 | In [7]: PATH='A Python string' |
|
91 | 92 | In [8]: show $PATH |
|
92 | 93 | A Python string |
|
93 | 94 | In [9]: show $$PATH |
|
94 | 95 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
95 | 96 | |
|
96 | 97 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
97 | 98 | and %rehashx functions, which automatically create aliases for the |
|
98 | 99 | contents of your $PATH. |
|
99 | 100 | |
|
100 | 101 | If called with no parameters, %alias prints the current alias table.""" |
|
101 | 102 | |
|
102 | 103 | par = parameter_s.strip() |
|
103 | 104 | if not par: |
|
104 | 105 | aliases = sorted(self.shell.alias_manager.aliases) |
|
105 | 106 | # stored = self.shell.db.get('stored_aliases', {} ) |
|
106 | 107 | # for k, v in stored: |
|
107 | 108 | # atab.append(k, v[0]) |
|
108 | 109 | |
|
109 | 110 | print "Total number of aliases:", len(aliases) |
|
110 | 111 | sys.stdout.flush() |
|
111 | 112 | return aliases |
|
112 | 113 | |
|
113 | 114 | # Now try to define a new one |
|
114 | 115 | try: |
|
115 | 116 | alias,cmd = par.split(None, 1) |
|
116 | except: | |
|
117 |
print |
|
|
118 | else: | |
|
119 | self.shell.alias_manager.soft_define_alias(alias, cmd) | |
|
117 | except TypeError: | |
|
118 | print(oinspect.getdoc(self.alias)) | |
|
119 | return | |
|
120 | ||
|
121 | try: | |
|
122 | self.shell.alias_manager.define_alias(alias, cmd) | |
|
123 | except AliasError as e: | |
|
124 | print(e) | |
|
120 | 125 | # end magic_alias |
|
121 | 126 | |
|
122 | 127 | @line_magic |
|
123 | 128 | def unalias(self, parameter_s=''): |
|
124 | 129 | """Remove an alias""" |
|
125 | 130 | |
|
126 | 131 | aname = parameter_s.strip() |
|
127 | self.shell.alias_manager.undefine_alias(aname) | |
|
132 | try: | |
|
133 | self.shell.alias_manager.undefine_alias(aname) | |
|
134 | except ValueError as e: | |
|
135 | print(e) | |
|
136 | return | |
|
137 | ||
|
128 | 138 | stored = self.shell.db.get('stored_aliases', {} ) |
|
129 | 139 | if aname in stored: |
|
130 | 140 | print "Removing %stored alias",aname |
|
131 | 141 | del stored[aname] |
|
132 | 142 | self.shell.db['stored_aliases'] = stored |
|
133 | 143 | |
|
134 | 144 | @line_magic |
|
135 | 145 | def rehashx(self, parameter_s=''): |
|
136 | 146 | """Update the alias table with all executable files in $PATH. |
|
137 | 147 | |
|
138 | 148 | This version explicitly checks that every entry in $PATH is a file |
|
139 | 149 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
140 | 150 | |
|
141 | 151 | Under Windows, it checks executability as a match against a |
|
142 | 152 | '|'-separated string of extensions, stored in the IPython config |
|
143 | 153 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
144 | 154 | |
|
145 | 155 | This function also resets the root module cache of module completer, |
|
146 | 156 | used on slow filesystems. |
|
147 | 157 | """ |
|
148 | 158 | from IPython.core.alias import InvalidAliasError |
|
149 | 159 | |
|
150 | 160 | # for the benefit of module completer in ipy_completers.py |
|
151 | 161 | del self.shell.db['rootmodules_cache'] |
|
152 | 162 | |
|
153 | 163 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
154 | 164 | os.environ.get('PATH','').split(os.pathsep)] |
|
155 | 165 | path = filter(os.path.isdir,path) |
|
156 | 166 | |
|
157 | 167 | syscmdlist = [] |
|
158 | 168 | # Now define isexec in a cross platform manner. |
|
159 | 169 | if os.name == 'posix': |
|
160 | 170 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
161 | 171 | os.access(fname,os.X_OK) |
|
162 | 172 | else: |
|
163 | 173 | try: |
|
164 | 174 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
165 | 175 | except KeyError: |
|
166 | 176 | winext = 'exe|com|bat|py' |
|
167 | 177 | if 'py' not in winext: |
|
168 | 178 | winext += '|py' |
|
169 | 179 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
170 | 180 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
171 | 181 | savedir = os.getcwdu() |
|
172 | 182 | |
|
173 | 183 | # Now walk the paths looking for executables to alias. |
|
174 | 184 | try: |
|
175 | 185 | # write the whole loop for posix/Windows so we don't have an if in |
|
176 | 186 | # the innermost part |
|
177 | 187 | if os.name == 'posix': |
|
178 | 188 | for pdir in path: |
|
179 | 189 | os.chdir(pdir) |
|
180 | 190 | for ff in os.listdir(pdir): |
|
181 | 191 | if isexec(ff): |
|
182 | 192 | try: |
|
183 | 193 | # Removes dots from the name since ipython |
|
184 | 194 | # will assume names with dots to be python. |
|
185 |
if |
|
|
195 | if not self.shell.alias_manager.is_alias(ff): | |
|
186 | 196 | self.shell.alias_manager.define_alias( |
|
187 | 197 | ff.replace('.',''), ff) |
|
188 | 198 | except InvalidAliasError: |
|
189 | 199 | pass |
|
190 | 200 | else: |
|
191 | 201 | syscmdlist.append(ff) |
|
192 | 202 | else: |
|
193 |
no_alias = s |
|
|
203 | no_alias = Alias.blacklist | |
|
194 | 204 | for pdir in path: |
|
195 | 205 | os.chdir(pdir) |
|
196 | 206 | for ff in os.listdir(pdir): |
|
197 | 207 | base, ext = os.path.splitext(ff) |
|
198 | 208 | if isexec(ff) and base.lower() not in no_alias: |
|
199 | 209 | if ext.lower() == '.exe': |
|
200 | 210 | ff = base |
|
201 | 211 | try: |
|
202 | 212 | # Removes dots from the name since ipython |
|
203 | 213 | # will assume names with dots to be python. |
|
204 | 214 | self.shell.alias_manager.define_alias( |
|
205 | 215 | base.lower().replace('.',''), ff) |
|
206 | 216 | except InvalidAliasError: |
|
207 | 217 | pass |
|
208 | 218 | syscmdlist.append(ff) |
|
209 | 219 | self.shell.db['syscmdlist'] = syscmdlist |
|
210 | 220 | finally: |
|
211 | 221 | os.chdir(savedir) |
|
212 | 222 | |
|
213 | 223 | @skip_doctest |
|
214 | 224 | @line_magic |
|
215 | 225 | def pwd(self, parameter_s=''): |
|
216 | 226 | """Return the current working directory path. |
|
217 | 227 | |
|
218 | 228 | Examples |
|
219 | 229 | -------- |
|
220 | 230 | :: |
|
221 | 231 | |
|
222 | 232 | In [9]: pwd |
|
223 | 233 | Out[9]: '/home/tsuser/sprint/ipython' |
|
224 | 234 | """ |
|
225 | 235 | return os.getcwdu() |
|
226 | 236 | |
|
227 | 237 | @skip_doctest |
|
228 | 238 | @line_magic |
|
229 | 239 | def cd(self, parameter_s=''): |
|
230 | 240 | """Change the current working directory. |
|
231 | 241 | |
|
232 | 242 | This command automatically maintains an internal list of directories |
|
233 | 243 | you visit during your IPython session, in the variable _dh. The |
|
234 | 244 | command %dhist shows this history nicely formatted. You can also |
|
235 | 245 | do 'cd -<tab>' to see directory history conveniently. |
|
236 | 246 | |
|
237 | 247 | Usage: |
|
238 | 248 | |
|
239 | 249 | cd 'dir': changes to directory 'dir'. |
|
240 | 250 | |
|
241 | 251 | cd -: changes to the last visited directory. |
|
242 | 252 | |
|
243 | 253 | cd -<n>: changes to the n-th directory in the directory history. |
|
244 | 254 | |
|
245 | 255 | cd --foo: change to directory that matches 'foo' in history |
|
246 | 256 | |
|
247 | 257 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
248 | 258 | (note: cd <bookmark_name> is enough if there is no |
|
249 | 259 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
250 | 260 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
251 | 261 | |
|
252 | 262 | Options: |
|
253 | 263 | |
|
254 | 264 | -q: quiet. Do not print the working directory after the cd command is |
|
255 | 265 | executed. By default IPython's cd command does print this directory, |
|
256 | 266 | since the default prompts do not display path information. |
|
257 | 267 | |
|
258 | 268 | Note that !cd doesn't work for this purpose because the shell where |
|
259 | 269 | !command runs is immediately discarded after executing 'command'. |
|
260 | 270 | |
|
261 | 271 | Examples |
|
262 | 272 | -------- |
|
263 | 273 | :: |
|
264 | 274 | |
|
265 | 275 | In [10]: cd parent/child |
|
266 | 276 | /home/tsuser/parent/child |
|
267 | 277 | """ |
|
268 | 278 | |
|
269 | 279 | oldcwd = os.getcwdu() |
|
270 | 280 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
271 | 281 | # jump in directory history by number |
|
272 | 282 | if numcd: |
|
273 | 283 | nn = int(numcd.group(2)) |
|
274 | 284 | try: |
|
275 | 285 | ps = self.shell.user_ns['_dh'][nn] |
|
276 | 286 | except IndexError: |
|
277 | 287 | print 'The requested directory does not exist in history.' |
|
278 | 288 | return |
|
279 | 289 | else: |
|
280 | 290 | opts = {} |
|
281 | 291 | elif parameter_s.startswith('--'): |
|
282 | 292 | ps = None |
|
283 | 293 | fallback = None |
|
284 | 294 | pat = parameter_s[2:] |
|
285 | 295 | dh = self.shell.user_ns['_dh'] |
|
286 | 296 | # first search only by basename (last component) |
|
287 | 297 | for ent in reversed(dh): |
|
288 | 298 | if pat in os.path.basename(ent) and os.path.isdir(ent): |
|
289 | 299 | ps = ent |
|
290 | 300 | break |
|
291 | 301 | |
|
292 | 302 | if fallback is None and pat in ent and os.path.isdir(ent): |
|
293 | 303 | fallback = ent |
|
294 | 304 | |
|
295 | 305 | # if we have no last part match, pick the first full path match |
|
296 | 306 | if ps is None: |
|
297 | 307 | ps = fallback |
|
298 | 308 | |
|
299 | 309 | if ps is None: |
|
300 | 310 | print "No matching entry in directory history" |
|
301 | 311 | return |
|
302 | 312 | else: |
|
303 | 313 | opts = {} |
|
304 | 314 | |
|
305 | 315 | |
|
306 | 316 | else: |
|
307 | 317 | #turn all non-space-escaping backslashes to slashes, |
|
308 | 318 | # for c:\windows\directory\names\ |
|
309 | 319 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
310 | 320 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
311 | 321 | # jump to previous |
|
312 | 322 | if ps == '-': |
|
313 | 323 | try: |
|
314 | 324 | ps = self.shell.user_ns['_dh'][-2] |
|
315 | 325 | except IndexError: |
|
316 | 326 | raise UsageError('%cd -: No previous directory to change to.') |
|
317 | 327 | # jump to bookmark if needed |
|
318 | 328 | else: |
|
319 | 329 | if not os.path.isdir(ps) or 'b' in opts: |
|
320 | 330 | bkms = self.shell.db.get('bookmarks', {}) |
|
321 | 331 | |
|
322 | 332 | if ps in bkms: |
|
323 | 333 | target = bkms[ps] |
|
324 | 334 | print '(bookmark:%s) -> %s' % (ps, target) |
|
325 | 335 | ps = target |
|
326 | 336 | else: |
|
327 | 337 | if 'b' in opts: |
|
328 | 338 | raise UsageError("Bookmark '%s' not found. " |
|
329 | 339 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
330 | 340 | |
|
331 | 341 | # strip extra quotes on Windows, because os.chdir doesn't like them |
|
332 | 342 | ps = unquote_filename(ps) |
|
333 | 343 | # at this point ps should point to the target dir |
|
334 | 344 | if ps: |
|
335 | 345 | try: |
|
336 | 346 | os.chdir(os.path.expanduser(ps)) |
|
337 | 347 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
338 | 348 | set_term_title('IPython: ' + abbrev_cwd()) |
|
339 | 349 | except OSError: |
|
340 | 350 | print sys.exc_info()[1] |
|
341 | 351 | else: |
|
342 | 352 | cwd = os.getcwdu() |
|
343 | 353 | dhist = self.shell.user_ns['_dh'] |
|
344 | 354 | if oldcwd != cwd: |
|
345 | 355 | dhist.append(cwd) |
|
346 | 356 | self.shell.db['dhist'] = compress_dhist(dhist)[-100:] |
|
347 | 357 | |
|
348 | 358 | else: |
|
349 | 359 | os.chdir(self.shell.home_dir) |
|
350 | 360 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
351 | 361 | set_term_title('IPython: ' + '~') |
|
352 | 362 | cwd = os.getcwdu() |
|
353 | 363 | dhist = self.shell.user_ns['_dh'] |
|
354 | 364 | |
|
355 | 365 | if oldcwd != cwd: |
|
356 | 366 | dhist.append(cwd) |
|
357 | 367 | self.shell.db['dhist'] = compress_dhist(dhist)[-100:] |
|
358 | 368 | if not 'q' in opts and self.shell.user_ns['_dh']: |
|
359 | 369 | print self.shell.user_ns['_dh'][-1] |
|
360 | 370 | |
|
361 | 371 | |
|
362 | 372 | @line_magic |
|
363 | 373 | def env(self, parameter_s=''): |
|
364 | 374 | """List environment variables.""" |
|
365 | 375 | |
|
366 | 376 | return dict(os.environ) |
|
367 | 377 | |
|
368 | 378 | @line_magic |
|
369 | 379 | def pushd(self, parameter_s=''): |
|
370 | 380 | """Place the current dir on stack and change directory. |
|
371 | 381 | |
|
372 | 382 | Usage:\\ |
|
373 | 383 | %pushd ['dirname'] |
|
374 | 384 | """ |
|
375 | 385 | |
|
376 | 386 | dir_s = self.shell.dir_stack |
|
377 | 387 | tgt = os.path.expanduser(unquote_filename(parameter_s)) |
|
378 | 388 | cwd = os.getcwdu().replace(self.shell.home_dir,'~') |
|
379 | 389 | if tgt: |
|
380 | 390 | self.cd(parameter_s) |
|
381 | 391 | dir_s.insert(0,cwd) |
|
382 | 392 | return self.shell.magic('dirs') |
|
383 | 393 | |
|
384 | 394 | @line_magic |
|
385 | 395 | def popd(self, parameter_s=''): |
|
386 | 396 | """Change to directory popped off the top of the stack. |
|
387 | 397 | """ |
|
388 | 398 | if not self.shell.dir_stack: |
|
389 | 399 | raise UsageError("%popd on empty stack") |
|
390 | 400 | top = self.shell.dir_stack.pop(0) |
|
391 | 401 | self.cd(top) |
|
392 | 402 | print "popd ->",top |
|
393 | 403 | |
|
394 | 404 | @line_magic |
|
395 | 405 | def dirs(self, parameter_s=''): |
|
396 | 406 | """Return the current directory stack.""" |
|
397 | 407 | |
|
398 | 408 | return self.shell.dir_stack |
|
399 | 409 | |
|
400 | 410 | @line_magic |
|
401 | 411 | def dhist(self, parameter_s=''): |
|
402 | 412 | """Print your history of visited directories. |
|
403 | 413 | |
|
404 | 414 | %dhist -> print full history\\ |
|
405 | 415 | %dhist n -> print last n entries only\\ |
|
406 | 416 | %dhist n1 n2 -> print entries between n1 and n2 (n2 not included)\\ |
|
407 | 417 | |
|
408 | 418 | This history is automatically maintained by the %cd command, and |
|
409 | 419 | always available as the global list variable _dh. You can use %cd -<n> |
|
410 | 420 | to go to directory number <n>. |
|
411 | 421 | |
|
412 | 422 | Note that most of time, you should view directory history by entering |
|
413 | 423 | cd -<TAB>. |
|
414 | 424 | |
|
415 | 425 | """ |
|
416 | 426 | |
|
417 | 427 | dh = self.shell.user_ns['_dh'] |
|
418 | 428 | if parameter_s: |
|
419 | 429 | try: |
|
420 | 430 | args = map(int,parameter_s.split()) |
|
421 | 431 | except: |
|
422 | 432 | self.arg_err(self.dhist) |
|
423 | 433 | return |
|
424 | 434 | if len(args) == 1: |
|
425 | 435 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
426 | 436 | elif len(args) == 2: |
|
427 | 437 | ini,fin = args |
|
428 | 438 | fin = min(fin, len(dh)) |
|
429 | 439 | else: |
|
430 | 440 | self.arg_err(self.dhist) |
|
431 | 441 | return |
|
432 | 442 | else: |
|
433 | 443 | ini,fin = 0,len(dh) |
|
434 | 444 | print 'Directory history (kept in _dh)' |
|
435 | 445 | for i in range(ini, fin): |
|
436 | 446 | print "%d: %s" % (i, dh[i]) |
|
437 | 447 | |
|
438 | 448 | @skip_doctest |
|
439 | 449 | @line_magic |
|
440 | 450 | def sc(self, parameter_s=''): |
|
441 | 451 | """Shell capture - run shell command and capture output (DEPRECATED use !). |
|
442 | 452 | |
|
443 | 453 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
444 | 454 | |
|
445 | 455 | You should use the form 'var = !command' instead. Example: |
|
446 | 456 | |
|
447 | 457 | "%sc -l myfiles = ls ~" should now be written as |
|
448 | 458 | |
|
449 | 459 | "myfiles = !ls ~" |
|
450 | 460 | |
|
451 | 461 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
452 | 462 | below. |
|
453 | 463 | |
|
454 | 464 | -- |
|
455 | 465 | %sc [options] varname=command |
|
456 | 466 | |
|
457 | 467 | IPython will run the given command using commands.getoutput(), and |
|
458 | 468 | will then update the user's interactive namespace with a variable |
|
459 | 469 | called varname, containing the value of the call. Your command can |
|
460 | 470 | contain shell wildcards, pipes, etc. |
|
461 | 471 | |
|
462 | 472 | The '=' sign in the syntax is mandatory, and the variable name you |
|
463 | 473 | supply must follow Python's standard conventions for valid names. |
|
464 | 474 | |
|
465 | 475 | (A special format without variable name exists for internal use) |
|
466 | 476 | |
|
467 | 477 | Options: |
|
468 | 478 | |
|
469 | 479 | -l: list output. Split the output on newlines into a list before |
|
470 | 480 | assigning it to the given variable. By default the output is stored |
|
471 | 481 | as a single string. |
|
472 | 482 | |
|
473 | 483 | -v: verbose. Print the contents of the variable. |
|
474 | 484 | |
|
475 | 485 | In most cases you should not need to split as a list, because the |
|
476 | 486 | returned value is a special type of string which can automatically |
|
477 | 487 | provide its contents either as a list (split on newlines) or as a |
|
478 | 488 | space-separated string. These are convenient, respectively, either |
|
479 | 489 | for sequential processing or to be passed to a shell command. |
|
480 | 490 | |
|
481 | 491 | For example:: |
|
482 | 492 | |
|
483 | 493 | # Capture into variable a |
|
484 | 494 | In [1]: sc a=ls *py |
|
485 | 495 | |
|
486 | 496 | # a is a string with embedded newlines |
|
487 | 497 | In [2]: a |
|
488 | 498 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' |
|
489 | 499 | |
|
490 | 500 | # which can be seen as a list: |
|
491 | 501 | In [3]: a.l |
|
492 | 502 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] |
|
493 | 503 | |
|
494 | 504 | # or as a whitespace-separated string: |
|
495 | 505 | In [4]: a.s |
|
496 | 506 | Out[4]: 'setup.py win32_manual_post_install.py' |
|
497 | 507 | |
|
498 | 508 | # a.s is useful to pass as a single command line: |
|
499 | 509 | In [5]: !wc -l $a.s |
|
500 | 510 | 146 setup.py |
|
501 | 511 | 130 win32_manual_post_install.py |
|
502 | 512 | 276 total |
|
503 | 513 | |
|
504 | 514 | # while the list form is useful to loop over: |
|
505 | 515 | In [6]: for f in a.l: |
|
506 | 516 | ...: !wc -l $f |
|
507 | 517 | ...: |
|
508 | 518 | 146 setup.py |
|
509 | 519 | 130 win32_manual_post_install.py |
|
510 | 520 | |
|
511 | 521 | Similarly, the lists returned by the -l option are also special, in |
|
512 | 522 | the sense that you can equally invoke the .s attribute on them to |
|
513 | 523 | automatically get a whitespace-separated string from their contents:: |
|
514 | 524 | |
|
515 | 525 | In [7]: sc -l b=ls *py |
|
516 | 526 | |
|
517 | 527 | In [8]: b |
|
518 | 528 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] |
|
519 | 529 | |
|
520 | 530 | In [9]: b.s |
|
521 | 531 | Out[9]: 'setup.py win32_manual_post_install.py' |
|
522 | 532 | |
|
523 | 533 | In summary, both the lists and strings used for output capture have |
|
524 | 534 | the following special attributes:: |
|
525 | 535 | |
|
526 | 536 | .l (or .list) : value as list. |
|
527 | 537 | .n (or .nlstr): value as newline-separated string. |
|
528 | 538 | .s (or .spstr): value as space-separated string. |
|
529 | 539 | """ |
|
530 | 540 | |
|
531 | 541 | opts,args = self.parse_options(parameter_s, 'lv') |
|
532 | 542 | # Try to get a variable name and command to run |
|
533 | 543 | try: |
|
534 | 544 | # the variable name must be obtained from the parse_options |
|
535 | 545 | # output, which uses shlex.split to strip options out. |
|
536 | 546 | var,_ = args.split('=', 1) |
|
537 | 547 | var = var.strip() |
|
538 | 548 | # But the command has to be extracted from the original input |
|
539 | 549 | # parameter_s, not on what parse_options returns, to avoid the |
|
540 | 550 | # quote stripping which shlex.split performs on it. |
|
541 | 551 | _,cmd = parameter_s.split('=', 1) |
|
542 | 552 | except ValueError: |
|
543 | 553 | var,cmd = '','' |
|
544 | 554 | # If all looks ok, proceed |
|
545 | 555 | split = 'l' in opts |
|
546 | 556 | out = self.shell.getoutput(cmd, split=split) |
|
547 | 557 | if 'v' in opts: |
|
548 | 558 | print '%s ==\n%s' % (var, pformat(out)) |
|
549 | 559 | if var: |
|
550 | 560 | self.shell.user_ns.update({var:out}) |
|
551 | 561 | else: |
|
552 | 562 | return out |
|
553 | 563 | |
|
554 | 564 | @line_cell_magic |
|
555 | 565 | def sx(self, line='', cell=None): |
|
556 | 566 | """Shell execute - run shell command and capture output (!! is short-hand). |
|
557 | 567 | |
|
558 | 568 | %sx command |
|
559 | 569 | |
|
560 | 570 | IPython will run the given command using commands.getoutput(), and |
|
561 | 571 | return the result formatted as a list (split on '\\n'). Since the |
|
562 | 572 | output is _returned_, it will be stored in ipython's regular output |
|
563 | 573 | cache Out[N] and in the '_N' automatic variables. |
|
564 | 574 | |
|
565 | 575 | Notes: |
|
566 | 576 | |
|
567 | 577 | 1) If an input line begins with '!!', then %sx is automatically |
|
568 | 578 | invoked. That is, while:: |
|
569 | 579 | |
|
570 | 580 | !ls |
|
571 | 581 | |
|
572 | 582 | causes ipython to simply issue system('ls'), typing:: |
|
573 | 583 | |
|
574 | 584 | !!ls |
|
575 | 585 | |
|
576 | 586 | is a shorthand equivalent to:: |
|
577 | 587 | |
|
578 | 588 | %sx ls |
|
579 | 589 | |
|
580 | 590 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
581 | 591 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
582 | 592 | to process line-oriented shell output via further python commands. |
|
583 | 593 | %sc is meant to provide much finer control, but requires more |
|
584 | 594 | typing. |
|
585 | 595 | |
|
586 | 596 | 3) Just like %sc -l, this is a list with special attributes: |
|
587 | 597 | :: |
|
588 | 598 | |
|
589 | 599 | .l (or .list) : value as list. |
|
590 | 600 | .n (or .nlstr): value as newline-separated string. |
|
591 | 601 | .s (or .spstr): value as whitespace-separated string. |
|
592 | 602 | |
|
593 | 603 | This is very useful when trying to use such lists as arguments to |
|
594 | 604 | system commands.""" |
|
595 | 605 | |
|
596 | 606 | if cell is None: |
|
597 | 607 | # line magic |
|
598 | 608 | return self.shell.getoutput(line) |
|
599 | 609 | else: |
|
600 | 610 | opts,args = self.parse_options(line, '', 'out=') |
|
601 | 611 | output = self.shell.getoutput(cell) |
|
602 | 612 | out_name = opts.get('out', opts.get('o')) |
|
603 | 613 | if out_name: |
|
604 | 614 | self.shell.user_ns[out_name] = output |
|
605 | 615 | else: |
|
606 | 616 | return output |
|
607 | 617 | |
|
608 | 618 | system = line_cell_magic('system')(sx) |
|
609 | 619 | bang = cell_magic('!')(sx) |
|
610 | 620 | |
|
611 | 621 | @line_magic |
|
612 | 622 | def bookmark(self, parameter_s=''): |
|
613 | 623 | """Manage IPython's bookmark system. |
|
614 | 624 | |
|
615 | 625 | %bookmark <name> - set bookmark to current dir |
|
616 | 626 | %bookmark <name> <dir> - set bookmark to <dir> |
|
617 | 627 | %bookmark -l - list all bookmarks |
|
618 | 628 | %bookmark -d <name> - remove bookmark |
|
619 | 629 | %bookmark -r - remove all bookmarks |
|
620 | 630 | |
|
621 | 631 | You can later on access a bookmarked folder with:: |
|
622 | 632 | |
|
623 | 633 | %cd -b <name> |
|
624 | 634 | |
|
625 | 635 | or simply '%cd <name>' if there is no directory called <name> AND |
|
626 | 636 | there is such a bookmark defined. |
|
627 | 637 | |
|
628 | 638 | Your bookmarks persist through IPython sessions, but they are |
|
629 | 639 | associated with each profile.""" |
|
630 | 640 | |
|
631 | 641 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
632 | 642 | if len(args) > 2: |
|
633 | 643 | raise UsageError("%bookmark: too many arguments") |
|
634 | 644 | |
|
635 | 645 | bkms = self.shell.db.get('bookmarks',{}) |
|
636 | 646 | |
|
637 | 647 | if 'd' in opts: |
|
638 | 648 | try: |
|
639 | 649 | todel = args[0] |
|
640 | 650 | except IndexError: |
|
641 | 651 | raise UsageError( |
|
642 | 652 | "%bookmark -d: must provide a bookmark to delete") |
|
643 | 653 | else: |
|
644 | 654 | try: |
|
645 | 655 | del bkms[todel] |
|
646 | 656 | except KeyError: |
|
647 | 657 | raise UsageError( |
|
648 | 658 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) |
|
649 | 659 | |
|
650 | 660 | elif 'r' in opts: |
|
651 | 661 | bkms = {} |
|
652 | 662 | elif 'l' in opts: |
|
653 | 663 | bks = bkms.keys() |
|
654 | 664 | bks.sort() |
|
655 | 665 | if bks: |
|
656 | 666 | size = max(map(len, bks)) |
|
657 | 667 | else: |
|
658 | 668 | size = 0 |
|
659 | 669 | fmt = '%-'+str(size)+'s -> %s' |
|
660 | 670 | print 'Current bookmarks:' |
|
661 | 671 | for bk in bks: |
|
662 | 672 | print fmt % (bk, bkms[bk]) |
|
663 | 673 | else: |
|
664 | 674 | if not args: |
|
665 | 675 | raise UsageError("%bookmark: You must specify the bookmark name") |
|
666 | 676 | elif len(args)==1: |
|
667 | 677 | bkms[args[0]] = os.getcwdu() |
|
668 | 678 | elif len(args)==2: |
|
669 | 679 | bkms[args[0]] = args[1] |
|
670 | 680 | self.shell.db['bookmarks'] = bkms |
|
671 | 681 | |
|
672 | 682 | @line_magic |
|
673 | 683 | def pycat(self, parameter_s=''): |
|
674 | 684 | """Show a syntax-highlighted file through a pager. |
|
675 | 685 | |
|
676 | 686 | This magic is similar to the cat utility, but it will assume the file |
|
677 | 687 | to be Python source and will show it with syntax highlighting. |
|
678 | 688 | |
|
679 | 689 | This magic command can either take a local filename, an url, |
|
680 | 690 | an history range (see %history) or a macro as argument :: |
|
681 | 691 | |
|
682 | 692 | %pycat myscript.py |
|
683 | 693 | %pycat 7-27 |
|
684 | 694 | %pycat myMacro |
|
685 | 695 | %pycat http://www.example.com/myscript.py |
|
686 | 696 | """ |
|
687 | 697 | if not parameter_s: |
|
688 | 698 | raise UsageError('Missing filename, URL, input history range, ' |
|
689 | 699 | 'or macro.') |
|
690 | 700 | |
|
691 | 701 | try : |
|
692 | 702 | cont = self.shell.find_user_code(parameter_s, skip_encoding_cookie=False) |
|
693 | 703 | except (ValueError, IOError): |
|
694 | 704 | print "Error: no such file, variable, URL, history range or macro" |
|
695 | 705 | return |
|
696 | 706 | |
|
697 | 707 | page.page(self.shell.pycolorize(source_to_unicode(cont))) |
|
698 | 708 | |
|
699 | 709 | @magic_arguments.magic_arguments() |
|
700 | 710 | @magic_arguments.argument( |
|
701 | 711 | '-a', '--append', action='store_true', default=False, |
|
702 | 712 | help='Append contents of the cell to an existing file. ' |
|
703 | 713 | 'The file will be created if it does not exist.' |
|
704 | 714 | ) |
|
705 | 715 | @magic_arguments.argument( |
|
706 | 716 | 'filename', type=unicode, |
|
707 | 717 | help='file to write' |
|
708 | 718 | ) |
|
709 | 719 | @cell_magic |
|
710 | 720 | def writefile(self, line, cell): |
|
711 | 721 | """Write the contents of the cell to a file. |
|
712 | 722 | |
|
713 | 723 | The file will be overwritten unless the -a (--append) flag is specified. |
|
714 | 724 | """ |
|
715 | 725 | args = magic_arguments.parse_argstring(self.writefile, line) |
|
716 | 726 | filename = os.path.expanduser(unquote_filename(args.filename)) |
|
717 | 727 | |
|
718 | 728 | if os.path.exists(filename): |
|
719 | 729 | if args.append: |
|
720 | 730 | print "Appending to %s" % filename |
|
721 | 731 | else: |
|
722 | 732 | print "Overwriting %s" % filename |
|
723 | 733 | else: |
|
724 | 734 | print "Writing %s" % filename |
|
725 | 735 | |
|
726 | 736 | mode = 'a' if args.append else 'w' |
|
727 | 737 | with io.open(filename, mode, encoding='utf-8') as f: |
|
728 | 738 | f.write(cell) |
@@ -1,745 +1,713 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """ |
|
3 | 3 | Prefiltering components. |
|
4 | 4 | |
|
5 | 5 | Prefilters transform user input before it is exec'd by Python. These |
|
6 | 6 | transforms are used to implement additional syntax such as !ls and %magic. |
|
7 | 7 | |
|
8 | 8 | Authors: |
|
9 | 9 | |
|
10 | 10 | * Brian Granger |
|
11 | 11 | * Fernando Perez |
|
12 | 12 | * Dan Milstein |
|
13 | 13 | * Ville Vainio |
|
14 | 14 | """ |
|
15 | 15 | |
|
16 | 16 | #----------------------------------------------------------------------------- |
|
17 | 17 | # Copyright (C) 2008-2011 The IPython Development Team |
|
18 | 18 | # |
|
19 | 19 | # Distributed under the terms of the BSD License. The full license is in |
|
20 | 20 | # the file COPYING, distributed as part of this software. |
|
21 | 21 | #----------------------------------------------------------------------------- |
|
22 | 22 | |
|
23 | 23 | #----------------------------------------------------------------------------- |
|
24 | 24 | # Imports |
|
25 | 25 | #----------------------------------------------------------------------------- |
|
26 | 26 | |
|
27 | 27 | import re |
|
28 | 28 | |
|
29 | 29 | from IPython.core.autocall import IPyAutocall |
|
30 | 30 | from IPython.config.configurable import Configurable |
|
31 | 31 | from IPython.core.inputsplitter import ( |
|
32 | 32 | ESC_MAGIC, |
|
33 | 33 | ESC_QUOTE, |
|
34 | 34 | ESC_QUOTE2, |
|
35 | 35 | ESC_PAREN, |
|
36 | 36 | ) |
|
37 | 37 | from IPython.core.macro import Macro |
|
38 | 38 | from IPython.core.splitinput import LineInfo |
|
39 | 39 | |
|
40 | 40 | from IPython.utils.traitlets import ( |
|
41 | 41 | List, Integer, Unicode, CBool, Bool, Instance, CRegExp |
|
42 | 42 | ) |
|
43 | 43 | |
|
44 | 44 | #----------------------------------------------------------------------------- |
|
45 | 45 | # Global utilities, errors and constants |
|
46 | 46 | #----------------------------------------------------------------------------- |
|
47 | 47 | |
|
48 | 48 | |
|
49 | 49 | class PrefilterError(Exception): |
|
50 | 50 | pass |
|
51 | 51 | |
|
52 | 52 | |
|
53 | 53 | # RegExp to identify potential function names |
|
54 | 54 | re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$') |
|
55 | 55 | |
|
56 | 56 | # RegExp to exclude strings with this start from autocalling. In |
|
57 | 57 | # particular, all binary operators should be excluded, so that if foo is |
|
58 | 58 | # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The |
|
59 | 59 | # characters '!=()' don't need to be checked for, as the checkPythonChars |
|
60 | 60 | # routine explicitely does so, to catch direct calls and rebindings of |
|
61 | 61 | # existing names. |
|
62 | 62 | |
|
63 | 63 | # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise |
|
64 | 64 | # it affects the rest of the group in square brackets. |
|
65 | 65 | re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]' |
|
66 | 66 | r'|^is |^not |^in |^and |^or ') |
|
67 | 67 | |
|
68 | 68 | # try to catch also methods for stuff in lists/tuples/dicts: off |
|
69 | 69 | # (experimental). For this to work, the line_split regexp would need |
|
70 | 70 | # to be modified so it wouldn't break things at '['. That line is |
|
71 | 71 | # nasty enough that I shouldn't change it until I can test it _well_. |
|
72 | 72 | #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$') |
|
73 | 73 | |
|
74 | 74 | |
|
75 | 75 | # Handler Check Utilities |
|
76 | 76 | def is_shadowed(identifier, ip): |
|
77 | 77 | """Is the given identifier defined in one of the namespaces which shadow |
|
78 | 78 | the alias and magic namespaces? Note that an identifier is different |
|
79 | 79 | than ifun, because it can not contain a '.' character.""" |
|
80 | 80 | # This is much safer than calling ofind, which can change state |
|
81 | 81 | return (identifier in ip.user_ns \ |
|
82 | 82 | or identifier in ip.user_global_ns \ |
|
83 | 83 | or identifier in ip.ns_table['builtin']) |
|
84 | 84 | |
|
85 | 85 | |
|
86 | 86 | #----------------------------------------------------------------------------- |
|
87 | 87 | # Main Prefilter manager |
|
88 | 88 | #----------------------------------------------------------------------------- |
|
89 | 89 | |
|
90 | 90 | |
|
91 | 91 | class PrefilterManager(Configurable): |
|
92 | 92 | """Main prefilter component. |
|
93 | 93 | |
|
94 | 94 | The IPython prefilter is run on all user input before it is run. The |
|
95 | 95 | prefilter consumes lines of input and produces transformed lines of |
|
96 | 96 | input. |
|
97 | 97 | |
|
98 | 98 | The iplementation consists of two phases: |
|
99 | 99 | |
|
100 | 100 | 1. Transformers |
|
101 | 101 | 2. Checkers and handlers |
|
102 | 102 | |
|
103 | 103 | Over time, we plan on deprecating the checkers and handlers and doing |
|
104 | 104 | everything in the transformers. |
|
105 | 105 | |
|
106 | 106 | The transformers are instances of :class:`PrefilterTransformer` and have |
|
107 | 107 | a single method :meth:`transform` that takes a line and returns a |
|
108 | 108 | transformed line. The transformation can be accomplished using any |
|
109 | 109 | tool, but our current ones use regular expressions for speed. |
|
110 | 110 | |
|
111 | 111 | After all the transformers have been run, the line is fed to the checkers, |
|
112 | 112 | which are instances of :class:`PrefilterChecker`. The line is passed to |
|
113 | 113 | the :meth:`check` method, which either returns `None` or a |
|
114 | 114 | :class:`PrefilterHandler` instance. If `None` is returned, the other |
|
115 | 115 | checkers are tried. If an :class:`PrefilterHandler` instance is returned, |
|
116 | 116 | the line is passed to the :meth:`handle` method of the returned |
|
117 | 117 | handler and no further checkers are tried. |
|
118 | 118 | |
|
119 | 119 | Both transformers and checkers have a `priority` attribute, that determines |
|
120 | 120 | the order in which they are called. Smaller priorities are tried first. |
|
121 | 121 | |
|
122 | 122 | Both transformers and checkers also have `enabled` attribute, which is |
|
123 | 123 | a boolean that determines if the instance is used. |
|
124 | 124 | |
|
125 | 125 | Users or developers can change the priority or enabled attribute of |
|
126 | 126 | transformers or checkers, but they must call the :meth:`sort_checkers` |
|
127 | 127 | or :meth:`sort_transformers` method after changing the priority. |
|
128 | 128 | """ |
|
129 | 129 | |
|
130 | 130 | multi_line_specials = CBool(True, config=True) |
|
131 | 131 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
132 | 132 | |
|
133 | 133 | def __init__(self, shell=None, **kwargs): |
|
134 | 134 | super(PrefilterManager, self).__init__(shell=shell, **kwargs) |
|
135 | 135 | self.shell = shell |
|
136 | 136 | self.init_transformers() |
|
137 | 137 | self.init_handlers() |
|
138 | 138 | self.init_checkers() |
|
139 | 139 | |
|
140 | 140 | #------------------------------------------------------------------------- |
|
141 | 141 | # API for managing transformers |
|
142 | 142 | #------------------------------------------------------------------------- |
|
143 | 143 | |
|
144 | 144 | def init_transformers(self): |
|
145 | 145 | """Create the default transformers.""" |
|
146 | 146 | self._transformers = [] |
|
147 | 147 | for transformer_cls in _default_transformers: |
|
148 | 148 | transformer_cls( |
|
149 | 149 | shell=self.shell, prefilter_manager=self, parent=self |
|
150 | 150 | ) |
|
151 | 151 | |
|
152 | 152 | def sort_transformers(self): |
|
153 | 153 | """Sort the transformers by priority. |
|
154 | 154 | |
|
155 | 155 | This must be called after the priority of a transformer is changed. |
|
156 | 156 | The :meth:`register_transformer` method calls this automatically. |
|
157 | 157 | """ |
|
158 | 158 | self._transformers.sort(key=lambda x: x.priority) |
|
159 | 159 | |
|
160 | 160 | @property |
|
161 | 161 | def transformers(self): |
|
162 | 162 | """Return a list of checkers, sorted by priority.""" |
|
163 | 163 | return self._transformers |
|
164 | 164 | |
|
165 | 165 | def register_transformer(self, transformer): |
|
166 | 166 | """Register a transformer instance.""" |
|
167 | 167 | if transformer not in self._transformers: |
|
168 | 168 | self._transformers.append(transformer) |
|
169 | 169 | self.sort_transformers() |
|
170 | 170 | |
|
171 | 171 | def unregister_transformer(self, transformer): |
|
172 | 172 | """Unregister a transformer instance.""" |
|
173 | 173 | if transformer in self._transformers: |
|
174 | 174 | self._transformers.remove(transformer) |
|
175 | 175 | |
|
176 | 176 | #------------------------------------------------------------------------- |
|
177 | 177 | # API for managing checkers |
|
178 | 178 | #------------------------------------------------------------------------- |
|
179 | 179 | |
|
180 | 180 | def init_checkers(self): |
|
181 | 181 | """Create the default checkers.""" |
|
182 | 182 | self._checkers = [] |
|
183 | 183 | for checker in _default_checkers: |
|
184 | 184 | checker( |
|
185 | 185 | shell=self.shell, prefilter_manager=self, parent=self |
|
186 | 186 | ) |
|
187 | 187 | |
|
188 | 188 | def sort_checkers(self): |
|
189 | 189 | """Sort the checkers by priority. |
|
190 | 190 | |
|
191 | 191 | This must be called after the priority of a checker is changed. |
|
192 | 192 | The :meth:`register_checker` method calls this automatically. |
|
193 | 193 | """ |
|
194 | 194 | self._checkers.sort(key=lambda x: x.priority) |
|
195 | 195 | |
|
196 | 196 | @property |
|
197 | 197 | def checkers(self): |
|
198 | 198 | """Return a list of checkers, sorted by priority.""" |
|
199 | 199 | return self._checkers |
|
200 | 200 | |
|
201 | 201 | def register_checker(self, checker): |
|
202 | 202 | """Register a checker instance.""" |
|
203 | 203 | if checker not in self._checkers: |
|
204 | 204 | self._checkers.append(checker) |
|
205 | 205 | self.sort_checkers() |
|
206 | 206 | |
|
207 | 207 | def unregister_checker(self, checker): |
|
208 | 208 | """Unregister a checker instance.""" |
|
209 | 209 | if checker in self._checkers: |
|
210 | 210 | self._checkers.remove(checker) |
|
211 | 211 | |
|
212 | 212 | #------------------------------------------------------------------------- |
|
213 | 213 | # API for managing checkers |
|
214 | 214 | #------------------------------------------------------------------------- |
|
215 | 215 | |
|
216 | 216 | def init_handlers(self): |
|
217 | 217 | """Create the default handlers.""" |
|
218 | 218 | self._handlers = {} |
|
219 | 219 | self._esc_handlers = {} |
|
220 | 220 | for handler in _default_handlers: |
|
221 | 221 | handler( |
|
222 | 222 | shell=self.shell, prefilter_manager=self, parent=self |
|
223 | 223 | ) |
|
224 | 224 | |
|
225 | 225 | @property |
|
226 | 226 | def handlers(self): |
|
227 | 227 | """Return a dict of all the handlers.""" |
|
228 | 228 | return self._handlers |
|
229 | 229 | |
|
230 | 230 | def register_handler(self, name, handler, esc_strings): |
|
231 | 231 | """Register a handler instance by name with esc_strings.""" |
|
232 | 232 | self._handlers[name] = handler |
|
233 | 233 | for esc_str in esc_strings: |
|
234 | 234 | self._esc_handlers[esc_str] = handler |
|
235 | 235 | |
|
236 | 236 | def unregister_handler(self, name, handler, esc_strings): |
|
237 | 237 | """Unregister a handler instance by name with esc_strings.""" |
|
238 | 238 | try: |
|
239 | 239 | del self._handlers[name] |
|
240 | 240 | except KeyError: |
|
241 | 241 | pass |
|
242 | 242 | for esc_str in esc_strings: |
|
243 | 243 | h = self._esc_handlers.get(esc_str) |
|
244 | 244 | if h is handler: |
|
245 | 245 | del self._esc_handlers[esc_str] |
|
246 | 246 | |
|
247 | 247 | def get_handler_by_name(self, name): |
|
248 | 248 | """Get a handler by its name.""" |
|
249 | 249 | return self._handlers.get(name) |
|
250 | 250 | |
|
251 | 251 | def get_handler_by_esc(self, esc_str): |
|
252 | 252 | """Get a handler by its escape string.""" |
|
253 | 253 | return self._esc_handlers.get(esc_str) |
|
254 | 254 | |
|
255 | 255 | #------------------------------------------------------------------------- |
|
256 | 256 | # Main prefiltering API |
|
257 | 257 | #------------------------------------------------------------------------- |
|
258 | 258 | |
|
259 | 259 | def prefilter_line_info(self, line_info): |
|
260 | 260 | """Prefilter a line that has been converted to a LineInfo object. |
|
261 | 261 | |
|
262 | 262 | This implements the checker/handler part of the prefilter pipe. |
|
263 | 263 | """ |
|
264 | 264 | # print "prefilter_line_info: ", line_info |
|
265 | 265 | handler = self.find_handler(line_info) |
|
266 | 266 | return handler.handle(line_info) |
|
267 | 267 | |
|
268 | 268 | def find_handler(self, line_info): |
|
269 | 269 | """Find a handler for the line_info by trying checkers.""" |
|
270 | 270 | for checker in self.checkers: |
|
271 | 271 | if checker.enabled: |
|
272 | 272 | handler = checker.check(line_info) |
|
273 | 273 | if handler: |
|
274 | 274 | return handler |
|
275 | 275 | return self.get_handler_by_name('normal') |
|
276 | 276 | |
|
277 | 277 | def transform_line(self, line, continue_prompt): |
|
278 | 278 | """Calls the enabled transformers in order of increasing priority.""" |
|
279 | 279 | for transformer in self.transformers: |
|
280 | 280 | if transformer.enabled: |
|
281 | 281 | line = transformer.transform(line, continue_prompt) |
|
282 | 282 | return line |
|
283 | 283 | |
|
284 | 284 | def prefilter_line(self, line, continue_prompt=False): |
|
285 | 285 | """Prefilter a single input line as text. |
|
286 | 286 | |
|
287 | 287 | This method prefilters a single line of text by calling the |
|
288 | 288 | transformers and then the checkers/handlers. |
|
289 | 289 | """ |
|
290 | 290 | |
|
291 | 291 | # print "prefilter_line: ", line, continue_prompt |
|
292 | 292 | # All handlers *must* return a value, even if it's blank (''). |
|
293 | 293 | |
|
294 | 294 | # save the line away in case we crash, so the post-mortem handler can |
|
295 | 295 | # record it |
|
296 | 296 | self.shell._last_input_line = line |
|
297 | 297 | |
|
298 | 298 | if not line: |
|
299 | 299 | # Return immediately on purely empty lines, so that if the user |
|
300 | 300 | # previously typed some whitespace that started a continuation |
|
301 | 301 | # prompt, he can break out of that loop with just an empty line. |
|
302 | 302 | # This is how the default python prompt works. |
|
303 | 303 | return '' |
|
304 | 304 | |
|
305 | 305 | # At this point, we invoke our transformers. |
|
306 | 306 | if not continue_prompt or (continue_prompt and self.multi_line_specials): |
|
307 | 307 | line = self.transform_line(line, continue_prompt) |
|
308 | 308 | |
|
309 | 309 | # Now we compute line_info for the checkers and handlers |
|
310 | 310 | line_info = LineInfo(line, continue_prompt) |
|
311 | 311 | |
|
312 | 312 | # the input history needs to track even empty lines |
|
313 | 313 | stripped = line.strip() |
|
314 | 314 | |
|
315 | 315 | normal_handler = self.get_handler_by_name('normal') |
|
316 | 316 | if not stripped: |
|
317 | 317 | return normal_handler.handle(line_info) |
|
318 | 318 | |
|
319 | 319 | # special handlers are only allowed for single line statements |
|
320 | 320 | if continue_prompt and not self.multi_line_specials: |
|
321 | 321 | return normal_handler.handle(line_info) |
|
322 | 322 | |
|
323 | 323 | prefiltered = self.prefilter_line_info(line_info) |
|
324 | 324 | # print "prefiltered line: %r" % prefiltered |
|
325 | 325 | return prefiltered |
|
326 | 326 | |
|
327 | 327 | def prefilter_lines(self, lines, continue_prompt=False): |
|
328 | 328 | """Prefilter multiple input lines of text. |
|
329 | 329 | |
|
330 | 330 | This is the main entry point for prefiltering multiple lines of |
|
331 | 331 | input. This simply calls :meth:`prefilter_line` for each line of |
|
332 | 332 | input. |
|
333 | 333 | |
|
334 | 334 | This covers cases where there are multiple lines in the user entry, |
|
335 | 335 | which is the case when the user goes back to a multiline history |
|
336 | 336 | entry and presses enter. |
|
337 | 337 | """ |
|
338 | 338 | llines = lines.rstrip('\n').split('\n') |
|
339 | 339 | # We can get multiple lines in one shot, where multiline input 'blends' |
|
340 | 340 | # into one line, in cases like recalling from the readline history |
|
341 | 341 | # buffer. We need to make sure that in such cases, we correctly |
|
342 | 342 | # communicate downstream which line is first and which are continuation |
|
343 | 343 | # ones. |
|
344 | 344 | if len(llines) > 1: |
|
345 | 345 | out = '\n'.join([self.prefilter_line(line, lnum>0) |
|
346 | 346 | for lnum, line in enumerate(llines) ]) |
|
347 | 347 | else: |
|
348 | 348 | out = self.prefilter_line(llines[0], continue_prompt) |
|
349 | 349 | |
|
350 | 350 | return out |
|
351 | 351 | |
|
352 | 352 | #----------------------------------------------------------------------------- |
|
353 | 353 | # Prefilter transformers |
|
354 | 354 | #----------------------------------------------------------------------------- |
|
355 | 355 | |
|
356 | 356 | |
|
357 | 357 | class PrefilterTransformer(Configurable): |
|
358 | 358 | """Transform a line of user input.""" |
|
359 | 359 | |
|
360 | 360 | priority = Integer(100, config=True) |
|
361 | 361 | # Transformers don't currently use shell or prefilter_manager, but as we |
|
362 | 362 | # move away from checkers and handlers, they will need them. |
|
363 | 363 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
364 | 364 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
365 | 365 | enabled = Bool(True, config=True) |
|
366 | 366 | |
|
367 | 367 | def __init__(self, shell=None, prefilter_manager=None, **kwargs): |
|
368 | 368 | super(PrefilterTransformer, self).__init__( |
|
369 | 369 | shell=shell, prefilter_manager=prefilter_manager, **kwargs |
|
370 | 370 | ) |
|
371 | 371 | self.prefilter_manager.register_transformer(self) |
|
372 | 372 | |
|
373 | 373 | def transform(self, line, continue_prompt): |
|
374 | 374 | """Transform a line, returning the new one.""" |
|
375 | 375 | return None |
|
376 | 376 | |
|
377 | 377 | def __repr__(self): |
|
378 | 378 | return "<%s(priority=%r, enabled=%r)>" % ( |
|
379 | 379 | self.__class__.__name__, self.priority, self.enabled) |
|
380 | 380 | |
|
381 | 381 | |
|
382 | 382 | #----------------------------------------------------------------------------- |
|
383 | 383 | # Prefilter checkers |
|
384 | 384 | #----------------------------------------------------------------------------- |
|
385 | 385 | |
|
386 | 386 | |
|
387 | 387 | class PrefilterChecker(Configurable): |
|
388 | 388 | """Inspect an input line and return a handler for that line.""" |
|
389 | 389 | |
|
390 | 390 | priority = Integer(100, config=True) |
|
391 | 391 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
392 | 392 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
393 | 393 | enabled = Bool(True, config=True) |
|
394 | 394 | |
|
395 | 395 | def __init__(self, shell=None, prefilter_manager=None, **kwargs): |
|
396 | 396 | super(PrefilterChecker, self).__init__( |
|
397 | 397 | shell=shell, prefilter_manager=prefilter_manager, **kwargs |
|
398 | 398 | ) |
|
399 | 399 | self.prefilter_manager.register_checker(self) |
|
400 | 400 | |
|
401 | 401 | def check(self, line_info): |
|
402 | 402 | """Inspect line_info and return a handler instance or None.""" |
|
403 | 403 | return None |
|
404 | 404 | |
|
405 | 405 | def __repr__(self): |
|
406 | 406 | return "<%s(priority=%r, enabled=%r)>" % ( |
|
407 | 407 | self.__class__.__name__, self.priority, self.enabled) |
|
408 | 408 | |
|
409 | 409 | |
|
410 | 410 | class EmacsChecker(PrefilterChecker): |
|
411 | 411 | |
|
412 | 412 | priority = Integer(100, config=True) |
|
413 | 413 | enabled = Bool(False, config=True) |
|
414 | 414 | |
|
415 | 415 | def check(self, line_info): |
|
416 | 416 | "Emacs ipython-mode tags certain input lines." |
|
417 | 417 | if line_info.line.endswith('# PYTHON-MODE'): |
|
418 | 418 | return self.prefilter_manager.get_handler_by_name('emacs') |
|
419 | 419 | else: |
|
420 | 420 | return None |
|
421 | 421 | |
|
422 | 422 | |
|
423 | 423 | class MacroChecker(PrefilterChecker): |
|
424 | 424 | |
|
425 | 425 | priority = Integer(250, config=True) |
|
426 | 426 | |
|
427 | 427 | def check(self, line_info): |
|
428 | 428 | obj = self.shell.user_ns.get(line_info.ifun) |
|
429 | 429 | if isinstance(obj, Macro): |
|
430 | 430 | return self.prefilter_manager.get_handler_by_name('macro') |
|
431 | 431 | else: |
|
432 | 432 | return None |
|
433 | 433 | |
|
434 | 434 | |
|
435 | 435 | class IPyAutocallChecker(PrefilterChecker): |
|
436 | 436 | |
|
437 | 437 | priority = Integer(300, config=True) |
|
438 | 438 | |
|
439 | 439 | def check(self, line_info): |
|
440 | 440 | "Instances of IPyAutocall in user_ns get autocalled immediately" |
|
441 | 441 | obj = self.shell.user_ns.get(line_info.ifun, None) |
|
442 | 442 | if isinstance(obj, IPyAutocall): |
|
443 | 443 | obj.set_ip(self.shell) |
|
444 | 444 | return self.prefilter_manager.get_handler_by_name('auto') |
|
445 | 445 | else: |
|
446 | 446 | return None |
|
447 | 447 | |
|
448 | 448 | |
|
449 | 449 | class AssignmentChecker(PrefilterChecker): |
|
450 | 450 | |
|
451 | 451 | priority = Integer(600, config=True) |
|
452 | 452 | |
|
453 | 453 | def check(self, line_info): |
|
454 | 454 | """Check to see if user is assigning to a var for the first time, in |
|
455 | 455 | which case we want to avoid any sort of automagic / autocall games. |
|
456 | 456 | |
|
457 | 457 | This allows users to assign to either alias or magic names true python |
|
458 | 458 | variables (the magic/alias systems always take second seat to true |
|
459 | 459 | python code). E.g. ls='hi', or ls,that=1,2""" |
|
460 | 460 | if line_info.the_rest: |
|
461 | 461 | if line_info.the_rest[0] in '=,': |
|
462 | 462 | return self.prefilter_manager.get_handler_by_name('normal') |
|
463 | 463 | else: |
|
464 | 464 | return None |
|
465 | 465 | |
|
466 | 466 | |
|
467 | 467 | class AutoMagicChecker(PrefilterChecker): |
|
468 | 468 | |
|
469 | 469 | priority = Integer(700, config=True) |
|
470 | 470 | |
|
471 | 471 | def check(self, line_info): |
|
472 | 472 | """If the ifun is magic, and automagic is on, run it. Note: normal, |
|
473 | 473 | non-auto magic would already have been triggered via '%' in |
|
474 | 474 | check_esc_chars. This just checks for automagic. Also, before |
|
475 | 475 | triggering the magic handler, make sure that there is nothing in the |
|
476 | 476 | user namespace which could shadow it.""" |
|
477 | 477 | if not self.shell.automagic or not self.shell.find_magic(line_info.ifun): |
|
478 | 478 | return None |
|
479 | 479 | |
|
480 | 480 | # We have a likely magic method. Make sure we should actually call it. |
|
481 | 481 | if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials: |
|
482 | 482 | return None |
|
483 | 483 | |
|
484 | 484 | head = line_info.ifun.split('.',1)[0] |
|
485 | 485 | if is_shadowed(head, self.shell): |
|
486 | 486 | return None |
|
487 | 487 | |
|
488 | 488 | return self.prefilter_manager.get_handler_by_name('magic') |
|
489 | 489 | |
|
490 | 490 | |
|
491 | class AliasChecker(PrefilterChecker): | |
|
492 | ||
|
493 | priority = Integer(800, config=True) | |
|
494 | ||
|
495 | def check(self, line_info): | |
|
496 | "Check if the initital identifier on the line is an alias." | |
|
497 | # Note: aliases can not contain '.' | |
|
498 | head = line_info.ifun.split('.',1)[0] | |
|
499 | if line_info.ifun not in self.shell.alias_manager \ | |
|
500 | or head not in self.shell.alias_manager \ | |
|
501 | or is_shadowed(head, self.shell): | |
|
502 | return None | |
|
503 | ||
|
504 | return self.prefilter_manager.get_handler_by_name('alias') | |
|
505 | ||
|
506 | ||
|
507 | 491 | class PythonOpsChecker(PrefilterChecker): |
|
508 | 492 | |
|
509 | 493 | priority = Integer(900, config=True) |
|
510 | 494 | |
|
511 | 495 | def check(self, line_info): |
|
512 | 496 | """If the 'rest' of the line begins with a function call or pretty much |
|
513 | 497 | any python operator, we should simply execute the line (regardless of |
|
514 | 498 | whether or not there's a possible autocall expansion). This avoids |
|
515 | 499 | spurious (and very confusing) geattr() accesses.""" |
|
516 | 500 | if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|': |
|
517 | 501 | return self.prefilter_manager.get_handler_by_name('normal') |
|
518 | 502 | else: |
|
519 | 503 | return None |
|
520 | 504 | |
|
521 | 505 | |
|
522 | 506 | class AutocallChecker(PrefilterChecker): |
|
523 | 507 | |
|
524 | 508 | priority = Integer(1000, config=True) |
|
525 | 509 | |
|
526 | 510 | function_name_regexp = CRegExp(re_fun_name, config=True, |
|
527 | 511 | help="RegExp to identify potential function names.") |
|
528 | 512 | exclude_regexp = CRegExp(re_exclude_auto, config=True, |
|
529 | 513 | help="RegExp to exclude strings with this start from autocalling.") |
|
530 | 514 | |
|
531 | 515 | def check(self, line_info): |
|
532 | 516 | "Check if the initial word/function is callable and autocall is on." |
|
533 | 517 | if not self.shell.autocall: |
|
534 | 518 | return None |
|
535 | 519 | |
|
536 | 520 | oinfo = line_info.ofind(self.shell) # This can mutate state via getattr |
|
537 | 521 | if not oinfo['found']: |
|
538 | 522 | return None |
|
539 | 523 | |
|
540 | 524 | if callable(oinfo['obj']) \ |
|
541 | 525 | and (not self.exclude_regexp.match(line_info.the_rest)) \ |
|
542 | 526 | and self.function_name_regexp.match(line_info.ifun): |
|
543 | 527 | return self.prefilter_manager.get_handler_by_name('auto') |
|
544 | 528 | else: |
|
545 | 529 | return None |
|
546 | 530 | |
|
547 | 531 | |
|
548 | 532 | #----------------------------------------------------------------------------- |
|
549 | 533 | # Prefilter handlers |
|
550 | 534 | #----------------------------------------------------------------------------- |
|
551 | 535 | |
|
552 | 536 | |
|
553 | 537 | class PrefilterHandler(Configurable): |
|
554 | 538 | |
|
555 | 539 | handler_name = Unicode('normal') |
|
556 | 540 | esc_strings = List([]) |
|
557 | 541 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
558 | 542 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
559 | 543 | |
|
560 | 544 | def __init__(self, shell=None, prefilter_manager=None, **kwargs): |
|
561 | 545 | super(PrefilterHandler, self).__init__( |
|
562 | 546 | shell=shell, prefilter_manager=prefilter_manager, **kwargs |
|
563 | 547 | ) |
|
564 | 548 | self.prefilter_manager.register_handler( |
|
565 | 549 | self.handler_name, |
|
566 | 550 | self, |
|
567 | 551 | self.esc_strings |
|
568 | 552 | ) |
|
569 | 553 | |
|
570 | 554 | def handle(self, line_info): |
|
571 | 555 | # print "normal: ", line_info |
|
572 | 556 | """Handle normal input lines. Use as a template for handlers.""" |
|
573 | 557 | |
|
574 | 558 | # With autoindent on, we need some way to exit the input loop, and I |
|
575 | 559 | # don't want to force the user to have to backspace all the way to |
|
576 | 560 | # clear the line. The rule will be in this case, that either two |
|
577 | 561 | # lines of pure whitespace in a row, or a line of pure whitespace but |
|
578 | 562 | # of a size different to the indent level, will exit the input loop. |
|
579 | 563 | line = line_info.line |
|
580 | 564 | continue_prompt = line_info.continue_prompt |
|
581 | 565 | |
|
582 | 566 | if (continue_prompt and |
|
583 | 567 | self.shell.autoindent and |
|
584 | 568 | line.isspace() and |
|
585 | 569 | 0 < abs(len(line) - self.shell.indent_current_nsp) <= 2): |
|
586 | 570 | line = '' |
|
587 | 571 | |
|
588 | 572 | return line |
|
589 | 573 | |
|
590 | 574 | def __str__(self): |
|
591 | 575 | return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name) |
|
592 | 576 | |
|
593 | 577 | |
|
594 | class AliasHandler(PrefilterHandler): | |
|
595 | ||
|
596 | handler_name = Unicode('alias') | |
|
597 | ||
|
598 | def handle(self, line_info): | |
|
599 | """Handle alias input lines. """ | |
|
600 | transformed = self.shell.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest) | |
|
601 | # pre is needed, because it carries the leading whitespace. Otherwise | |
|
602 | # aliases won't work in indented sections. | |
|
603 | line_out = '%sget_ipython().system(%r)' % (line_info.pre_whitespace, transformed) | |
|
604 | ||
|
605 | return line_out | |
|
606 | ||
|
607 | ||
|
608 | 578 | class MacroHandler(PrefilterHandler): |
|
609 | 579 | handler_name = Unicode("macro") |
|
610 | 580 | |
|
611 | 581 | def handle(self, line_info): |
|
612 | 582 | obj = self.shell.user_ns.get(line_info.ifun) |
|
613 | 583 | pre_space = line_info.pre_whitespace |
|
614 | 584 | line_sep = "\n" + pre_space |
|
615 | 585 | return pre_space + line_sep.join(obj.value.splitlines()) |
|
616 | 586 | |
|
617 | 587 | |
|
618 | 588 | class MagicHandler(PrefilterHandler): |
|
619 | 589 | |
|
620 | 590 | handler_name = Unicode('magic') |
|
621 | 591 | esc_strings = List([ESC_MAGIC]) |
|
622 | 592 | |
|
623 | 593 | def handle(self, line_info): |
|
624 | 594 | """Execute magic functions.""" |
|
625 | 595 | ifun = line_info.ifun |
|
626 | 596 | the_rest = line_info.the_rest |
|
627 | 597 | cmd = '%sget_ipython().magic(%r)' % (line_info.pre_whitespace, |
|
628 | 598 | (ifun + " " + the_rest)) |
|
629 | 599 | return cmd |
|
630 | 600 | |
|
631 | 601 | |
|
632 | 602 | class AutoHandler(PrefilterHandler): |
|
633 | 603 | |
|
634 | 604 | handler_name = Unicode('auto') |
|
635 | 605 | esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2]) |
|
636 | 606 | |
|
637 | 607 | def handle(self, line_info): |
|
638 | 608 | """Handle lines which can be auto-executed, quoting if requested.""" |
|
639 | 609 | line = line_info.line |
|
640 | 610 | ifun = line_info.ifun |
|
641 | 611 | the_rest = line_info.the_rest |
|
642 | 612 | pre = line_info.pre |
|
643 | 613 | esc = line_info.esc |
|
644 | 614 | continue_prompt = line_info.continue_prompt |
|
645 | 615 | obj = line_info.ofind(self.shell)['obj'] |
|
646 | 616 | #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg |
|
647 | 617 | |
|
648 | 618 | # This should only be active for single-line input! |
|
649 | 619 | if continue_prompt: |
|
650 | 620 | return line |
|
651 | 621 | |
|
652 | 622 | force_auto = isinstance(obj, IPyAutocall) |
|
653 | 623 | |
|
654 | 624 | # User objects sometimes raise exceptions on attribute access other |
|
655 | 625 | # than AttributeError (we've seen it in the past), so it's safest to be |
|
656 | 626 | # ultra-conservative here and catch all. |
|
657 | 627 | try: |
|
658 | 628 | auto_rewrite = obj.rewrite |
|
659 | 629 | except Exception: |
|
660 | 630 | auto_rewrite = True |
|
661 | 631 | |
|
662 | 632 | if esc == ESC_QUOTE: |
|
663 | 633 | # Auto-quote splitting on whitespace |
|
664 | 634 | newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) ) |
|
665 | 635 | elif esc == ESC_QUOTE2: |
|
666 | 636 | # Auto-quote whole string |
|
667 | 637 | newcmd = '%s("%s")' % (ifun,the_rest) |
|
668 | 638 | elif esc == ESC_PAREN: |
|
669 | 639 | newcmd = '%s(%s)' % (ifun,",".join(the_rest.split())) |
|
670 | 640 | else: |
|
671 | 641 | # Auto-paren. |
|
672 | 642 | if force_auto: |
|
673 | 643 | # Don't rewrite if it is already a call. |
|
674 | 644 | do_rewrite = not the_rest.startswith('(') |
|
675 | 645 | else: |
|
676 | 646 | if not the_rest: |
|
677 | 647 | # We only apply it to argument-less calls if the autocall |
|
678 | 648 | # parameter is set to 2. |
|
679 | 649 | do_rewrite = (self.shell.autocall >= 2) |
|
680 | 650 | elif the_rest.startswith('[') and hasattr(obj, '__getitem__'): |
|
681 | 651 | # Don't autocall in this case: item access for an object |
|
682 | 652 | # which is BOTH callable and implements __getitem__. |
|
683 | 653 | do_rewrite = False |
|
684 | 654 | else: |
|
685 | 655 | do_rewrite = True |
|
686 | 656 | |
|
687 | 657 | # Figure out the rewritten command |
|
688 | 658 | if do_rewrite: |
|
689 | 659 | if the_rest.endswith(';'): |
|
690 | 660 | newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1]) |
|
691 | 661 | else: |
|
692 | 662 | newcmd = '%s(%s)' % (ifun.rstrip(), the_rest) |
|
693 | 663 | else: |
|
694 | 664 | normal_handler = self.prefilter_manager.get_handler_by_name('normal') |
|
695 | 665 | return normal_handler.handle(line_info) |
|
696 | 666 | |
|
697 | 667 | # Display the rewritten call |
|
698 | 668 | if auto_rewrite: |
|
699 | 669 | self.shell.auto_rewrite_input(newcmd) |
|
700 | 670 | |
|
701 | 671 | return newcmd |
|
702 | 672 | |
|
703 | 673 | |
|
704 | 674 | class EmacsHandler(PrefilterHandler): |
|
705 | 675 | |
|
706 | 676 | handler_name = Unicode('emacs') |
|
707 | 677 | esc_strings = List([]) |
|
708 | 678 | |
|
709 | 679 | def handle(self, line_info): |
|
710 | 680 | """Handle input lines marked by python-mode.""" |
|
711 | 681 | |
|
712 | 682 | # Currently, nothing is done. Later more functionality can be added |
|
713 | 683 | # here if needed. |
|
714 | 684 | |
|
715 | 685 | # The input cache shouldn't be updated |
|
716 | 686 | return line_info.line |
|
717 | 687 | |
|
718 | 688 | |
|
719 | 689 | #----------------------------------------------------------------------------- |
|
720 | 690 | # Defaults |
|
721 | 691 | #----------------------------------------------------------------------------- |
|
722 | 692 | |
|
723 | 693 | |
|
724 | 694 | _default_transformers = [ |
|
725 | 695 | ] |
|
726 | 696 | |
|
727 | 697 | _default_checkers = [ |
|
728 | 698 | EmacsChecker, |
|
729 | 699 | MacroChecker, |
|
730 | 700 | IPyAutocallChecker, |
|
731 | 701 | AssignmentChecker, |
|
732 | 702 | AutoMagicChecker, |
|
733 | AliasChecker, | |
|
734 | 703 | PythonOpsChecker, |
|
735 | 704 | AutocallChecker |
|
736 | 705 | ] |
|
737 | 706 | |
|
738 | 707 | _default_handlers = [ |
|
739 | 708 | PrefilterHandler, |
|
740 | AliasHandler, | |
|
741 | 709 | MacroHandler, |
|
742 | 710 | MagicHandler, |
|
743 | 711 | AutoHandler, |
|
744 | 712 | EmacsHandler |
|
745 | 713 | ] |
@@ -1,119 +1,97 b'' | |||
|
1 | 1 | """Tests for input handlers. |
|
2 | 2 | """ |
|
3 | 3 | #----------------------------------------------------------------------------- |
|
4 | 4 | # Module imports |
|
5 | 5 | #----------------------------------------------------------------------------- |
|
6 | 6 | |
|
7 | 7 | # third party |
|
8 | 8 | import nose.tools as nt |
|
9 | 9 | |
|
10 | 10 | # our own packages |
|
11 | 11 | from IPython.core import autocall |
|
12 | 12 | from IPython.testing import tools as tt |
|
13 | 13 | from IPython.testing.globalipapp import get_ipython |
|
14 | 14 | from IPython.utils import py3compat |
|
15 | 15 | |
|
16 | 16 | #----------------------------------------------------------------------------- |
|
17 | 17 | # Globals |
|
18 | 18 | #----------------------------------------------------------------------------- |
|
19 | 19 | |
|
20 | 20 | # Get the public instance of IPython |
|
21 | 21 | ip = get_ipython() |
|
22 | 22 | |
|
23 | 23 | failures = [] |
|
24 | 24 | num_tests = 0 |
|
25 | 25 | |
|
26 | 26 | #----------------------------------------------------------------------------- |
|
27 | 27 | # Test functions |
|
28 | 28 | #----------------------------------------------------------------------------- |
|
29 | 29 | |
|
30 | 30 | class CallableIndexable(object): |
|
31 | 31 | def __getitem__(self, idx): return True |
|
32 | 32 | def __call__(self, *args, **kws): return True |
|
33 | 33 | |
|
34 | 34 | |
|
35 | 35 | class Autocallable(autocall.IPyAutocall): |
|
36 | 36 | def __call__(self): |
|
37 | 37 | return "called" |
|
38 | 38 | |
|
39 | 39 | |
|
40 | 40 | def run(tests): |
|
41 | 41 | """Loop through a list of (pre, post) inputs, where pre is the string |
|
42 | 42 | handed to ipython, and post is how that string looks after it's been |
|
43 | 43 | transformed (i.e. ipython's notion of _i)""" |
|
44 | 44 | tt.check_pairs(ip.prefilter_manager.prefilter_lines, tests) |
|
45 | 45 | |
|
46 | 46 | |
|
47 | 47 | def test_handlers(): |
|
48 | # alias expansion | |
|
49 | ||
|
50 | # We're using 'true' as our syscall of choice because it doesn't | |
|
51 | # write anything to stdout. | |
|
52 | ||
|
53 | # Turn off actual execution of aliases, because it's noisy | |
|
54 | old_system_cmd = ip.system | |
|
55 | ip.system = lambda cmd: None | |
|
56 | ||
|
57 | ||
|
58 | ip.alias_manager.alias_table['an_alias'] = (0, 'true') | |
|
59 | # These are useful for checking a particular recursive alias issue | |
|
60 | ip.alias_manager.alias_table['top'] = (0, 'd:/cygwin/top') | |
|
61 | ip.alias_manager.alias_table['d'] = (0, 'true') | |
|
62 | run([(i,py3compat.u_format(o)) for i,o in \ | |
|
63 | [("an_alias", "get_ipython().system({u}'true ')"), # alias | |
|
64 | # Below: recursive aliases should expand whitespace-surrounded | |
|
65 | # chars, *not* initial chars which happen to be aliases: | |
|
66 | ("top", "get_ipython().system({u}'d:/cygwin/top ')"), | |
|
67 | ]]) | |
|
68 | ip.system = old_system_cmd | |
|
69 | ||
|
70 | 48 | call_idx = CallableIndexable() |
|
71 | 49 | ip.user_ns['call_idx'] = call_idx |
|
72 | 50 | |
|
73 | 51 | # For many of the below, we're also checking that leading whitespace |
|
74 | 52 | # turns off the esc char, which it should unless there is a continuation |
|
75 | 53 | # line. |
|
76 | 54 | run([(i,py3compat.u_format(o)) for i,o in \ |
|
77 | 55 | [('"no change"', '"no change"'), # normal |
|
78 | 56 | (u"lsmagic", "get_ipython().magic({u}'lsmagic ')"), # magic |
|
79 | 57 | #("a = b # PYTHON-MODE", '_i'), # emacs -- avoids _in cache |
|
80 | 58 | ]]) |
|
81 | 59 | |
|
82 | 60 | # Objects which are instances of IPyAutocall are *always* autocalled |
|
83 | 61 | autocallable = Autocallable() |
|
84 | 62 | ip.user_ns['autocallable'] = autocallable |
|
85 | 63 | |
|
86 | 64 | # auto |
|
87 | 65 | ip.magic('autocall 0') |
|
88 | 66 | # Only explicit escapes or instances of IPyAutocallable should get |
|
89 | 67 | # expanded |
|
90 | 68 | run([ |
|
91 | 69 | ('len "abc"', 'len "abc"'), |
|
92 | 70 | ('autocallable', 'autocallable()'), |
|
93 | 71 | # Don't add extra brackets (gh-1117) |
|
94 | 72 | ('autocallable()', 'autocallable()'), |
|
95 | 73 | ]) |
|
96 | 74 | ip.magic('autocall 1') |
|
97 | 75 | run([ |
|
98 | 76 | ('len "abc"', 'len("abc")'), |
|
99 | 77 | ('len "abc";', 'len("abc");'), # ; is special -- moves out of parens |
|
100 | 78 | # Autocall is turned off if first arg is [] and the object |
|
101 | 79 | # is both callable and indexable. Like so: |
|
102 | 80 | ('len [1,2]', 'len([1,2])'), # len doesn't support __getitem__... |
|
103 | 81 | ('call_idx [1]', 'call_idx [1]'), # call_idx *does*.. |
|
104 | 82 | ('call_idx 1', 'call_idx(1)'), |
|
105 | 83 | ('len', 'len'), # only at 2 does it auto-call on single args |
|
106 | 84 | ]) |
|
107 | 85 | ip.magic('autocall 2') |
|
108 | 86 | run([ |
|
109 | 87 | ('len "abc"', 'len("abc")'), |
|
110 | 88 | ('len "abc";', 'len("abc");'), |
|
111 | 89 | ('len [1,2]', 'len([1,2])'), |
|
112 | 90 | ('call_idx [1]', 'call_idx [1]'), |
|
113 | 91 | ('call_idx 1', 'call_idx(1)'), |
|
114 | 92 | # This is what's different: |
|
115 | 93 | ('len', 'len()'), # only at 2 does it auto-call on single args |
|
116 | 94 | ]) |
|
117 | 95 | ip.magic('autocall 1') |
|
118 | 96 | |
|
119 | 97 | nt.assert_equal(failures, []) |
@@ -1,652 +1,641 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Tests for the key interactiveshell module. |
|
3 | 3 | |
|
4 | 4 | Historically the main classes in interactiveshell have been under-tested. This |
|
5 | 5 | module should grow as many single-method tests as possible to trap many of the |
|
6 | 6 | recurring bugs we seem to encounter with high-level interaction. |
|
7 | 7 | |
|
8 | 8 | Authors |
|
9 | 9 | ------- |
|
10 | 10 | * Fernando Perez |
|
11 | 11 | """ |
|
12 | 12 | #----------------------------------------------------------------------------- |
|
13 | 13 | # Copyright (C) 2011 The IPython Development Team |
|
14 | 14 | # |
|
15 | 15 | # Distributed under the terms of the BSD License. The full license is in |
|
16 | 16 | # the file COPYING, distributed as part of this software. |
|
17 | 17 | #----------------------------------------------------------------------------- |
|
18 | 18 | |
|
19 | 19 | #----------------------------------------------------------------------------- |
|
20 | 20 | # Imports |
|
21 | 21 | #----------------------------------------------------------------------------- |
|
22 | 22 | # stdlib |
|
23 | 23 | import ast |
|
24 | 24 | import os |
|
25 | 25 | import shutil |
|
26 | 26 | import sys |
|
27 | 27 | import tempfile |
|
28 | 28 | import unittest |
|
29 | 29 | from os.path import join |
|
30 | 30 | from StringIO import StringIO |
|
31 | 31 | |
|
32 | 32 | # third-party |
|
33 | 33 | import nose.tools as nt |
|
34 | 34 | |
|
35 | 35 | # Our own |
|
36 | 36 | from IPython.testing.decorators import skipif, onlyif_unicode_paths |
|
37 | 37 | from IPython.testing import tools as tt |
|
38 | 38 | from IPython.utils import io |
|
39 | 39 | |
|
40 | 40 | #----------------------------------------------------------------------------- |
|
41 | 41 | # Globals |
|
42 | 42 | #----------------------------------------------------------------------------- |
|
43 | 43 | # This is used by every single test, no point repeating it ad nauseam |
|
44 | 44 | ip = get_ipython() |
|
45 | 45 | |
|
46 | 46 | #----------------------------------------------------------------------------- |
|
47 | 47 | # Tests |
|
48 | 48 | #----------------------------------------------------------------------------- |
|
49 | 49 | |
|
50 | 50 | class InteractiveShellTestCase(unittest.TestCase): |
|
51 | 51 | def test_naked_string_cells(self): |
|
52 | 52 | """Test that cells with only naked strings are fully executed""" |
|
53 | 53 | # First, single-line inputs |
|
54 | 54 | ip.run_cell('"a"\n') |
|
55 | 55 | self.assertEqual(ip.user_ns['_'], 'a') |
|
56 | 56 | # And also multi-line cells |
|
57 | 57 | ip.run_cell('"""a\nb"""\n') |
|
58 | 58 | self.assertEqual(ip.user_ns['_'], 'a\nb') |
|
59 | 59 | |
|
60 | 60 | def test_run_empty_cell(self): |
|
61 | 61 | """Just make sure we don't get a horrible error with a blank |
|
62 | 62 | cell of input. Yes, I did overlook that.""" |
|
63 | 63 | old_xc = ip.execution_count |
|
64 | 64 | ip.run_cell('') |
|
65 | 65 | self.assertEqual(ip.execution_count, old_xc) |
|
66 | 66 | |
|
67 | 67 | def test_run_cell_multiline(self): |
|
68 | 68 | """Multi-block, multi-line cells must execute correctly. |
|
69 | 69 | """ |
|
70 | 70 | src = '\n'.join(["x=1", |
|
71 | 71 | "y=2", |
|
72 | 72 | "if 1:", |
|
73 | 73 | " x += 1", |
|
74 | 74 | " y += 1",]) |
|
75 | 75 | ip.run_cell(src) |
|
76 | 76 | self.assertEqual(ip.user_ns['x'], 2) |
|
77 | 77 | self.assertEqual(ip.user_ns['y'], 3) |
|
78 | 78 | |
|
79 | 79 | def test_multiline_string_cells(self): |
|
80 | 80 | "Code sprinkled with multiline strings should execute (GH-306)" |
|
81 | 81 | ip.run_cell('tmp=0') |
|
82 | 82 | self.assertEqual(ip.user_ns['tmp'], 0) |
|
83 | 83 | ip.run_cell('tmp=1;"""a\nb"""\n') |
|
84 | 84 | self.assertEqual(ip.user_ns['tmp'], 1) |
|
85 | 85 | |
|
86 | 86 | def test_dont_cache_with_semicolon(self): |
|
87 | 87 | "Ending a line with semicolon should not cache the returned object (GH-307)" |
|
88 | 88 | oldlen = len(ip.user_ns['Out']) |
|
89 | 89 | a = ip.run_cell('1;', store_history=True) |
|
90 | 90 | newlen = len(ip.user_ns['Out']) |
|
91 | 91 | self.assertEqual(oldlen, newlen) |
|
92 | 92 | #also test the default caching behavior |
|
93 | 93 | ip.run_cell('1', store_history=True) |
|
94 | 94 | newlen = len(ip.user_ns['Out']) |
|
95 | 95 | self.assertEqual(oldlen+1, newlen) |
|
96 | 96 | |
|
97 | 97 | def test_In_variable(self): |
|
98 | 98 | "Verify that In variable grows with user input (GH-284)" |
|
99 | 99 | oldlen = len(ip.user_ns['In']) |
|
100 | 100 | ip.run_cell('1;', store_history=True) |
|
101 | 101 | newlen = len(ip.user_ns['In']) |
|
102 | 102 | self.assertEqual(oldlen+1, newlen) |
|
103 | 103 | self.assertEqual(ip.user_ns['In'][-1],'1;') |
|
104 | 104 | |
|
105 | 105 | def test_magic_names_in_string(self): |
|
106 | 106 | ip.run_cell('a = """\n%exit\n"""') |
|
107 | 107 | self.assertEqual(ip.user_ns['a'], '\n%exit\n') |
|
108 | 108 | |
|
109 | def test_alias_crash(self): | |
|
110 | """Errors in prefilter can't crash IPython""" | |
|
111 | ip.run_cell('%alias parts echo first %s second %s') | |
|
112 | # capture stderr: | |
|
113 | save_err = io.stderr | |
|
114 | io.stderr = StringIO() | |
|
115 | ip.run_cell('parts 1') | |
|
116 | err = io.stderr.getvalue() | |
|
117 | io.stderr = save_err | |
|
118 | self.assertEqual(err.split(':')[0], 'ERROR') | |
|
119 | ||
|
120 | 109 | def test_trailing_newline(self): |
|
121 | 110 | """test that running !(command) does not raise a SyntaxError""" |
|
122 | 111 | ip.run_cell('!(true)\n', False) |
|
123 | 112 | ip.run_cell('!(true)\n\n\n', False) |
|
124 | 113 | |
|
125 | 114 | def test_gh_597(self): |
|
126 | 115 | """Pretty-printing lists of objects with non-ascii reprs may cause |
|
127 | 116 | problems.""" |
|
128 | 117 | class Spam(object): |
|
129 | 118 | def __repr__(self): |
|
130 | 119 | return "\xe9"*50 |
|
131 | 120 | import IPython.core.formatters |
|
132 | 121 | f = IPython.core.formatters.PlainTextFormatter() |
|
133 | 122 | f([Spam(),Spam()]) |
|
134 | 123 | |
|
135 | 124 | |
|
136 | 125 | def test_future_flags(self): |
|
137 | 126 | """Check that future flags are used for parsing code (gh-777)""" |
|
138 | 127 | ip.run_cell('from __future__ import print_function') |
|
139 | 128 | try: |
|
140 | 129 | ip.run_cell('prfunc_return_val = print(1,2, sep=" ")') |
|
141 | 130 | assert 'prfunc_return_val' in ip.user_ns |
|
142 | 131 | finally: |
|
143 | 132 | # Reset compiler flags so we don't mess up other tests. |
|
144 | 133 | ip.compile.reset_compiler_flags() |
|
145 | 134 | |
|
146 | 135 | def test_future_unicode(self): |
|
147 | 136 | """Check that unicode_literals is imported from __future__ (gh #786)""" |
|
148 | 137 | try: |
|
149 | 138 | ip.run_cell(u'byte_str = "a"') |
|
150 | 139 | assert isinstance(ip.user_ns['byte_str'], str) # string literals are byte strings by default |
|
151 | 140 | ip.run_cell('from __future__ import unicode_literals') |
|
152 | 141 | ip.run_cell(u'unicode_str = "a"') |
|
153 | 142 | assert isinstance(ip.user_ns['unicode_str'], unicode) # strings literals are now unicode |
|
154 | 143 | finally: |
|
155 | 144 | # Reset compiler flags so we don't mess up other tests. |
|
156 | 145 | ip.compile.reset_compiler_flags() |
|
157 | 146 | |
|
158 | 147 | def test_can_pickle(self): |
|
159 | 148 | "Can we pickle objects defined interactively (GH-29)" |
|
160 | 149 | ip = get_ipython() |
|
161 | 150 | ip.reset() |
|
162 | 151 | ip.run_cell(("class Mylist(list):\n" |
|
163 | 152 | " def __init__(self,x=[]):\n" |
|
164 | 153 | " list.__init__(self,x)")) |
|
165 | 154 | ip.run_cell("w=Mylist([1,2,3])") |
|
166 | 155 | |
|
167 | 156 | from cPickle import dumps |
|
168 | 157 | |
|
169 | 158 | # We need to swap in our main module - this is only necessary |
|
170 | 159 | # inside the test framework, because IPython puts the interactive module |
|
171 | 160 | # in place (but the test framework undoes this). |
|
172 | 161 | _main = sys.modules['__main__'] |
|
173 | 162 | sys.modules['__main__'] = ip.user_module |
|
174 | 163 | try: |
|
175 | 164 | res = dumps(ip.user_ns["w"]) |
|
176 | 165 | finally: |
|
177 | 166 | sys.modules['__main__'] = _main |
|
178 | 167 | self.assertTrue(isinstance(res, bytes)) |
|
179 | 168 | |
|
180 | 169 | def test_global_ns(self): |
|
181 | 170 | "Code in functions must be able to access variables outside them." |
|
182 | 171 | ip = get_ipython() |
|
183 | 172 | ip.run_cell("a = 10") |
|
184 | 173 | ip.run_cell(("def f(x):\n" |
|
185 | 174 | " return x + a")) |
|
186 | 175 | ip.run_cell("b = f(12)") |
|
187 | 176 | self.assertEqual(ip.user_ns["b"], 22) |
|
188 | 177 | |
|
189 | 178 | def test_bad_custom_tb(self): |
|
190 | 179 | """Check that InteractiveShell is protected from bad custom exception handlers""" |
|
191 | 180 | from IPython.utils import io |
|
192 | 181 | save_stderr = io.stderr |
|
193 | 182 | try: |
|
194 | 183 | # capture stderr |
|
195 | 184 | io.stderr = StringIO() |
|
196 | 185 | ip.set_custom_exc((IOError,), lambda etype,value,tb: 1/0) |
|
197 | 186 | self.assertEqual(ip.custom_exceptions, (IOError,)) |
|
198 | 187 | ip.run_cell(u'raise IOError("foo")') |
|
199 | 188 | self.assertEqual(ip.custom_exceptions, ()) |
|
200 | 189 | self.assertTrue("Custom TB Handler failed" in io.stderr.getvalue()) |
|
201 | 190 | finally: |
|
202 | 191 | io.stderr = save_stderr |
|
203 | 192 | |
|
204 | 193 | def test_bad_custom_tb_return(self): |
|
205 | 194 | """Check that InteractiveShell is protected from bad return types in custom exception handlers""" |
|
206 | 195 | from IPython.utils import io |
|
207 | 196 | save_stderr = io.stderr |
|
208 | 197 | try: |
|
209 | 198 | # capture stderr |
|
210 | 199 | io.stderr = StringIO() |
|
211 | 200 | ip.set_custom_exc((NameError,),lambda etype,value,tb, tb_offset=None: 1) |
|
212 | 201 | self.assertEqual(ip.custom_exceptions, (NameError,)) |
|
213 | 202 | ip.run_cell(u'a=abracadabra') |
|
214 | 203 | self.assertEqual(ip.custom_exceptions, ()) |
|
215 | 204 | self.assertTrue("Custom TB Handler failed" in io.stderr.getvalue()) |
|
216 | 205 | finally: |
|
217 | 206 | io.stderr = save_stderr |
|
218 | 207 | |
|
219 | 208 | def test_drop_by_id(self): |
|
220 | 209 | myvars = {"a":object(), "b":object(), "c": object()} |
|
221 | 210 | ip.push(myvars, interactive=False) |
|
222 | 211 | for name in myvars: |
|
223 | 212 | assert name in ip.user_ns, name |
|
224 | 213 | assert name in ip.user_ns_hidden, name |
|
225 | 214 | ip.user_ns['b'] = 12 |
|
226 | 215 | ip.drop_by_id(myvars) |
|
227 | 216 | for name in ["a", "c"]: |
|
228 | 217 | assert name not in ip.user_ns, name |
|
229 | 218 | assert name not in ip.user_ns_hidden, name |
|
230 | 219 | assert ip.user_ns['b'] == 12 |
|
231 | 220 | ip.reset() |
|
232 | 221 | |
|
233 | 222 | def test_var_expand(self): |
|
234 | 223 | ip.user_ns['f'] = u'Ca\xf1o' |
|
235 | 224 | self.assertEqual(ip.var_expand(u'echo $f'), u'echo Ca\xf1o') |
|
236 | 225 | self.assertEqual(ip.var_expand(u'echo {f}'), u'echo Ca\xf1o') |
|
237 | 226 | self.assertEqual(ip.var_expand(u'echo {f[:-1]}'), u'echo Ca\xf1') |
|
238 | 227 | self.assertEqual(ip.var_expand(u'echo {1*2}'), u'echo 2') |
|
239 | 228 | |
|
240 | 229 | ip.user_ns['f'] = b'Ca\xc3\xb1o' |
|
241 | 230 | # This should not raise any exception: |
|
242 | 231 | ip.var_expand(u'echo $f') |
|
243 | 232 | |
|
244 | 233 | def test_var_expand_local(self): |
|
245 | 234 | """Test local variable expansion in !system and %magic calls""" |
|
246 | 235 | # !system |
|
247 | 236 | ip.run_cell('def test():\n' |
|
248 | 237 | ' lvar = "ttt"\n' |
|
249 | 238 | ' ret = !echo {lvar}\n' |
|
250 | 239 | ' return ret[0]\n') |
|
251 | 240 | res = ip.user_ns['test']() |
|
252 | 241 | nt.assert_in('ttt', res) |
|
253 | 242 | |
|
254 | 243 | # %magic |
|
255 | 244 | ip.run_cell('def makemacro():\n' |
|
256 | 245 | ' macroname = "macro_var_expand_locals"\n' |
|
257 | 246 | ' %macro {macroname} codestr\n') |
|
258 | 247 | ip.user_ns['codestr'] = "str(12)" |
|
259 | 248 | ip.run_cell('makemacro()') |
|
260 | 249 | nt.assert_in('macro_var_expand_locals', ip.user_ns) |
|
261 | 250 | |
|
262 | 251 | def test_var_expand_self(self): |
|
263 | 252 | """Test variable expansion with the name 'self', which was failing. |
|
264 | 253 | |
|
265 | 254 | See https://github.com/ipython/ipython/issues/1878#issuecomment-7698218 |
|
266 | 255 | """ |
|
267 | 256 | ip.run_cell('class cTest:\n' |
|
268 | 257 | ' classvar="see me"\n' |
|
269 | 258 | ' def test(self):\n' |
|
270 | 259 | ' res = !echo Variable: {self.classvar}\n' |
|
271 | 260 | ' return res[0]\n') |
|
272 | 261 | nt.assert_in('see me', ip.user_ns['cTest']().test()) |
|
273 | 262 | |
|
274 | 263 | def test_bad_var_expand(self): |
|
275 | 264 | """var_expand on invalid formats shouldn't raise""" |
|
276 | 265 | # SyntaxError |
|
277 | 266 | self.assertEqual(ip.var_expand(u"{'a':5}"), u"{'a':5}") |
|
278 | 267 | # NameError |
|
279 | 268 | self.assertEqual(ip.var_expand(u"{asdf}"), u"{asdf}") |
|
280 | 269 | # ZeroDivisionError |
|
281 | 270 | self.assertEqual(ip.var_expand(u"{1/0}"), u"{1/0}") |
|
282 | 271 | |
|
283 | 272 | def test_silent_nopostexec(self): |
|
284 | 273 | """run_cell(silent=True) doesn't invoke post-exec funcs""" |
|
285 | 274 | d = dict(called=False) |
|
286 | 275 | def set_called(): |
|
287 | 276 | d['called'] = True |
|
288 | 277 | |
|
289 | 278 | ip.register_post_execute(set_called) |
|
290 | 279 | ip.run_cell("1", silent=True) |
|
291 | 280 | self.assertFalse(d['called']) |
|
292 | 281 | # double-check that non-silent exec did what we expected |
|
293 | 282 | # silent to avoid |
|
294 | 283 | ip.run_cell("1") |
|
295 | 284 | self.assertTrue(d['called']) |
|
296 | 285 | # remove post-exec |
|
297 | 286 | ip._post_execute.pop(set_called) |
|
298 | 287 | |
|
299 | 288 | def test_silent_noadvance(self): |
|
300 | 289 | """run_cell(silent=True) doesn't advance execution_count""" |
|
301 | 290 | ec = ip.execution_count |
|
302 | 291 | # silent should force store_history=False |
|
303 | 292 | ip.run_cell("1", store_history=True, silent=True) |
|
304 | 293 | |
|
305 | 294 | self.assertEqual(ec, ip.execution_count) |
|
306 | 295 | # double-check that non-silent exec did what we expected |
|
307 | 296 | # silent to avoid |
|
308 | 297 | ip.run_cell("1", store_history=True) |
|
309 | 298 | self.assertEqual(ec+1, ip.execution_count) |
|
310 | 299 | |
|
311 | 300 | def test_silent_nodisplayhook(self): |
|
312 | 301 | """run_cell(silent=True) doesn't trigger displayhook""" |
|
313 | 302 | d = dict(called=False) |
|
314 | 303 | |
|
315 | 304 | trap = ip.display_trap |
|
316 | 305 | save_hook = trap.hook |
|
317 | 306 | |
|
318 | 307 | def failing_hook(*args, **kwargs): |
|
319 | 308 | d['called'] = True |
|
320 | 309 | |
|
321 | 310 | try: |
|
322 | 311 | trap.hook = failing_hook |
|
323 | 312 | ip.run_cell("1", silent=True) |
|
324 | 313 | self.assertFalse(d['called']) |
|
325 | 314 | # double-check that non-silent exec did what we expected |
|
326 | 315 | # silent to avoid |
|
327 | 316 | ip.run_cell("1") |
|
328 | 317 | self.assertTrue(d['called']) |
|
329 | 318 | finally: |
|
330 | 319 | trap.hook = save_hook |
|
331 | 320 | |
|
332 | 321 | @skipif(sys.version_info[0] >= 3, "softspace removed in py3") |
|
333 | 322 | def test_print_softspace(self): |
|
334 | 323 | """Verify that softspace is handled correctly when executing multiple |
|
335 | 324 | statements. |
|
336 | 325 | |
|
337 | 326 | In [1]: print 1; print 2 |
|
338 | 327 | 1 |
|
339 | 328 | 2 |
|
340 | 329 | |
|
341 | 330 | In [2]: print 1,; print 2 |
|
342 | 331 | 1 2 |
|
343 | 332 | """ |
|
344 | 333 | |
|
345 | 334 | def test_ofind_line_magic(self): |
|
346 | 335 | from IPython.core.magic import register_line_magic |
|
347 | 336 | |
|
348 | 337 | @register_line_magic |
|
349 | 338 | def lmagic(line): |
|
350 | 339 | "A line magic" |
|
351 | 340 | |
|
352 | 341 | # Get info on line magic |
|
353 | 342 | lfind = ip._ofind('lmagic') |
|
354 | 343 | info = dict(found=True, isalias=False, ismagic=True, |
|
355 | 344 | namespace = 'IPython internal', obj= lmagic.__wrapped__, |
|
356 | 345 | parent = None) |
|
357 | 346 | nt.assert_equal(lfind, info) |
|
358 | 347 | |
|
359 | 348 | def test_ofind_cell_magic(self): |
|
360 | 349 | from IPython.core.magic import register_cell_magic |
|
361 | 350 | |
|
362 | 351 | @register_cell_magic |
|
363 | 352 | def cmagic(line, cell): |
|
364 | 353 | "A cell magic" |
|
365 | 354 | |
|
366 | 355 | # Get info on cell magic |
|
367 | 356 | find = ip._ofind('cmagic') |
|
368 | 357 | info = dict(found=True, isalias=False, ismagic=True, |
|
369 | 358 | namespace = 'IPython internal', obj= cmagic.__wrapped__, |
|
370 | 359 | parent = None) |
|
371 | 360 | nt.assert_equal(find, info) |
|
372 | 361 | |
|
373 | 362 | def test_custom_exception(self): |
|
374 | 363 | called = [] |
|
375 | 364 | def my_handler(shell, etype, value, tb, tb_offset=None): |
|
376 | 365 | called.append(etype) |
|
377 | 366 | shell.showtraceback((etype, value, tb), tb_offset=tb_offset) |
|
378 | 367 | |
|
379 | 368 | ip.set_custom_exc((ValueError,), my_handler) |
|
380 | 369 | try: |
|
381 | 370 | ip.run_cell("raise ValueError('test')") |
|
382 | 371 | # Check that this was called, and only once. |
|
383 | 372 | self.assertEqual(called, [ValueError]) |
|
384 | 373 | finally: |
|
385 | 374 | # Reset the custom exception hook |
|
386 | 375 | ip.set_custom_exc((), None) |
|
387 | 376 | |
|
388 | 377 | @skipif(sys.version_info[0] >= 3, "no differences with __future__ in py3") |
|
389 | 378 | def test_future_environment(self): |
|
390 | 379 | "Can we run code with & without the shell's __future__ imports?" |
|
391 | 380 | ip.run_cell("from __future__ import division") |
|
392 | 381 | ip.run_cell("a = 1/2", shell_futures=True) |
|
393 | 382 | self.assertEqual(ip.user_ns['a'], 0.5) |
|
394 | 383 | ip.run_cell("b = 1/2", shell_futures=False) |
|
395 | 384 | self.assertEqual(ip.user_ns['b'], 0) |
|
396 | 385 | |
|
397 | 386 | ip.compile.reset_compiler_flags() |
|
398 | 387 | # This shouldn't leak to the shell's compiler |
|
399 | 388 | ip.run_cell("from __future__ import division \nc=1/2", shell_futures=False) |
|
400 | 389 | self.assertEqual(ip.user_ns['c'], 0.5) |
|
401 | 390 | ip.run_cell("d = 1/2", shell_futures=True) |
|
402 | 391 | self.assertEqual(ip.user_ns['d'], 0) |
|
403 | 392 | |
|
404 | 393 | |
|
405 | 394 | class TestSafeExecfileNonAsciiPath(unittest.TestCase): |
|
406 | 395 | |
|
407 | 396 | @onlyif_unicode_paths |
|
408 | 397 | def setUp(self): |
|
409 | 398 | self.BASETESTDIR = tempfile.mkdtemp() |
|
410 | 399 | self.TESTDIR = join(self.BASETESTDIR, u"Γ₯Àâ") |
|
411 | 400 | os.mkdir(self.TESTDIR) |
|
412 | 401 | with open(join(self.TESTDIR, u"Γ₯Àâtestscript.py"), "w") as sfile: |
|
413 | 402 | sfile.write("pass\n") |
|
414 | 403 | self.oldpath = os.getcwdu() |
|
415 | 404 | os.chdir(self.TESTDIR) |
|
416 | 405 | self.fname = u"Γ₯Àâtestscript.py" |
|
417 | 406 | |
|
418 | 407 | def tearDown(self): |
|
419 | 408 | os.chdir(self.oldpath) |
|
420 | 409 | shutil.rmtree(self.BASETESTDIR) |
|
421 | 410 | |
|
422 | 411 | @onlyif_unicode_paths |
|
423 | 412 | def test_1(self): |
|
424 | 413 | """Test safe_execfile with non-ascii path |
|
425 | 414 | """ |
|
426 | 415 | ip.safe_execfile(self.fname, {}, raise_exceptions=True) |
|
427 | 416 | |
|
428 | 417 | |
|
429 | 418 | class TestSystemRaw(unittest.TestCase): |
|
430 | 419 | @onlyif_unicode_paths |
|
431 | 420 | def test_1(self): |
|
432 | 421 | """Test system_raw with non-ascii cmd |
|
433 | 422 | """ |
|
434 | 423 | cmd = ur'''python -c "'Γ₯Àâ'" ''' |
|
435 | 424 | ip.system_raw(cmd) |
|
436 | 425 | |
|
437 | 426 | def test_exit_code(self): |
|
438 | 427 | """Test that the exit code is parsed correctly.""" |
|
439 | 428 | ip.system_raw('exit 1') |
|
440 | 429 | self.assertEqual(ip.user_ns['_exit_code'], 1) |
|
441 | 430 | |
|
442 | 431 | class TestModules(unittest.TestCase, tt.TempFileMixin): |
|
443 | 432 | def test_extraneous_loads(self): |
|
444 | 433 | """Test we're not loading modules on startup that we shouldn't. |
|
445 | 434 | """ |
|
446 | 435 | self.mktmp("import sys\n" |
|
447 | 436 | "print('numpy' in sys.modules)\n" |
|
448 | 437 | "print('IPython.parallel' in sys.modules)\n" |
|
449 | 438 | "print('IPython.kernel.zmq' in sys.modules)\n" |
|
450 | 439 | ) |
|
451 | 440 | out = "False\nFalse\nFalse\n" |
|
452 | 441 | tt.ipexec_validate(self.fname, out) |
|
453 | 442 | |
|
454 | 443 | class Negator(ast.NodeTransformer): |
|
455 | 444 | """Negates all number literals in an AST.""" |
|
456 | 445 | def visit_Num(self, node): |
|
457 | 446 | node.n = -node.n |
|
458 | 447 | return node |
|
459 | 448 | |
|
460 | 449 | class TestAstTransform(unittest.TestCase): |
|
461 | 450 | def setUp(self): |
|
462 | 451 | self.negator = Negator() |
|
463 | 452 | ip.ast_transformers.append(self.negator) |
|
464 | 453 | |
|
465 | 454 | def tearDown(self): |
|
466 | 455 | ip.ast_transformers.remove(self.negator) |
|
467 | 456 | |
|
468 | 457 | def test_run_cell(self): |
|
469 | 458 | with tt.AssertPrints('-34'): |
|
470 | 459 | ip.run_cell('print (12 + 22)') |
|
471 | 460 | |
|
472 | 461 | # A named reference to a number shouldn't be transformed. |
|
473 | 462 | ip.user_ns['n'] = 55 |
|
474 | 463 | with tt.AssertNotPrints('-55'): |
|
475 | 464 | ip.run_cell('print (n)') |
|
476 | 465 | |
|
477 | 466 | def test_timeit(self): |
|
478 | 467 | called = set() |
|
479 | 468 | def f(x): |
|
480 | 469 | called.add(x) |
|
481 | 470 | ip.push({'f':f}) |
|
482 | 471 | |
|
483 | 472 | with tt.AssertPrints("best of "): |
|
484 | 473 | ip.run_line_magic("timeit", "-n1 f(1)") |
|
485 | 474 | self.assertEqual(called, set([-1])) |
|
486 | 475 | called.clear() |
|
487 | 476 | |
|
488 | 477 | with tt.AssertPrints("best of "): |
|
489 | 478 | ip.run_cell_magic("timeit", "-n1 f(2)", "f(3)") |
|
490 | 479 | self.assertEqual(called, set([-2, -3])) |
|
491 | 480 | |
|
492 | 481 | def test_time(self): |
|
493 | 482 | called = [] |
|
494 | 483 | def f(x): |
|
495 | 484 | called.append(x) |
|
496 | 485 | ip.push({'f':f}) |
|
497 | 486 | |
|
498 | 487 | # Test with an expression |
|
499 | 488 | with tt.AssertPrints("Wall time: "): |
|
500 | 489 | ip.run_line_magic("time", "f(5+9)") |
|
501 | 490 | self.assertEqual(called, [-14]) |
|
502 | 491 | called[:] = [] |
|
503 | 492 | |
|
504 | 493 | # Test with a statement (different code path) |
|
505 | 494 | with tt.AssertPrints("Wall time: "): |
|
506 | 495 | ip.run_line_magic("time", "a = f(-3 + -2)") |
|
507 | 496 | self.assertEqual(called, [5]) |
|
508 | 497 | |
|
509 | 498 | def test_macro(self): |
|
510 | 499 | ip.push({'a':10}) |
|
511 | 500 | # The AST transformation makes this do a+=-1 |
|
512 | 501 | ip.define_macro("amacro", "a+=1\nprint(a)") |
|
513 | 502 | |
|
514 | 503 | with tt.AssertPrints("9"): |
|
515 | 504 | ip.run_cell("amacro") |
|
516 | 505 | with tt.AssertPrints("8"): |
|
517 | 506 | ip.run_cell("amacro") |
|
518 | 507 | |
|
519 | 508 | class IntegerWrapper(ast.NodeTransformer): |
|
520 | 509 | """Wraps all integers in a call to Integer()""" |
|
521 | 510 | def visit_Num(self, node): |
|
522 | 511 | if isinstance(node.n, int): |
|
523 | 512 | return ast.Call(func=ast.Name(id='Integer', ctx=ast.Load()), |
|
524 | 513 | args=[node], keywords=[]) |
|
525 | 514 | return node |
|
526 | 515 | |
|
527 | 516 | class TestAstTransform2(unittest.TestCase): |
|
528 | 517 | def setUp(self): |
|
529 | 518 | self.intwrapper = IntegerWrapper() |
|
530 | 519 | ip.ast_transformers.append(self.intwrapper) |
|
531 | 520 | |
|
532 | 521 | self.calls = [] |
|
533 | 522 | def Integer(*args): |
|
534 | 523 | self.calls.append(args) |
|
535 | 524 | return args |
|
536 | 525 | ip.push({"Integer": Integer}) |
|
537 | 526 | |
|
538 | 527 | def tearDown(self): |
|
539 | 528 | ip.ast_transformers.remove(self.intwrapper) |
|
540 | 529 | del ip.user_ns['Integer'] |
|
541 | 530 | |
|
542 | 531 | def test_run_cell(self): |
|
543 | 532 | ip.run_cell("n = 2") |
|
544 | 533 | self.assertEqual(self.calls, [(2,)]) |
|
545 | 534 | |
|
546 | 535 | # This shouldn't throw an error |
|
547 | 536 | ip.run_cell("o = 2.0") |
|
548 | 537 | self.assertEqual(ip.user_ns['o'], 2.0) |
|
549 | 538 | |
|
550 | 539 | def test_timeit(self): |
|
551 | 540 | called = set() |
|
552 | 541 | def f(x): |
|
553 | 542 | called.add(x) |
|
554 | 543 | ip.push({'f':f}) |
|
555 | 544 | |
|
556 | 545 | with tt.AssertPrints("best of "): |
|
557 | 546 | ip.run_line_magic("timeit", "-n1 f(1)") |
|
558 | 547 | self.assertEqual(called, set([(1,)])) |
|
559 | 548 | called.clear() |
|
560 | 549 | |
|
561 | 550 | with tt.AssertPrints("best of "): |
|
562 | 551 | ip.run_cell_magic("timeit", "-n1 f(2)", "f(3)") |
|
563 | 552 | self.assertEqual(called, set([(2,), (3,)])) |
|
564 | 553 | |
|
565 | 554 | class ErrorTransformer(ast.NodeTransformer): |
|
566 | 555 | """Throws an error when it sees a number.""" |
|
567 | 556 | def visit_Num(self): |
|
568 | 557 | raise ValueError("test") |
|
569 | 558 | |
|
570 | 559 | class TestAstTransformError(unittest.TestCase): |
|
571 | 560 | def test_unregistering(self): |
|
572 | 561 | err_transformer = ErrorTransformer() |
|
573 | 562 | ip.ast_transformers.append(err_transformer) |
|
574 | 563 | |
|
575 | 564 | with tt.AssertPrints("unregister", channel='stderr'): |
|
576 | 565 | ip.run_cell("1 + 2") |
|
577 | 566 | |
|
578 | 567 | # This should have been removed. |
|
579 | 568 | nt.assert_not_in(err_transformer, ip.ast_transformers) |
|
580 | 569 | |
|
581 | 570 | def test__IPYTHON__(): |
|
582 | 571 | # This shouldn't raise a NameError, that's all |
|
583 | 572 | __IPYTHON__ |
|
584 | 573 | |
|
585 | 574 | |
|
586 | 575 | class DummyRepr(object): |
|
587 | 576 | def __repr__(self): |
|
588 | 577 | return "DummyRepr" |
|
589 | 578 | |
|
590 | 579 | def _repr_html_(self): |
|
591 | 580 | return "<b>dummy</b>" |
|
592 | 581 | |
|
593 | 582 | def _repr_javascript_(self): |
|
594 | 583 | return "console.log('hi');", {'key': 'value'} |
|
595 | 584 | |
|
596 | 585 | |
|
597 | 586 | def test_user_variables(): |
|
598 | 587 | # enable all formatters |
|
599 | 588 | ip.display_formatter.active_types = ip.display_formatter.format_types |
|
600 | 589 | |
|
601 | 590 | ip.user_ns['dummy'] = d = DummyRepr() |
|
602 | 591 | keys = set(['dummy', 'doesnotexist']) |
|
603 | 592 | r = ip.user_variables(keys) |
|
604 | 593 | |
|
605 | 594 | nt.assert_equal(keys, set(r.keys())) |
|
606 | 595 | dummy = r['dummy'] |
|
607 | 596 | nt.assert_equal(set(['status', 'data', 'metadata']), set(dummy.keys())) |
|
608 | 597 | nt.assert_equal(dummy['status'], 'ok') |
|
609 | 598 | data = dummy['data'] |
|
610 | 599 | metadata = dummy['metadata'] |
|
611 | 600 | nt.assert_equal(data.get('text/html'), d._repr_html_()) |
|
612 | 601 | js, jsmd = d._repr_javascript_() |
|
613 | 602 | nt.assert_equal(data.get('application/javascript'), js) |
|
614 | 603 | nt.assert_equal(metadata.get('application/javascript'), jsmd) |
|
615 | 604 | |
|
616 | 605 | dne = r['doesnotexist'] |
|
617 | 606 | nt.assert_equal(dne['status'], 'error') |
|
618 | 607 | nt.assert_equal(dne['ename'], 'KeyError') |
|
619 | 608 | |
|
620 | 609 | # back to text only |
|
621 | 610 | ip.display_formatter.active_types = ['text/plain'] |
|
622 | 611 | |
|
623 | 612 | def test_user_expression(): |
|
624 | 613 | # enable all formatters |
|
625 | 614 | ip.display_formatter.active_types = ip.display_formatter.format_types |
|
626 | 615 | query = { |
|
627 | 616 | 'a' : '1 + 2', |
|
628 | 617 | 'b' : '1/0', |
|
629 | 618 | } |
|
630 | 619 | r = ip.user_expressions(query) |
|
631 | 620 | import pprint |
|
632 | 621 | pprint.pprint(r) |
|
633 | 622 | nt.assert_equal(r.keys(), query.keys()) |
|
634 | 623 | a = r['a'] |
|
635 | 624 | nt.assert_equal(set(['status', 'data', 'metadata']), set(a.keys())) |
|
636 | 625 | nt.assert_equal(a['status'], 'ok') |
|
637 | 626 | data = a['data'] |
|
638 | 627 | metadata = a['metadata'] |
|
639 | 628 | nt.assert_equal(data.get('text/plain'), '3') |
|
640 | 629 | |
|
641 | 630 | b = r['b'] |
|
642 | 631 | nt.assert_equal(b['status'], 'error') |
|
643 | 632 | nt.assert_equal(b['ename'], 'ZeroDivisionError') |
|
644 | 633 | |
|
645 | 634 | # back to text only |
|
646 | 635 | ip.display_formatter.active_types = ['text/plain'] |
|
647 | 636 | |
|
648 | 637 | |
|
649 | 638 | |
|
650 | 639 | |
|
651 | 640 | |
|
652 | 641 |
@@ -1,895 +1,895 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Tests for various magic functions. |
|
3 | 3 | |
|
4 | 4 | Needs to be run by nose (to make ipython session available). |
|
5 | 5 | """ |
|
6 | 6 | from __future__ import absolute_import |
|
7 | 7 | |
|
8 | 8 | #----------------------------------------------------------------------------- |
|
9 | 9 | # Imports |
|
10 | 10 | #----------------------------------------------------------------------------- |
|
11 | 11 | |
|
12 | 12 | import io |
|
13 | 13 | import os |
|
14 | 14 | import sys |
|
15 | 15 | from StringIO import StringIO |
|
16 | 16 | from unittest import TestCase |
|
17 | 17 | |
|
18 | 18 | try: |
|
19 | 19 | from importlib import invalidate_caches # Required from Python 3.3 |
|
20 | 20 | except ImportError: |
|
21 | 21 | def invalidate_caches(): |
|
22 | 22 | pass |
|
23 | 23 | |
|
24 | 24 | import nose.tools as nt |
|
25 | 25 | |
|
26 | 26 | from IPython.core import magic |
|
27 | 27 | from IPython.core.magic import (Magics, magics_class, line_magic, |
|
28 | 28 | cell_magic, line_cell_magic, |
|
29 | 29 | register_line_magic, register_cell_magic, |
|
30 | 30 | register_line_cell_magic) |
|
31 | 31 | from IPython.core.magics import execution, script, code |
|
32 | 32 | from IPython.nbformat.v3.tests.nbexamples import nb0 |
|
33 | 33 | from IPython.nbformat import current |
|
34 | 34 | from IPython.testing import decorators as dec |
|
35 | 35 | from IPython.testing import tools as tt |
|
36 | 36 | from IPython.utils import py3compat |
|
37 | 37 | from IPython.utils.io import capture_output |
|
38 | 38 | from IPython.utils.tempdir import TemporaryDirectory |
|
39 | 39 | from IPython.utils.process import find_cmd |
|
40 | 40 | |
|
41 | 41 | #----------------------------------------------------------------------------- |
|
42 | 42 | # Test functions begin |
|
43 | 43 | #----------------------------------------------------------------------------- |
|
44 | 44 | |
|
45 | 45 | @magic.magics_class |
|
46 | 46 | class DummyMagics(magic.Magics): pass |
|
47 | 47 | |
|
48 | 48 | def test_rehashx(): |
|
49 | 49 | # clear up everything |
|
50 | 50 | _ip = get_ipython() |
|
51 |
_ip.alias_manager. |
|
|
51 | _ip.alias_manager.clear_aliases() | |
|
52 | 52 | del _ip.db['syscmdlist'] |
|
53 | 53 | |
|
54 | 54 | _ip.magic('rehashx') |
|
55 | 55 | # Practically ALL ipython development systems will have more than 10 aliases |
|
56 | 56 | |
|
57 |
nt.assert_true(len(_ip.alias_manager.alias |
|
|
58 |
for |
|
|
57 | nt.assert_true(len(_ip.alias_manager.aliases) > 10) | |
|
58 | for name, cmd in _ip.alias_manager.aliases: | |
|
59 | 59 | # we must strip dots from alias names |
|
60 |
nt.assert_not_in('.', |
|
|
60 | nt.assert_not_in('.', name) | |
|
61 | 61 | |
|
62 | 62 | # rehashx must fill up syscmdlist |
|
63 | 63 | scoms = _ip.db['syscmdlist'] |
|
64 | 64 | nt.assert_true(len(scoms) > 10) |
|
65 | 65 | |
|
66 | 66 | |
|
67 | 67 | def test_magic_parse_options(): |
|
68 | 68 | """Test that we don't mangle paths when parsing magic options.""" |
|
69 | 69 | ip = get_ipython() |
|
70 | 70 | path = 'c:\\x' |
|
71 | 71 | m = DummyMagics(ip) |
|
72 | 72 | opts = m.parse_options('-f %s' % path,'f:')[0] |
|
73 | 73 | # argv splitting is os-dependent |
|
74 | 74 | if os.name == 'posix': |
|
75 | 75 | expected = 'c:x' |
|
76 | 76 | else: |
|
77 | 77 | expected = path |
|
78 | 78 | nt.assert_equal(opts['f'], expected) |
|
79 | 79 | |
|
80 | 80 | def test_magic_parse_long_options(): |
|
81 | 81 | """Magic.parse_options can handle --foo=bar long options""" |
|
82 | 82 | ip = get_ipython() |
|
83 | 83 | m = DummyMagics(ip) |
|
84 | 84 | opts, _ = m.parse_options('--foo --bar=bubble', 'a', 'foo', 'bar=') |
|
85 | 85 | nt.assert_in('foo', opts) |
|
86 | 86 | nt.assert_in('bar', opts) |
|
87 | 87 | nt.assert_equal(opts['bar'], "bubble") |
|
88 | 88 | |
|
89 | 89 | |
|
90 | 90 | @dec.skip_without('sqlite3') |
|
91 | 91 | def doctest_hist_f(): |
|
92 | 92 | """Test %hist -f with temporary filename. |
|
93 | 93 | |
|
94 | 94 | In [9]: import tempfile |
|
95 | 95 | |
|
96 | 96 | In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-') |
|
97 | 97 | |
|
98 | 98 | In [11]: %hist -nl -f $tfile 3 |
|
99 | 99 | |
|
100 | 100 | In [13]: import os; os.unlink(tfile) |
|
101 | 101 | """ |
|
102 | 102 | |
|
103 | 103 | |
|
104 | 104 | @dec.skip_without('sqlite3') |
|
105 | 105 | def doctest_hist_r(): |
|
106 | 106 | """Test %hist -r |
|
107 | 107 | |
|
108 | 108 | XXX - This test is not recording the output correctly. For some reason, in |
|
109 | 109 | testing mode the raw history isn't getting populated. No idea why. |
|
110 | 110 | Disabling the output checking for now, though at least we do run it. |
|
111 | 111 | |
|
112 | 112 | In [1]: 'hist' in _ip.lsmagic() |
|
113 | 113 | Out[1]: True |
|
114 | 114 | |
|
115 | 115 | In [2]: x=1 |
|
116 | 116 | |
|
117 | 117 | In [3]: %hist -rl 2 |
|
118 | 118 | x=1 # random |
|
119 | 119 | %hist -r 2 |
|
120 | 120 | """ |
|
121 | 121 | |
|
122 | 122 | |
|
123 | 123 | @dec.skip_without('sqlite3') |
|
124 | 124 | def doctest_hist_op(): |
|
125 | 125 | """Test %hist -op |
|
126 | 126 | |
|
127 | 127 | In [1]: class b(float): |
|
128 | 128 | ...: pass |
|
129 | 129 | ...: |
|
130 | 130 | |
|
131 | 131 | In [2]: class s(object): |
|
132 | 132 | ...: def __str__(self): |
|
133 | 133 | ...: return 's' |
|
134 | 134 | ...: |
|
135 | 135 | |
|
136 | 136 | In [3]: |
|
137 | 137 | |
|
138 | 138 | In [4]: class r(b): |
|
139 | 139 | ...: def __repr__(self): |
|
140 | 140 | ...: return 'r' |
|
141 | 141 | ...: |
|
142 | 142 | |
|
143 | 143 | In [5]: class sr(s,r): pass |
|
144 | 144 | ...: |
|
145 | 145 | |
|
146 | 146 | In [6]: |
|
147 | 147 | |
|
148 | 148 | In [7]: bb=b() |
|
149 | 149 | |
|
150 | 150 | In [8]: ss=s() |
|
151 | 151 | |
|
152 | 152 | In [9]: rr=r() |
|
153 | 153 | |
|
154 | 154 | In [10]: ssrr=sr() |
|
155 | 155 | |
|
156 | 156 | In [11]: 4.5 |
|
157 | 157 | Out[11]: 4.5 |
|
158 | 158 | |
|
159 | 159 | In [12]: str(ss) |
|
160 | 160 | Out[12]: 's' |
|
161 | 161 | |
|
162 | 162 | In [13]: |
|
163 | 163 | |
|
164 | 164 | In [14]: %hist -op |
|
165 | 165 | >>> class b: |
|
166 | 166 | ... pass |
|
167 | 167 | ... |
|
168 | 168 | >>> class s(b): |
|
169 | 169 | ... def __str__(self): |
|
170 | 170 | ... return 's' |
|
171 | 171 | ... |
|
172 | 172 | >>> |
|
173 | 173 | >>> class r(b): |
|
174 | 174 | ... def __repr__(self): |
|
175 | 175 | ... return 'r' |
|
176 | 176 | ... |
|
177 | 177 | >>> class sr(s,r): pass |
|
178 | 178 | >>> |
|
179 | 179 | >>> bb=b() |
|
180 | 180 | >>> ss=s() |
|
181 | 181 | >>> rr=r() |
|
182 | 182 | >>> ssrr=sr() |
|
183 | 183 | >>> 4.5 |
|
184 | 184 | 4.5 |
|
185 | 185 | >>> str(ss) |
|
186 | 186 | 's' |
|
187 | 187 | >>> |
|
188 | 188 | """ |
|
189 | 189 | |
|
190 | 190 | |
|
191 | 191 | @dec.skip_without('sqlite3') |
|
192 | 192 | def test_macro(): |
|
193 | 193 | ip = get_ipython() |
|
194 | 194 | ip.history_manager.reset() # Clear any existing history. |
|
195 | 195 | cmds = ["a=1", "def b():\n return a**2", "print(a,b())"] |
|
196 | 196 | for i, cmd in enumerate(cmds, start=1): |
|
197 | 197 | ip.history_manager.store_inputs(i, cmd) |
|
198 | 198 | ip.magic("macro test 1-3") |
|
199 | 199 | nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n") |
|
200 | 200 | |
|
201 | 201 | # List macros |
|
202 | 202 | nt.assert_in("test", ip.magic("macro")) |
|
203 | 203 | |
|
204 | 204 | |
|
205 | 205 | @dec.skip_without('sqlite3') |
|
206 | 206 | def test_macro_run(): |
|
207 | 207 | """Test that we can run a multi-line macro successfully.""" |
|
208 | 208 | ip = get_ipython() |
|
209 | 209 | ip.history_manager.reset() |
|
210 | 210 | cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"), |
|
211 | 211 | "%macro test 2-3"] |
|
212 | 212 | for cmd in cmds: |
|
213 | 213 | ip.run_cell(cmd, store_history=True) |
|
214 | 214 | nt.assert_equal(ip.user_ns["test"].value, |
|
215 | 215 | py3compat.doctest_refactor_print("a+=1\nprint a\n")) |
|
216 | 216 | with tt.AssertPrints("12"): |
|
217 | 217 | ip.run_cell("test") |
|
218 | 218 | with tt.AssertPrints("13"): |
|
219 | 219 | ip.run_cell("test") |
|
220 | 220 | |
|
221 | 221 | |
|
222 | 222 | def test_magic_magic(): |
|
223 | 223 | """Test %magic""" |
|
224 | 224 | ip = get_ipython() |
|
225 | 225 | with capture_output() as captured: |
|
226 | 226 | ip.magic("magic") |
|
227 | 227 | |
|
228 | 228 | stdout = captured.stdout |
|
229 | 229 | nt.assert_in('%magic', stdout) |
|
230 | 230 | nt.assert_in('IPython', stdout) |
|
231 | 231 | nt.assert_in('Available', stdout) |
|
232 | 232 | |
|
233 | 233 | |
|
234 | 234 | @dec.skipif_not_numpy |
|
235 | 235 | def test_numpy_reset_array_undec(): |
|
236 | 236 | "Test '%reset array' functionality" |
|
237 | 237 | _ip.ex('import numpy as np') |
|
238 | 238 | _ip.ex('a = np.empty(2)') |
|
239 | 239 | nt.assert_in('a', _ip.user_ns) |
|
240 | 240 | _ip.magic('reset -f array') |
|
241 | 241 | nt.assert_not_in('a', _ip.user_ns) |
|
242 | 242 | |
|
243 | 243 | def test_reset_out(): |
|
244 | 244 | "Test '%reset out' magic" |
|
245 | 245 | _ip.run_cell("parrot = 'dead'", store_history=True) |
|
246 | 246 | # test '%reset -f out', make an Out prompt |
|
247 | 247 | _ip.run_cell("parrot", store_history=True) |
|
248 | 248 | nt.assert_true('dead' in [_ip.user_ns[x] for x in '_','__','___']) |
|
249 | 249 | _ip.magic('reset -f out') |
|
250 | 250 | nt.assert_false('dead' in [_ip.user_ns[x] for x in '_','__','___']) |
|
251 | 251 | nt.assert_equal(len(_ip.user_ns['Out']), 0) |
|
252 | 252 | |
|
253 | 253 | def test_reset_in(): |
|
254 | 254 | "Test '%reset in' magic" |
|
255 | 255 | # test '%reset -f in' |
|
256 | 256 | _ip.run_cell("parrot", store_history=True) |
|
257 | 257 | nt.assert_true('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii']) |
|
258 | 258 | _ip.magic('%reset -f in') |
|
259 | 259 | nt.assert_false('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii']) |
|
260 | 260 | nt.assert_equal(len(set(_ip.user_ns['In'])), 1) |
|
261 | 261 | |
|
262 | 262 | def test_reset_dhist(): |
|
263 | 263 | "Test '%reset dhist' magic" |
|
264 | 264 | _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing |
|
265 | 265 | _ip.magic('cd ' + os.path.dirname(nt.__file__)) |
|
266 | 266 | _ip.magic('cd -') |
|
267 | 267 | nt.assert_true(len(_ip.user_ns['_dh']) > 0) |
|
268 | 268 | _ip.magic('reset -f dhist') |
|
269 | 269 | nt.assert_equal(len(_ip.user_ns['_dh']), 0) |
|
270 | 270 | _ip.run_cell("_dh = [d for d in tmp]") #restore |
|
271 | 271 | |
|
272 | 272 | def test_reset_in_length(): |
|
273 | 273 | "Test that '%reset in' preserves In[] length" |
|
274 | 274 | _ip.run_cell("print 'foo'") |
|
275 | 275 | _ip.run_cell("reset -f in") |
|
276 | 276 | nt.assert_equal(len(_ip.user_ns['In']), _ip.displayhook.prompt_count+1) |
|
277 | 277 | |
|
278 | 278 | def test_tb_syntaxerror(): |
|
279 | 279 | """test %tb after a SyntaxError""" |
|
280 | 280 | ip = get_ipython() |
|
281 | 281 | ip.run_cell("for") |
|
282 | 282 | |
|
283 | 283 | # trap and validate stdout |
|
284 | 284 | save_stdout = sys.stdout |
|
285 | 285 | try: |
|
286 | 286 | sys.stdout = StringIO() |
|
287 | 287 | ip.run_cell("%tb") |
|
288 | 288 | out = sys.stdout.getvalue() |
|
289 | 289 | finally: |
|
290 | 290 | sys.stdout = save_stdout |
|
291 | 291 | # trim output, and only check the last line |
|
292 | 292 | last_line = out.rstrip().splitlines()[-1].strip() |
|
293 | 293 | nt.assert_equal(last_line, "SyntaxError: invalid syntax") |
|
294 | 294 | |
|
295 | 295 | |
|
296 | 296 | def test_time(): |
|
297 | 297 | ip = get_ipython() |
|
298 | 298 | |
|
299 | 299 | with tt.AssertPrints("Wall time: "): |
|
300 | 300 | ip.run_cell("%time None") |
|
301 | 301 | |
|
302 | 302 | ip.run_cell("def f(kmjy):\n" |
|
303 | 303 | " %time print (2*kmjy)") |
|
304 | 304 | |
|
305 | 305 | with tt.AssertPrints("Wall time: "): |
|
306 | 306 | with tt.AssertPrints("hihi", suppress=False): |
|
307 | 307 | ip.run_cell("f('hi')") |
|
308 | 308 | |
|
309 | 309 | |
|
310 | 310 | @dec.skip_win32 |
|
311 | 311 | def test_time2(): |
|
312 | 312 | ip = get_ipython() |
|
313 | 313 | |
|
314 | 314 | with tt.AssertPrints("CPU times: user "): |
|
315 | 315 | ip.run_cell("%time None") |
|
316 | 316 | |
|
317 | 317 | def test_time3(): |
|
318 | 318 | """Erroneous magic function calls, issue gh-3334""" |
|
319 | 319 | ip = get_ipython() |
|
320 | 320 | ip.user_ns.pop('run', None) |
|
321 | 321 | |
|
322 | 322 | with tt.AssertNotPrints("not found", channel='stderr'): |
|
323 | 323 | ip.run_cell("%%time\n" |
|
324 | 324 | "run = 0\n" |
|
325 | 325 | "run += 1") |
|
326 | 326 | |
|
327 | 327 | def test_doctest_mode(): |
|
328 | 328 | "Toggle doctest_mode twice, it should be a no-op and run without error" |
|
329 | 329 | _ip.magic('doctest_mode') |
|
330 | 330 | _ip.magic('doctest_mode') |
|
331 | 331 | |
|
332 | 332 | |
|
333 | 333 | def test_parse_options(): |
|
334 | 334 | """Tests for basic options parsing in magics.""" |
|
335 | 335 | # These are only the most minimal of tests, more should be added later. At |
|
336 | 336 | # the very least we check that basic text/unicode calls work OK. |
|
337 | 337 | m = DummyMagics(_ip) |
|
338 | 338 | nt.assert_equal(m.parse_options('foo', '')[1], 'foo') |
|
339 | 339 | nt.assert_equal(m.parse_options(u'foo', '')[1], u'foo') |
|
340 | 340 | |
|
341 | 341 | |
|
342 | 342 | def test_dirops(): |
|
343 | 343 | """Test various directory handling operations.""" |
|
344 | 344 | # curpath = lambda :os.path.splitdrive(os.getcwdu())[1].replace('\\','/') |
|
345 | 345 | curpath = os.getcwdu |
|
346 | 346 | startdir = os.getcwdu() |
|
347 | 347 | ipdir = os.path.realpath(_ip.ipython_dir) |
|
348 | 348 | try: |
|
349 | 349 | _ip.magic('cd "%s"' % ipdir) |
|
350 | 350 | nt.assert_equal(curpath(), ipdir) |
|
351 | 351 | _ip.magic('cd -') |
|
352 | 352 | nt.assert_equal(curpath(), startdir) |
|
353 | 353 | _ip.magic('pushd "%s"' % ipdir) |
|
354 | 354 | nt.assert_equal(curpath(), ipdir) |
|
355 | 355 | _ip.magic('popd') |
|
356 | 356 | nt.assert_equal(curpath(), startdir) |
|
357 | 357 | finally: |
|
358 | 358 | os.chdir(startdir) |
|
359 | 359 | |
|
360 | 360 | |
|
361 | 361 | def test_xmode(): |
|
362 | 362 | # Calling xmode three times should be a no-op |
|
363 | 363 | xmode = _ip.InteractiveTB.mode |
|
364 | 364 | for i in range(3): |
|
365 | 365 | _ip.magic("xmode") |
|
366 | 366 | nt.assert_equal(_ip.InteractiveTB.mode, xmode) |
|
367 | 367 | |
|
368 | 368 | def test_reset_hard(): |
|
369 | 369 | monitor = [] |
|
370 | 370 | class A(object): |
|
371 | 371 | def __del__(self): |
|
372 | 372 | monitor.append(1) |
|
373 | 373 | def __repr__(self): |
|
374 | 374 | return "<A instance>" |
|
375 | 375 | |
|
376 | 376 | _ip.user_ns["a"] = A() |
|
377 | 377 | _ip.run_cell("a") |
|
378 | 378 | |
|
379 | 379 | nt.assert_equal(monitor, []) |
|
380 | 380 | _ip.magic("reset -f") |
|
381 | 381 | nt.assert_equal(monitor, [1]) |
|
382 | 382 | |
|
383 | 383 | class TestXdel(tt.TempFileMixin): |
|
384 | 384 | def test_xdel(self): |
|
385 | 385 | """Test that references from %run are cleared by xdel.""" |
|
386 | 386 | src = ("class A(object):\n" |
|
387 | 387 | " monitor = []\n" |
|
388 | 388 | " def __del__(self):\n" |
|
389 | 389 | " self.monitor.append(1)\n" |
|
390 | 390 | "a = A()\n") |
|
391 | 391 | self.mktmp(src) |
|
392 | 392 | # %run creates some hidden references... |
|
393 | 393 | _ip.magic("run %s" % self.fname) |
|
394 | 394 | # ... as does the displayhook. |
|
395 | 395 | _ip.run_cell("a") |
|
396 | 396 | |
|
397 | 397 | monitor = _ip.user_ns["A"].monitor |
|
398 | 398 | nt.assert_equal(monitor, []) |
|
399 | 399 | |
|
400 | 400 | _ip.magic("xdel a") |
|
401 | 401 | |
|
402 | 402 | # Check that a's __del__ method has been called. |
|
403 | 403 | nt.assert_equal(monitor, [1]) |
|
404 | 404 | |
|
405 | 405 | def doctest_who(): |
|
406 | 406 | """doctest for %who |
|
407 | 407 | |
|
408 | 408 | In [1]: %reset -f |
|
409 | 409 | |
|
410 | 410 | In [2]: alpha = 123 |
|
411 | 411 | |
|
412 | 412 | In [3]: beta = 'beta' |
|
413 | 413 | |
|
414 | 414 | In [4]: %who int |
|
415 | 415 | alpha |
|
416 | 416 | |
|
417 | 417 | In [5]: %who str |
|
418 | 418 | beta |
|
419 | 419 | |
|
420 | 420 | In [6]: %whos |
|
421 | 421 | Variable Type Data/Info |
|
422 | 422 | ---------------------------- |
|
423 | 423 | alpha int 123 |
|
424 | 424 | beta str beta |
|
425 | 425 | |
|
426 | 426 | In [7]: %who_ls |
|
427 | 427 | Out[7]: ['alpha', 'beta'] |
|
428 | 428 | """ |
|
429 | 429 | |
|
430 | 430 | def test_whos(): |
|
431 | 431 | """Check that whos is protected against objects where repr() fails.""" |
|
432 | 432 | class A(object): |
|
433 | 433 | def __repr__(self): |
|
434 | 434 | raise Exception() |
|
435 | 435 | _ip.user_ns['a'] = A() |
|
436 | 436 | _ip.magic("whos") |
|
437 | 437 | |
|
438 | 438 | @py3compat.u_format |
|
439 | 439 | def doctest_precision(): |
|
440 | 440 | """doctest for %precision |
|
441 | 441 | |
|
442 | 442 | In [1]: f = get_ipython().display_formatter.formatters['text/plain'] |
|
443 | 443 | |
|
444 | 444 | In [2]: %precision 5 |
|
445 | 445 | Out[2]: {u}'%.5f' |
|
446 | 446 | |
|
447 | 447 | In [3]: f.float_format |
|
448 | 448 | Out[3]: {u}'%.5f' |
|
449 | 449 | |
|
450 | 450 | In [4]: %precision %e |
|
451 | 451 | Out[4]: {u}'%e' |
|
452 | 452 | |
|
453 | 453 | In [5]: f(3.1415927) |
|
454 | 454 | Out[5]: {u}'3.141593e+00' |
|
455 | 455 | """ |
|
456 | 456 | |
|
457 | 457 | def test_psearch(): |
|
458 | 458 | with tt.AssertPrints("dict.fromkeys"): |
|
459 | 459 | _ip.run_cell("dict.fr*?") |
|
460 | 460 | |
|
461 | 461 | def test_timeit_shlex(): |
|
462 | 462 | """test shlex issues with timeit (#1109)""" |
|
463 | 463 | _ip.ex("def f(*a,**kw): pass") |
|
464 | 464 | _ip.magic('timeit -n1 "this is a bug".count(" ")') |
|
465 | 465 | _ip.magic('timeit -r1 -n1 f(" ", 1)') |
|
466 | 466 | _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")') |
|
467 | 467 | _ip.magic('timeit -r1 -n1 ("a " + "b")') |
|
468 | 468 | _ip.magic('timeit -r1 -n1 f("a " + "b")') |
|
469 | 469 | _ip.magic('timeit -r1 -n1 f("a " + "b ")') |
|
470 | 470 | |
|
471 | 471 | |
|
472 | 472 | def test_timeit_arguments(): |
|
473 | 473 | "Test valid timeit arguments, should not cause SyntaxError (GH #1269)" |
|
474 | 474 | _ip.magic("timeit ('#')") |
|
475 | 475 | |
|
476 | 476 | |
|
477 | 477 | def test_timeit_special_syntax(): |
|
478 | 478 | "Test %%timeit with IPython special syntax" |
|
479 | 479 | @register_line_magic |
|
480 | 480 | def lmagic(line): |
|
481 | 481 | ip = get_ipython() |
|
482 | 482 | ip.user_ns['lmagic_out'] = line |
|
483 | 483 | |
|
484 | 484 | # line mode test |
|
485 | 485 | _ip.run_line_magic('timeit', '-n1 -r1 %lmagic my line') |
|
486 | 486 | nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line') |
|
487 | 487 | # cell mode test |
|
488 | 488 | _ip.run_cell_magic('timeit', '-n1 -r1', '%lmagic my line2') |
|
489 | 489 | nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2') |
|
490 | 490 | |
|
491 | 491 | def test_timeit_return(): |
|
492 | 492 | """ |
|
493 | 493 | test wether timeit -o return object |
|
494 | 494 | """ |
|
495 | 495 | |
|
496 | 496 | res = _ip.run_line_magic('timeit','-n10 -r10 -o 1') |
|
497 | 497 | assert(res is not None) |
|
498 | 498 | |
|
499 | 499 | def test_timeit_quiet(): |
|
500 | 500 | """ |
|
501 | 501 | test quiet option of timeit magic |
|
502 | 502 | """ |
|
503 | 503 | with tt.AssertNotPrints("loops"): |
|
504 | 504 | _ip.run_cell("%timeit -n1 -r1 -q 1") |
|
505 | 505 | |
|
506 | 506 | @dec.skipif(execution.profile is None) |
|
507 | 507 | def test_prun_special_syntax(): |
|
508 | 508 | "Test %%prun with IPython special syntax" |
|
509 | 509 | @register_line_magic |
|
510 | 510 | def lmagic(line): |
|
511 | 511 | ip = get_ipython() |
|
512 | 512 | ip.user_ns['lmagic_out'] = line |
|
513 | 513 | |
|
514 | 514 | # line mode test |
|
515 | 515 | _ip.run_line_magic('prun', '-q %lmagic my line') |
|
516 | 516 | nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line') |
|
517 | 517 | # cell mode test |
|
518 | 518 | _ip.run_cell_magic('prun', '-q', '%lmagic my line2') |
|
519 | 519 | nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2') |
|
520 | 520 | |
|
521 | 521 | @dec.skipif(execution.profile is None) |
|
522 | 522 | def test_prun_quotes(): |
|
523 | 523 | "Test that prun does not clobber string escapes (GH #1302)" |
|
524 | 524 | _ip.magic(r"prun -q x = '\t'") |
|
525 | 525 | nt.assert_equal(_ip.user_ns['x'], '\t') |
|
526 | 526 | |
|
527 | 527 | def test_extension(): |
|
528 | 528 | tmpdir = TemporaryDirectory() |
|
529 | 529 | orig_ipython_dir = _ip.ipython_dir |
|
530 | 530 | try: |
|
531 | 531 | _ip.ipython_dir = tmpdir.name |
|
532 | 532 | nt.assert_raises(ImportError, _ip.magic, "load_ext daft_extension") |
|
533 | 533 | url = os.path.join(os.path.dirname(__file__), "daft_extension.py") |
|
534 | 534 | _ip.magic("install_ext %s" % url) |
|
535 | 535 | _ip.user_ns.pop('arq', None) |
|
536 | 536 | invalidate_caches() # Clear import caches |
|
537 | 537 | _ip.magic("load_ext daft_extension") |
|
538 | 538 | nt.assert_equal(_ip.user_ns['arq'], 185) |
|
539 | 539 | _ip.magic("unload_ext daft_extension") |
|
540 | 540 | assert 'arq' not in _ip.user_ns |
|
541 | 541 | finally: |
|
542 | 542 | _ip.ipython_dir = orig_ipython_dir |
|
543 | 543 | tmpdir.cleanup() |
|
544 | 544 | |
|
545 | 545 | def test_notebook_export_json(): |
|
546 | 546 | with TemporaryDirectory() as td: |
|
547 | 547 | outfile = os.path.join(td, "nb.ipynb") |
|
548 | 548 | _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'")) |
|
549 | 549 | _ip.magic("notebook -e %s" % outfile) |
|
550 | 550 | |
|
551 | 551 | def test_notebook_export_py(): |
|
552 | 552 | with TemporaryDirectory() as td: |
|
553 | 553 | outfile = os.path.join(td, "nb.py") |
|
554 | 554 | _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'")) |
|
555 | 555 | _ip.magic("notebook -e %s" % outfile) |
|
556 | 556 | |
|
557 | 557 | def test_notebook_reformat_py(): |
|
558 | 558 | with TemporaryDirectory() as td: |
|
559 | 559 | infile = os.path.join(td, "nb.ipynb") |
|
560 | 560 | with io.open(infile, 'w', encoding='utf-8') as f: |
|
561 | 561 | current.write(nb0, f, 'json') |
|
562 | 562 | |
|
563 | 563 | _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'")) |
|
564 | 564 | _ip.magic("notebook -f py %s" % infile) |
|
565 | 565 | |
|
566 | 566 | def test_notebook_reformat_json(): |
|
567 | 567 | with TemporaryDirectory() as td: |
|
568 | 568 | infile = os.path.join(td, "nb.py") |
|
569 | 569 | with io.open(infile, 'w', encoding='utf-8') as f: |
|
570 | 570 | current.write(nb0, f, 'py') |
|
571 | 571 | |
|
572 | 572 | _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'")) |
|
573 | 573 | _ip.magic("notebook -f ipynb %s" % infile) |
|
574 | 574 | _ip.magic("notebook -f json %s" % infile) |
|
575 | 575 | |
|
576 | 576 | def test_env(): |
|
577 | 577 | env = _ip.magic("env") |
|
578 | 578 | assert isinstance(env, dict), type(env) |
|
579 | 579 | |
|
580 | 580 | |
|
581 | 581 | class CellMagicTestCase(TestCase): |
|
582 | 582 | |
|
583 | 583 | def check_ident(self, magic): |
|
584 | 584 | # Manually called, we get the result |
|
585 | 585 | out = _ip.run_cell_magic(magic, 'a', 'b') |
|
586 | 586 | nt.assert_equal(out, ('a','b')) |
|
587 | 587 | # Via run_cell, it goes into the user's namespace via displayhook |
|
588 | 588 | _ip.run_cell('%%' + magic +' c\nd') |
|
589 | 589 | nt.assert_equal(_ip.user_ns['_'], ('c','d')) |
|
590 | 590 | |
|
591 | 591 | def test_cell_magic_func_deco(self): |
|
592 | 592 | "Cell magic using simple decorator" |
|
593 | 593 | @register_cell_magic |
|
594 | 594 | def cellm(line, cell): |
|
595 | 595 | return line, cell |
|
596 | 596 | |
|
597 | 597 | self.check_ident('cellm') |
|
598 | 598 | |
|
599 | 599 | def test_cell_magic_reg(self): |
|
600 | 600 | "Cell magic manually registered" |
|
601 | 601 | def cellm(line, cell): |
|
602 | 602 | return line, cell |
|
603 | 603 | |
|
604 | 604 | _ip.register_magic_function(cellm, 'cell', 'cellm2') |
|
605 | 605 | self.check_ident('cellm2') |
|
606 | 606 | |
|
607 | 607 | def test_cell_magic_class(self): |
|
608 | 608 | "Cell magics declared via a class" |
|
609 | 609 | @magics_class |
|
610 | 610 | class MyMagics(Magics): |
|
611 | 611 | |
|
612 | 612 | @cell_magic |
|
613 | 613 | def cellm3(self, line, cell): |
|
614 | 614 | return line, cell |
|
615 | 615 | |
|
616 | 616 | _ip.register_magics(MyMagics) |
|
617 | 617 | self.check_ident('cellm3') |
|
618 | 618 | |
|
619 | 619 | def test_cell_magic_class2(self): |
|
620 | 620 | "Cell magics declared via a class, #2" |
|
621 | 621 | @magics_class |
|
622 | 622 | class MyMagics2(Magics): |
|
623 | 623 | |
|
624 | 624 | @cell_magic('cellm4') |
|
625 | 625 | def cellm33(self, line, cell): |
|
626 | 626 | return line, cell |
|
627 | 627 | |
|
628 | 628 | _ip.register_magics(MyMagics2) |
|
629 | 629 | self.check_ident('cellm4') |
|
630 | 630 | # Check that nothing is registered as 'cellm33' |
|
631 | 631 | c33 = _ip.find_cell_magic('cellm33') |
|
632 | 632 | nt.assert_equal(c33, None) |
|
633 | 633 | |
|
634 | 634 | def test_file(): |
|
635 | 635 | """Basic %%file""" |
|
636 | 636 | ip = get_ipython() |
|
637 | 637 | with TemporaryDirectory() as td: |
|
638 | 638 | fname = os.path.join(td, 'file1') |
|
639 | 639 | ip.run_cell_magic("file", fname, u'\n'.join([ |
|
640 | 640 | 'line1', |
|
641 | 641 | 'line2', |
|
642 | 642 | ])) |
|
643 | 643 | with open(fname) as f: |
|
644 | 644 | s = f.read() |
|
645 | 645 | nt.assert_in('line1\n', s) |
|
646 | 646 | nt.assert_in('line2', s) |
|
647 | 647 | |
|
648 | 648 | def test_file_var_expand(): |
|
649 | 649 | """%%file $filename""" |
|
650 | 650 | ip = get_ipython() |
|
651 | 651 | with TemporaryDirectory() as td: |
|
652 | 652 | fname = os.path.join(td, 'file1') |
|
653 | 653 | ip.user_ns['filename'] = fname |
|
654 | 654 | ip.run_cell_magic("file", '$filename', u'\n'.join([ |
|
655 | 655 | 'line1', |
|
656 | 656 | 'line2', |
|
657 | 657 | ])) |
|
658 | 658 | with open(fname) as f: |
|
659 | 659 | s = f.read() |
|
660 | 660 | nt.assert_in('line1\n', s) |
|
661 | 661 | nt.assert_in('line2', s) |
|
662 | 662 | |
|
663 | 663 | def test_file_unicode(): |
|
664 | 664 | """%%file with unicode cell""" |
|
665 | 665 | ip = get_ipython() |
|
666 | 666 | with TemporaryDirectory() as td: |
|
667 | 667 | fname = os.path.join(td, 'file1') |
|
668 | 668 | ip.run_cell_magic("file", fname, u'\n'.join([ |
|
669 | 669 | u'linΓ©1', |
|
670 | 670 | u'linΓ©2', |
|
671 | 671 | ])) |
|
672 | 672 | with io.open(fname, encoding='utf-8') as f: |
|
673 | 673 | s = f.read() |
|
674 | 674 | nt.assert_in(u'linΓ©1\n', s) |
|
675 | 675 | nt.assert_in(u'linΓ©2', s) |
|
676 | 676 | |
|
677 | 677 | def test_file_amend(): |
|
678 | 678 | """%%file -a amends files""" |
|
679 | 679 | ip = get_ipython() |
|
680 | 680 | with TemporaryDirectory() as td: |
|
681 | 681 | fname = os.path.join(td, 'file2') |
|
682 | 682 | ip.run_cell_magic("file", fname, u'\n'.join([ |
|
683 | 683 | 'line1', |
|
684 | 684 | 'line2', |
|
685 | 685 | ])) |
|
686 | 686 | ip.run_cell_magic("file", "-a %s" % fname, u'\n'.join([ |
|
687 | 687 | 'line3', |
|
688 | 688 | 'line4', |
|
689 | 689 | ])) |
|
690 | 690 | with open(fname) as f: |
|
691 | 691 | s = f.read() |
|
692 | 692 | nt.assert_in('line1\n', s) |
|
693 | 693 | nt.assert_in('line3\n', s) |
|
694 | 694 | |
|
695 | 695 | |
|
696 | 696 | def test_script_config(): |
|
697 | 697 | ip = get_ipython() |
|
698 | 698 | ip.config.ScriptMagics.script_magics = ['whoda'] |
|
699 | 699 | sm = script.ScriptMagics(shell=ip) |
|
700 | 700 | nt.assert_in('whoda', sm.magics['cell']) |
|
701 | 701 | |
|
702 | 702 | @dec.skip_win32 |
|
703 | 703 | def test_script_out(): |
|
704 | 704 | ip = get_ipython() |
|
705 | 705 | ip.run_cell_magic("script", "--out output sh", "echo 'hi'") |
|
706 | 706 | nt.assert_equal(ip.user_ns['output'], 'hi\n') |
|
707 | 707 | |
|
708 | 708 | @dec.skip_win32 |
|
709 | 709 | def test_script_err(): |
|
710 | 710 | ip = get_ipython() |
|
711 | 711 | ip.run_cell_magic("script", "--err error sh", "echo 'hello' >&2") |
|
712 | 712 | nt.assert_equal(ip.user_ns['error'], 'hello\n') |
|
713 | 713 | |
|
714 | 714 | @dec.skip_win32 |
|
715 | 715 | def test_script_out_err(): |
|
716 | 716 | ip = get_ipython() |
|
717 | 717 | ip.run_cell_magic("script", "--out output --err error sh", "echo 'hi'\necho 'hello' >&2") |
|
718 | 718 | nt.assert_equal(ip.user_ns['output'], 'hi\n') |
|
719 | 719 | nt.assert_equal(ip.user_ns['error'], 'hello\n') |
|
720 | 720 | |
|
721 | 721 | @dec.skip_win32 |
|
722 | 722 | def test_script_bg_out(): |
|
723 | 723 | ip = get_ipython() |
|
724 | 724 | ip.run_cell_magic("script", "--bg --out output sh", "echo 'hi'") |
|
725 | 725 | nt.assert_equal(ip.user_ns['output'].read(), b'hi\n') |
|
726 | 726 | |
|
727 | 727 | @dec.skip_win32 |
|
728 | 728 | def test_script_bg_err(): |
|
729 | 729 | ip = get_ipython() |
|
730 | 730 | ip.run_cell_magic("script", "--bg --err error sh", "echo 'hello' >&2") |
|
731 | 731 | nt.assert_equal(ip.user_ns['error'].read(), b'hello\n') |
|
732 | 732 | |
|
733 | 733 | @dec.skip_win32 |
|
734 | 734 | def test_script_bg_out_err(): |
|
735 | 735 | ip = get_ipython() |
|
736 | 736 | ip.run_cell_magic("script", "--bg --out output --err error sh", "echo 'hi'\necho 'hello' >&2") |
|
737 | 737 | nt.assert_equal(ip.user_ns['output'].read(), b'hi\n') |
|
738 | 738 | nt.assert_equal(ip.user_ns['error'].read(), b'hello\n') |
|
739 | 739 | |
|
740 | 740 | def test_script_defaults(): |
|
741 | 741 | ip = get_ipython() |
|
742 | 742 | for cmd in ['sh', 'bash', 'perl', 'ruby']: |
|
743 | 743 | try: |
|
744 | 744 | find_cmd(cmd) |
|
745 | 745 | except Exception: |
|
746 | 746 | pass |
|
747 | 747 | else: |
|
748 | 748 | nt.assert_in(cmd, ip.magics_manager.magics['cell']) |
|
749 | 749 | |
|
750 | 750 | |
|
751 | 751 | @magics_class |
|
752 | 752 | class FooFoo(Magics): |
|
753 | 753 | """class with both %foo and %%foo magics""" |
|
754 | 754 | @line_magic('foo') |
|
755 | 755 | def line_foo(self, line): |
|
756 | 756 | "I am line foo" |
|
757 | 757 | pass |
|
758 | 758 | |
|
759 | 759 | @cell_magic("foo") |
|
760 | 760 | def cell_foo(self, line, cell): |
|
761 | 761 | "I am cell foo, not line foo" |
|
762 | 762 | pass |
|
763 | 763 | |
|
764 | 764 | def test_line_cell_info(): |
|
765 | 765 | """%%foo and %foo magics are distinguishable to inspect""" |
|
766 | 766 | ip = get_ipython() |
|
767 | 767 | ip.magics_manager.register(FooFoo) |
|
768 | 768 | oinfo = ip.object_inspect('foo') |
|
769 | 769 | nt.assert_true(oinfo['found']) |
|
770 | 770 | nt.assert_true(oinfo['ismagic']) |
|
771 | 771 | |
|
772 | 772 | oinfo = ip.object_inspect('%%foo') |
|
773 | 773 | nt.assert_true(oinfo['found']) |
|
774 | 774 | nt.assert_true(oinfo['ismagic']) |
|
775 | 775 | nt.assert_equal(oinfo['docstring'], FooFoo.cell_foo.__doc__) |
|
776 | 776 | |
|
777 | 777 | oinfo = ip.object_inspect('%foo') |
|
778 | 778 | nt.assert_true(oinfo['found']) |
|
779 | 779 | nt.assert_true(oinfo['ismagic']) |
|
780 | 780 | nt.assert_equal(oinfo['docstring'], FooFoo.line_foo.__doc__) |
|
781 | 781 | |
|
782 | 782 | def test_multiple_magics(): |
|
783 | 783 | ip = get_ipython() |
|
784 | 784 | foo1 = FooFoo(ip) |
|
785 | 785 | foo2 = FooFoo(ip) |
|
786 | 786 | mm = ip.magics_manager |
|
787 | 787 | mm.register(foo1) |
|
788 | 788 | nt.assert_true(mm.magics['line']['foo'].im_self is foo1) |
|
789 | 789 | mm.register(foo2) |
|
790 | 790 | nt.assert_true(mm.magics['line']['foo'].im_self is foo2) |
|
791 | 791 | |
|
792 | 792 | def test_alias_magic(): |
|
793 | 793 | """Test %alias_magic.""" |
|
794 | 794 | ip = get_ipython() |
|
795 | 795 | mm = ip.magics_manager |
|
796 | 796 | |
|
797 | 797 | # Basic operation: both cell and line magics are created, if possible. |
|
798 | 798 | ip.run_line_magic('alias_magic', 'timeit_alias timeit') |
|
799 | 799 | nt.assert_in('timeit_alias', mm.magics['line']) |
|
800 | 800 | nt.assert_in('timeit_alias', mm.magics['cell']) |
|
801 | 801 | |
|
802 | 802 | # --cell is specified, line magic not created. |
|
803 | 803 | ip.run_line_magic('alias_magic', '--cell timeit_cell_alias timeit') |
|
804 | 804 | nt.assert_not_in('timeit_cell_alias', mm.magics['line']) |
|
805 | 805 | nt.assert_in('timeit_cell_alias', mm.magics['cell']) |
|
806 | 806 | |
|
807 | 807 | # Test that line alias is created successfully. |
|
808 | 808 | ip.run_line_magic('alias_magic', '--line env_alias env') |
|
809 | 809 | nt.assert_equal(ip.run_line_magic('env', ''), |
|
810 | 810 | ip.run_line_magic('env_alias', '')) |
|
811 | 811 | |
|
812 | 812 | def test_save(): |
|
813 | 813 | """Test %save.""" |
|
814 | 814 | ip = get_ipython() |
|
815 | 815 | ip.history_manager.reset() # Clear any existing history. |
|
816 | 816 | cmds = [u"a=1", u"def b():\n return a**2", u"print(a, b())"] |
|
817 | 817 | for i, cmd in enumerate(cmds, start=1): |
|
818 | 818 | ip.history_manager.store_inputs(i, cmd) |
|
819 | 819 | with TemporaryDirectory() as tmpdir: |
|
820 | 820 | file = os.path.join(tmpdir, "testsave.py") |
|
821 | 821 | ip.run_line_magic("save", "%s 1-10" % file) |
|
822 | 822 | with open(file) as f: |
|
823 | 823 | content = f.read() |
|
824 | 824 | nt.assert_equal(content.count(cmds[0]), 1) |
|
825 | 825 | nt.assert_in('coding: utf-8', content) |
|
826 | 826 | ip.run_line_magic("save", "-a %s 1-10" % file) |
|
827 | 827 | with open(file) as f: |
|
828 | 828 | content = f.read() |
|
829 | 829 | nt.assert_equal(content.count(cmds[0]), 2) |
|
830 | 830 | nt.assert_in('coding: utf-8', content) |
|
831 | 831 | |
|
832 | 832 | |
|
833 | 833 | def test_store(): |
|
834 | 834 | """Test %store.""" |
|
835 | 835 | ip = get_ipython() |
|
836 | 836 | ip.run_line_magic('load_ext', 'storemagic') |
|
837 | 837 | |
|
838 | 838 | # make sure the storage is empty |
|
839 | 839 | ip.run_line_magic('store', '-z') |
|
840 | 840 | ip.user_ns['var'] = 42 |
|
841 | 841 | ip.run_line_magic('store', 'var') |
|
842 | 842 | ip.user_ns['var'] = 39 |
|
843 | 843 | ip.run_line_magic('store', '-r') |
|
844 | 844 | nt.assert_equal(ip.user_ns['var'], 42) |
|
845 | 845 | |
|
846 | 846 | ip.run_line_magic('store', '-d var') |
|
847 | 847 | ip.user_ns['var'] = 39 |
|
848 | 848 | ip.run_line_magic('store' , '-r') |
|
849 | 849 | nt.assert_equal(ip.user_ns['var'], 39) |
|
850 | 850 | |
|
851 | 851 | |
|
852 | 852 | def _run_edit_test(arg_s, exp_filename=None, |
|
853 | 853 | exp_lineno=-1, |
|
854 | 854 | exp_contents=None, |
|
855 | 855 | exp_is_temp=None): |
|
856 | 856 | ip = get_ipython() |
|
857 | 857 | M = code.CodeMagics(ip) |
|
858 | 858 | last_call = ['',''] |
|
859 | 859 | opts,args = M.parse_options(arg_s,'prxn:') |
|
860 | 860 | filename, lineno, is_temp = M._find_edit_target(ip, args, opts, last_call) |
|
861 | 861 | |
|
862 | 862 | if exp_filename is not None: |
|
863 | 863 | nt.assert_equal(exp_filename, filename) |
|
864 | 864 | if exp_contents is not None: |
|
865 | 865 | with io.open(filename, 'r') as f: |
|
866 | 866 | contents = f.read() |
|
867 | 867 | nt.assert_equal(exp_contents, contents) |
|
868 | 868 | if exp_lineno != -1: |
|
869 | 869 | nt.assert_equal(exp_lineno, lineno) |
|
870 | 870 | if exp_is_temp is not None: |
|
871 | 871 | nt.assert_equal(exp_is_temp, is_temp) |
|
872 | 872 | |
|
873 | 873 | |
|
874 | 874 | def test_edit_interactive(): |
|
875 | 875 | """%edit on interactively defined objects""" |
|
876 | 876 | ip = get_ipython() |
|
877 | 877 | n = ip.execution_count |
|
878 | 878 | ip.run_cell(u"def foo(): return 1", store_history=True) |
|
879 | 879 | |
|
880 | 880 | try: |
|
881 | 881 | _run_edit_test("foo") |
|
882 | 882 | except code.InteractivelyDefined as e: |
|
883 | 883 | nt.assert_equal(e.index, n) |
|
884 | 884 | else: |
|
885 | 885 | raise AssertionError("Should have raised InteractivelyDefined") |
|
886 | 886 | |
|
887 | 887 | |
|
888 | 888 | def test_edit_cell(): |
|
889 | 889 | """%edit [cell id]""" |
|
890 | 890 | ip = get_ipython() |
|
891 | 891 | |
|
892 | 892 | ip.run_cell(u"def foo(): return 1", store_history=True) |
|
893 | 893 | |
|
894 | 894 | # test |
|
895 | 895 | _run_edit_test("1", exp_contents=ip.user_ns['In'][1], exp_is_temp=True) |
@@ -1,243 +1,243 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | %store magic for lightweight persistence. |
|
4 | 4 | |
|
5 | 5 | Stores variables, aliases and macros in IPython's database. |
|
6 | 6 | |
|
7 | 7 | To automatically restore stored variables at startup, add this to your |
|
8 | 8 | :file:`ipython_config.py` file:: |
|
9 | 9 | |
|
10 | 10 | c.StoreMagic.autorestore = True |
|
11 | 11 | """ |
|
12 | 12 | #----------------------------------------------------------------------------- |
|
13 | 13 | # Copyright (c) 2012, The IPython Development Team. |
|
14 | 14 | # |
|
15 | 15 | # Distributed under the terms of the Modified BSD License. |
|
16 | 16 | # |
|
17 | 17 | # The full license is in the file COPYING.txt, distributed with this software. |
|
18 | 18 | #----------------------------------------------------------------------------- |
|
19 | 19 | |
|
20 | 20 | #----------------------------------------------------------------------------- |
|
21 | 21 | # Imports |
|
22 | 22 | #----------------------------------------------------------------------------- |
|
23 | 23 | |
|
24 | 24 | # Stdlib |
|
25 | 25 | import inspect, os, sys, textwrap |
|
26 | 26 | |
|
27 | 27 | # Our own |
|
28 | 28 | from IPython.config.configurable import Configurable |
|
29 | 29 | from IPython.core.error import UsageError |
|
30 | 30 | from IPython.core.magic import Magics, magics_class, line_magic |
|
31 | 31 | from IPython.testing.skipdoctest import skip_doctest |
|
32 | 32 | from IPython.utils.traitlets import Bool |
|
33 | 33 | |
|
34 | 34 | #----------------------------------------------------------------------------- |
|
35 | 35 | # Functions and classes |
|
36 | 36 | #----------------------------------------------------------------------------- |
|
37 | 37 | |
|
38 | 38 | def restore_aliases(ip): |
|
39 | 39 | staliases = ip.db.get('stored_aliases', {}) |
|
40 | 40 | for k,v in staliases.items(): |
|
41 | 41 | #print "restore alias",k,v # dbg |
|
42 | 42 | #self.alias_table[k] = v |
|
43 | 43 | ip.alias_manager.define_alias(k,v) |
|
44 | 44 | |
|
45 | 45 | |
|
46 | 46 | def refresh_variables(ip): |
|
47 | 47 | db = ip.db |
|
48 | 48 | for key in db.keys('autorestore/*'): |
|
49 | 49 | # strip autorestore |
|
50 | 50 | justkey = os.path.basename(key) |
|
51 | 51 | try: |
|
52 | 52 | obj = db[key] |
|
53 | 53 | except KeyError: |
|
54 | 54 | print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % justkey |
|
55 | 55 | print "The error was:", sys.exc_info()[0] |
|
56 | 56 | else: |
|
57 | 57 | #print "restored",justkey,"=",obj #dbg |
|
58 | 58 | ip.user_ns[justkey] = obj |
|
59 | 59 | |
|
60 | 60 | |
|
61 | 61 | def restore_dhist(ip): |
|
62 | 62 | ip.user_ns['_dh'] = ip.db.get('dhist',[]) |
|
63 | 63 | |
|
64 | 64 | |
|
65 | 65 | def restore_data(ip): |
|
66 | 66 | refresh_variables(ip) |
|
67 | 67 | restore_aliases(ip) |
|
68 | 68 | restore_dhist(ip) |
|
69 | 69 | |
|
70 | 70 | |
|
71 | 71 | @magics_class |
|
72 | 72 | class StoreMagics(Magics, Configurable): |
|
73 | 73 | """Lightweight persistence for python variables. |
|
74 | 74 | |
|
75 | 75 | Provides the %store magic.""" |
|
76 | 76 | |
|
77 | 77 | autorestore = Bool(False, config=True, help= |
|
78 | 78 | """If True, any %store-d variables will be automatically restored |
|
79 | 79 | when IPython starts. |
|
80 | 80 | """ |
|
81 | 81 | ) |
|
82 | 82 | |
|
83 | 83 | def __init__(self, shell): |
|
84 | 84 | Configurable.__init__(self, config=shell.config) |
|
85 | 85 | Magics.__init__(self, shell=shell) |
|
86 | 86 | self.shell.configurables.append(self) |
|
87 | 87 | if self.autorestore: |
|
88 | 88 | restore_data(self.shell) |
|
89 | 89 | |
|
90 | 90 | @skip_doctest |
|
91 | 91 | @line_magic |
|
92 | 92 | def store(self, parameter_s=''): |
|
93 | 93 | """Lightweight persistence for python variables. |
|
94 | 94 | |
|
95 | 95 | Example:: |
|
96 | 96 | |
|
97 | 97 | In [1]: l = ['hello',10,'world'] |
|
98 | 98 | In [2]: %store l |
|
99 | 99 | In [3]: exit |
|
100 | 100 | |
|
101 | 101 | (IPython session is closed and started again...) |
|
102 | 102 | |
|
103 | 103 | ville@badger:~$ ipython |
|
104 | 104 | In [1]: l |
|
105 | 105 | NameError: name 'l' is not defined |
|
106 | 106 | In [2]: %store -r |
|
107 | 107 | In [3]: l |
|
108 | 108 | Out[3]: ['hello', 10, 'world'] |
|
109 | 109 | |
|
110 | 110 | Usage: |
|
111 | 111 | |
|
112 | 112 | * ``%store`` - Show list of all variables and their current |
|
113 | 113 | values |
|
114 | 114 | * ``%store spam`` - Store the *current* value of the variable spam |
|
115 | 115 | to disk |
|
116 | 116 | * ``%store -d spam`` - Remove the variable and its value from storage |
|
117 | 117 | * ``%store -z`` - Remove all variables from storage |
|
118 | 118 | * ``%store -r`` - Refresh all variables from store (overwrite |
|
119 | 119 | current vals) |
|
120 | 120 | * ``%store -r spam bar`` - Refresh specified variables from store |
|
121 | 121 | (delete current val) |
|
122 | 122 | * ``%store foo >a.txt`` - Store value of foo to new file a.txt |
|
123 | 123 | * ``%store foo >>a.txt`` - Append value of foo to file a.txt |
|
124 | 124 | |
|
125 | 125 | It should be noted that if you change the value of a variable, you |
|
126 | 126 | need to %store it again if you want to persist the new value. |
|
127 | 127 | |
|
128 | 128 | Note also that the variables will need to be pickleable; most basic |
|
129 | 129 | python types can be safely %store'd. |
|
130 | 130 | |
|
131 | 131 | Also aliases can be %store'd across sessions. |
|
132 | 132 | """ |
|
133 | 133 | |
|
134 | 134 | opts,argsl = self.parse_options(parameter_s,'drz',mode='string') |
|
135 | 135 | args = argsl.split(None,1) |
|
136 | 136 | ip = self.shell |
|
137 | 137 | db = ip.db |
|
138 | 138 | # delete |
|
139 | 139 | if 'd' in opts: |
|
140 | 140 | try: |
|
141 | 141 | todel = args[0] |
|
142 | 142 | except IndexError: |
|
143 | 143 | raise UsageError('You must provide the variable to forget') |
|
144 | 144 | else: |
|
145 | 145 | try: |
|
146 | 146 | del db['autorestore/' + todel] |
|
147 | 147 | except: |
|
148 | 148 | raise UsageError("Can't delete variable '%s'" % todel) |
|
149 | 149 | # reset |
|
150 | 150 | elif 'z' in opts: |
|
151 | 151 | for k in db.keys('autorestore/*'): |
|
152 | 152 | del db[k] |
|
153 | 153 | |
|
154 | 154 | elif 'r' in opts: |
|
155 | 155 | if args: |
|
156 | 156 | for arg in args: |
|
157 | 157 | try: |
|
158 | 158 | obj = db['autorestore/' + arg] |
|
159 | 159 | except KeyError: |
|
160 | 160 | print "no stored variable %s" % arg |
|
161 | 161 | else: |
|
162 | 162 | ip.user_ns[arg] = obj |
|
163 | 163 | else: |
|
164 | 164 | restore_data(ip) |
|
165 | 165 | |
|
166 | 166 | # run without arguments -> list variables & values |
|
167 | 167 | elif not args: |
|
168 | 168 | vars = db.keys('autorestore/*') |
|
169 | 169 | vars.sort() |
|
170 | 170 | if vars: |
|
171 | 171 | size = max(map(len, vars)) |
|
172 | 172 | else: |
|
173 | 173 | size = 0 |
|
174 | 174 | |
|
175 | 175 | print 'Stored variables and their in-db values:' |
|
176 | 176 | fmt = '%-'+str(size)+'s -> %s' |
|
177 | 177 | get = db.get |
|
178 | 178 | for var in vars: |
|
179 | 179 | justkey = os.path.basename(var) |
|
180 | 180 | # print 30 first characters from every var |
|
181 | 181 | print fmt % (justkey, repr(get(var, '<unavailable>'))[:50]) |
|
182 | 182 | |
|
183 | 183 | # default action - store the variable |
|
184 | 184 | else: |
|
185 | 185 | # %store foo >file.txt or >>file.txt |
|
186 | 186 | if len(args) > 1 and args[1].startswith('>'): |
|
187 | 187 | fnam = os.path.expanduser(args[1].lstrip('>').lstrip()) |
|
188 | 188 | if args[1].startswith('>>'): |
|
189 | 189 | fil = open(fnam, 'a') |
|
190 | 190 | else: |
|
191 | 191 | fil = open(fnam, 'w') |
|
192 | 192 | obj = ip.ev(args[0]) |
|
193 | 193 | print "Writing '%s' (%s) to file '%s'." % (args[0], |
|
194 | 194 | obj.__class__.__name__, fnam) |
|
195 | 195 | |
|
196 | 196 | |
|
197 | 197 | if not isinstance (obj, basestring): |
|
198 | 198 | from pprint import pprint |
|
199 | 199 | pprint(obj, fil) |
|
200 | 200 | else: |
|
201 | 201 | fil.write(obj) |
|
202 | 202 | if not obj.endswith('\n'): |
|
203 | 203 | fil.write('\n') |
|
204 | 204 | |
|
205 | 205 | fil.close() |
|
206 | 206 | return |
|
207 | 207 | |
|
208 | 208 | # %store foo |
|
209 | 209 | try: |
|
210 | 210 | obj = ip.user_ns[args[0]] |
|
211 | 211 | except KeyError: |
|
212 | 212 | # it might be an alias |
|
213 | # This needs to be refactored to use the new AliasManager stuff. | |
|
214 | if args[0] in ip.alias_manager: | |
|
215 | name = args[0] | |
|
216 | nargs, cmd = ip.alias_manager.alias_table[ name ] | |
|
217 | staliases = db.get('stored_aliases',{}) | |
|
218 | staliases[ name ] = cmd | |
|
219 |
|
|
|
220 |
|
|
|
221 | return | |
|
222 | else: | |
|
223 | raise UsageError("Unknown variable '%s'" % args[0]) | |
|
213 | name = args[0] | |
|
214 | try: | |
|
215 | cmd = ip.alias_manager.retrieve_alias(name) | |
|
216 | except ValueError: | |
|
217 | raise UsageError("Unknown variable '%s'" % name) | |
|
218 | ||
|
219 | staliases = db.get('stored_aliases',{}) | |
|
220 | staliases[name] = cmd | |
|
221 | db['stored_aliases'] = staliases | |
|
222 | print "Alias stored: %s (%s)" % (name, cmd) | |
|
223 | return | |
|
224 | 224 | |
|
225 | 225 | else: |
|
226 | 226 | modname = getattr(inspect.getmodule(obj), '__name__', '') |
|
227 | 227 | if modname == '__main__': |
|
228 | 228 | print textwrap.dedent("""\ |
|
229 | 229 | Warning:%s is %s |
|
230 | 230 | Proper storage of interactively declared classes (or instances |
|
231 | 231 | of those classes) is not possible! Only instances |
|
232 | 232 | of classes in real modules on file system can be %%store'd. |
|
233 | 233 | """ % (args[0], obj) ) |
|
234 | 234 | return |
|
235 | 235 | #pickled = pickle.dumps(obj) |
|
236 | 236 | db[ 'autorestore/' + args[0] ] = obj |
|
237 | 237 | print "Stored '%s' (%s)" % (args[0], obj.__class__.__name__) |
|
238 | 238 | |
|
239 | 239 | |
|
240 | 240 | def load_ipython_extension(ip): |
|
241 | 241 | """Load the extension in IPython.""" |
|
242 | 242 | ip.register_magics(StoreMagics) |
|
243 | 243 |
@@ -1,50 +1,50 b'' | |||
|
1 | 1 | import tempfile, os |
|
2 | 2 | |
|
3 | 3 | from IPython.config.loader import Config |
|
4 | 4 | import nose.tools as nt |
|
5 | 5 | |
|
6 | 6 | ip = get_ipython() |
|
7 | 7 | ip.magic('load_ext storemagic') |
|
8 | 8 | |
|
9 | 9 | def test_store_restore(): |
|
10 | 10 | ip.user_ns['foo'] = 78 |
|
11 | 11 | ip.magic('alias bar echo "hello"') |
|
12 | 12 | tmpd = tempfile.mkdtemp() |
|
13 | 13 | ip.magic('cd ' + tmpd) |
|
14 | 14 | ip.magic('store foo') |
|
15 | 15 | ip.magic('store bar') |
|
16 | 16 | |
|
17 | 17 | # Check storing |
|
18 | 18 | nt.assert_equal(ip.db['autorestore/foo'], 78) |
|
19 | 19 | nt.assert_in('bar', ip.db['stored_aliases']) |
|
20 | 20 | |
|
21 | 21 | # Remove those items |
|
22 | 22 | ip.user_ns.pop('foo', None) |
|
23 | 23 | ip.alias_manager.undefine_alias('bar') |
|
24 | 24 | ip.magic('cd -') |
|
25 | 25 | ip.user_ns['_dh'][:] = [] |
|
26 | 26 | |
|
27 | 27 | # Check restoring |
|
28 | 28 | ip.magic('store -r') |
|
29 | 29 | nt.assert_equal(ip.user_ns['foo'], 78) |
|
30 |
|
|
|
30 | assert ip.alias_manager.is_alias('bar') | |
|
31 | 31 | nt.assert_in(os.path.realpath(tmpd), ip.user_ns['_dh']) |
|
32 | 32 | |
|
33 | 33 | os.rmdir(tmpd) |
|
34 | 34 | |
|
35 | 35 | def test_autorestore(): |
|
36 | 36 | ip.user_ns['foo'] = 95 |
|
37 | 37 | ip.magic('store foo') |
|
38 | 38 | del ip.user_ns['foo'] |
|
39 | 39 | c = Config() |
|
40 | 40 | c.StoreMagics.autorestore = False |
|
41 | 41 | orig_config = ip.config |
|
42 | 42 | try: |
|
43 | 43 | ip.config = c |
|
44 | 44 | ip.extension_manager.reload_extension('storemagic') |
|
45 | 45 | nt.assert_not_in('foo', ip.user_ns) |
|
46 | 46 | c.StoreMagics.autorestore = True |
|
47 | 47 | ip.extension_manager.reload_extension('storemagic') |
|
48 | 48 | nt.assert_equal(ip.user_ns['foo'], 95) |
|
49 | 49 | finally: |
|
50 | 50 | ip.config = orig_config |
@@ -1,690 +1,690 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Subclass of InteractiveShell for terminal based frontends.""" |
|
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 | from __future__ import print_function |
|
17 | 17 | |
|
18 | 18 | import bdb |
|
19 | 19 | import os |
|
20 | 20 | import sys |
|
21 | 21 | |
|
22 | 22 | from IPython.core.error import TryNext, UsageError |
|
23 | 23 | from IPython.core.usage import interactive_usage, default_banner |
|
24 | 24 | from IPython.core.inputsplitter import IPythonInputSplitter |
|
25 | 25 | from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC |
|
26 | 26 | from IPython.core.magic import Magics, magics_class, line_magic |
|
27 | 27 | from IPython.testing.skipdoctest import skip_doctest |
|
28 | 28 | from IPython.utils.encoding import get_stream_enc |
|
29 | 29 | from IPython.utils import py3compat |
|
30 | 30 | from IPython.utils.terminal import toggle_set_term_title, set_term_title |
|
31 | 31 | from IPython.utils.process import abbrev_cwd |
|
32 | 32 | from IPython.utils.warn import warn, error |
|
33 | 33 | from IPython.utils.text import num_ini_spaces, SList, strip_email_quotes |
|
34 | 34 | from IPython.utils.traitlets import Integer, CBool, Unicode |
|
35 | 35 | |
|
36 | 36 | #----------------------------------------------------------------------------- |
|
37 | 37 | # Utilities |
|
38 | 38 | #----------------------------------------------------------------------------- |
|
39 | 39 | |
|
40 | 40 | def get_default_editor(): |
|
41 | 41 | try: |
|
42 | 42 | ed = os.environ['EDITOR'] |
|
43 | 43 | except KeyError: |
|
44 | 44 | if os.name == 'posix': |
|
45 | 45 | ed = 'vi' # the only one guaranteed to be there! |
|
46 | 46 | else: |
|
47 | 47 | ed = 'notepad' # same in Windows! |
|
48 | 48 | return ed |
|
49 | 49 | |
|
50 | 50 | |
|
51 | 51 | def get_pasted_lines(sentinel, l_input=py3compat.input): |
|
52 | 52 | """ Yield pasted lines until the user enters the given sentinel value. |
|
53 | 53 | """ |
|
54 | 54 | print("Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." \ |
|
55 | 55 | % sentinel) |
|
56 | 56 | while True: |
|
57 | 57 | try: |
|
58 | 58 | l = l_input(':') |
|
59 | 59 | if l == sentinel: |
|
60 | 60 | return |
|
61 | 61 | else: |
|
62 | 62 | yield l |
|
63 | 63 | except EOFError: |
|
64 | 64 | print('<EOF>') |
|
65 | 65 | return |
|
66 | 66 | |
|
67 | 67 | |
|
68 | 68 | #------------------------------------------------------------------------ |
|
69 | 69 | # Terminal-specific magics |
|
70 | 70 | #------------------------------------------------------------------------ |
|
71 | 71 | |
|
72 | 72 | @magics_class |
|
73 | 73 | class TerminalMagics(Magics): |
|
74 | 74 | def __init__(self, shell): |
|
75 | 75 | super(TerminalMagics, self).__init__(shell) |
|
76 | 76 | self.input_splitter = IPythonInputSplitter() |
|
77 | 77 | |
|
78 | 78 | def store_or_execute(self, block, name): |
|
79 | 79 | """ Execute a block, or store it in a variable, per the user's request. |
|
80 | 80 | """ |
|
81 | 81 | if name: |
|
82 | 82 | # If storing it for further editing |
|
83 | 83 | self.shell.user_ns[name] = SList(block.splitlines()) |
|
84 | 84 | print("Block assigned to '%s'" % name) |
|
85 | 85 | else: |
|
86 | 86 | b = self.preclean_input(block) |
|
87 | 87 | self.shell.user_ns['pasted_block'] = b |
|
88 | 88 | self.shell.using_paste_magics = True |
|
89 | 89 | try: |
|
90 | 90 | self.shell.run_cell(b) |
|
91 | 91 | finally: |
|
92 | 92 | self.shell.using_paste_magics = False |
|
93 | 93 | |
|
94 | 94 | def preclean_input(self, block): |
|
95 | 95 | lines = block.splitlines() |
|
96 | 96 | while lines and not lines[0].strip(): |
|
97 | 97 | lines = lines[1:] |
|
98 | 98 | return strip_email_quotes('\n'.join(lines)) |
|
99 | 99 | |
|
100 | 100 | def rerun_pasted(self, name='pasted_block'): |
|
101 | 101 | """ Rerun a previously pasted command. |
|
102 | 102 | """ |
|
103 | 103 | b = self.shell.user_ns.get(name) |
|
104 | 104 | |
|
105 | 105 | # Sanity checks |
|
106 | 106 | if b is None: |
|
107 | 107 | raise UsageError('No previous pasted block available') |
|
108 | 108 | if not isinstance(b, basestring): |
|
109 | 109 | raise UsageError( |
|
110 | 110 | "Variable 'pasted_block' is not a string, can't execute") |
|
111 | 111 | |
|
112 | 112 | print("Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))) |
|
113 | 113 | self.shell.run_cell(b) |
|
114 | 114 | |
|
115 | 115 | @line_magic |
|
116 | 116 | def autoindent(self, parameter_s = ''): |
|
117 | 117 | """Toggle autoindent on/off (if available).""" |
|
118 | 118 | |
|
119 | 119 | self.shell.set_autoindent() |
|
120 | 120 | print("Automatic indentation is:",['OFF','ON'][self.shell.autoindent]) |
|
121 | 121 | |
|
122 | 122 | @skip_doctest |
|
123 | 123 | @line_magic |
|
124 | 124 | def cpaste(self, parameter_s=''): |
|
125 | 125 | """Paste & execute a pre-formatted code block from clipboard. |
|
126 | 126 | |
|
127 | 127 | You must terminate the block with '--' (two minus-signs) or Ctrl-D |
|
128 | 128 | alone on the line. You can also provide your own sentinel with '%paste |
|
129 | 129 | -s %%' ('%%' is the new sentinel for this operation) |
|
130 | 130 | |
|
131 | 131 | The block is dedented prior to execution to enable execution of method |
|
132 | 132 | definitions. '>' and '+' characters at the beginning of a line are |
|
133 | 133 | ignored, to allow pasting directly from e-mails, diff files and |
|
134 | 134 | doctests (the '...' continuation prompt is also stripped). The |
|
135 | 135 | executed block is also assigned to variable named 'pasted_block' for |
|
136 | 136 | later editing with '%edit pasted_block'. |
|
137 | 137 | |
|
138 | 138 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. |
|
139 | 139 | This assigns the pasted block to variable 'foo' as string, without |
|
140 | 140 | dedenting or executing it (preceding >>> and + is still stripped) |
|
141 | 141 | |
|
142 | 142 | '%cpaste -r' re-executes the block previously entered by cpaste. |
|
143 | 143 | |
|
144 | 144 | Do not be alarmed by garbled output on Windows (it's a readline bug). |
|
145 | 145 | Just press enter and type -- (and press enter again) and the block |
|
146 | 146 | will be what was just pasted. |
|
147 | 147 | |
|
148 | 148 | IPython statements (magics, shell escapes) are not supported (yet). |
|
149 | 149 | |
|
150 | 150 | See also |
|
151 | 151 | -------- |
|
152 | 152 | paste: automatically pull code from clipboard. |
|
153 | 153 | |
|
154 | 154 | Examples |
|
155 | 155 | -------- |
|
156 | 156 | :: |
|
157 | 157 | |
|
158 | 158 | In [8]: %cpaste |
|
159 | 159 | Pasting code; enter '--' alone on the line to stop. |
|
160 | 160 | :>>> a = ["world!", "Hello"] |
|
161 | 161 | :>>> print " ".join(sorted(a)) |
|
162 | 162 | :-- |
|
163 | 163 | Hello world! |
|
164 | 164 | """ |
|
165 | 165 | opts, name = self.parse_options(parameter_s, 'rs:', mode='string') |
|
166 | 166 | if 'r' in opts: |
|
167 | 167 | self.rerun_pasted() |
|
168 | 168 | return |
|
169 | 169 | |
|
170 | 170 | sentinel = opts.get('s', '--') |
|
171 | 171 | block = '\n'.join(get_pasted_lines(sentinel)) |
|
172 | 172 | self.store_or_execute(block, name) |
|
173 | 173 | |
|
174 | 174 | @line_magic |
|
175 | 175 | def paste(self, parameter_s=''): |
|
176 | 176 | """Paste & execute a pre-formatted code block from clipboard. |
|
177 | 177 | |
|
178 | 178 | The text is pulled directly from the clipboard without user |
|
179 | 179 | intervention and printed back on the screen before execution (unless |
|
180 | 180 | the -q flag is given to force quiet mode). |
|
181 | 181 | |
|
182 | 182 | The block is dedented prior to execution to enable execution of method |
|
183 | 183 | definitions. '>' and '+' characters at the beginning of a line are |
|
184 | 184 | ignored, to allow pasting directly from e-mails, diff files and |
|
185 | 185 | doctests (the '...' continuation prompt is also stripped). The |
|
186 | 186 | executed block is also assigned to variable named 'pasted_block' for |
|
187 | 187 | later editing with '%edit pasted_block'. |
|
188 | 188 | |
|
189 | 189 | You can also pass a variable name as an argument, e.g. '%paste foo'. |
|
190 | 190 | This assigns the pasted block to variable 'foo' as string, without |
|
191 | 191 | executing it (preceding >>> and + is still stripped). |
|
192 | 192 | |
|
193 | 193 | Options |
|
194 | 194 | ------- |
|
195 | 195 | |
|
196 | 196 | -r: re-executes the block previously entered by cpaste. |
|
197 | 197 | |
|
198 | 198 | -q: quiet mode: do not echo the pasted text back to the terminal. |
|
199 | 199 | |
|
200 | 200 | IPython statements (magics, shell escapes) are not supported (yet). |
|
201 | 201 | |
|
202 | 202 | See also |
|
203 | 203 | -------- |
|
204 | 204 | cpaste: manually paste code into terminal until you mark its end. |
|
205 | 205 | """ |
|
206 | 206 | opts, name = self.parse_options(parameter_s, 'rq', mode='string') |
|
207 | 207 | if 'r' in opts: |
|
208 | 208 | self.rerun_pasted() |
|
209 | 209 | return |
|
210 | 210 | try: |
|
211 | 211 | block = self.shell.hooks.clipboard_get() |
|
212 | 212 | except TryNext as clipboard_exc: |
|
213 | 213 | message = getattr(clipboard_exc, 'args') |
|
214 | 214 | if message: |
|
215 | 215 | error(message[0]) |
|
216 | 216 | else: |
|
217 | 217 | error('Could not get text from the clipboard.') |
|
218 | 218 | return |
|
219 | 219 | |
|
220 | 220 | # By default, echo back to terminal unless quiet mode is requested |
|
221 | 221 | if 'q' not in opts: |
|
222 | 222 | write = self.shell.write |
|
223 | 223 | write(self.shell.pycolorize(block)) |
|
224 | 224 | if not block.endswith('\n'): |
|
225 | 225 | write('\n') |
|
226 | 226 | write("## -- End pasted text --\n") |
|
227 | 227 | |
|
228 | 228 | self.store_or_execute(block, name) |
|
229 | 229 | |
|
230 | 230 | # Class-level: add a '%cls' magic only on Windows |
|
231 | 231 | if sys.platform == 'win32': |
|
232 | 232 | @line_magic |
|
233 | 233 | def cls(self, s): |
|
234 | 234 | """Clear screen. |
|
235 | 235 | """ |
|
236 | 236 | os.system("cls") |
|
237 | 237 | |
|
238 | 238 | #----------------------------------------------------------------------------- |
|
239 | 239 | # Main class |
|
240 | 240 | #----------------------------------------------------------------------------- |
|
241 | 241 | |
|
242 | 242 | class TerminalInteractiveShell(InteractiveShell): |
|
243 | 243 | |
|
244 | 244 | autoedit_syntax = CBool(False, config=True, |
|
245 | 245 | help="auto editing of files with syntax errors.") |
|
246 | 246 | banner = Unicode('') |
|
247 | 247 | banner1 = Unicode(default_banner, config=True, |
|
248 | 248 | help="""The part of the banner to be printed before the profile""" |
|
249 | 249 | ) |
|
250 | 250 | banner2 = Unicode('', config=True, |
|
251 | 251 | help="""The part of the banner to be printed after the profile""" |
|
252 | 252 | ) |
|
253 | 253 | confirm_exit = CBool(True, config=True, |
|
254 | 254 | help=""" |
|
255 | 255 | Set to confirm when you try to exit IPython with an EOF (Control-D |
|
256 | 256 | in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit', |
|
257 | 257 | you can force a direct exit without any confirmation.""", |
|
258 | 258 | ) |
|
259 | 259 | # This display_banner only controls whether or not self.show_banner() |
|
260 | 260 | # is called when mainloop/interact are called. The default is False |
|
261 | 261 | # because for the terminal based application, the banner behavior |
|
262 | 262 | # is controlled by Global.display_banner, which IPythonApp looks at |
|
263 | 263 | # to determine if *it* should call show_banner() by hand or not. |
|
264 | 264 | display_banner = CBool(False) # This isn't configurable! |
|
265 | 265 | embedded = CBool(False) |
|
266 | 266 | embedded_active = CBool(False) |
|
267 | 267 | editor = Unicode(get_default_editor(), config=True, |
|
268 | 268 | help="Set the editor used by IPython (default to $EDITOR/vi/notepad)." |
|
269 | 269 | ) |
|
270 | 270 | pager = Unicode('less', config=True, |
|
271 | 271 | help="The shell program to be used for paging.") |
|
272 | 272 | |
|
273 | 273 | screen_length = Integer(0, config=True, |
|
274 | 274 | help= |
|
275 | 275 | """Number of lines of your screen, used to control printing of very |
|
276 | 276 | long strings. Strings longer than this number of lines will be sent |
|
277 | 277 | through a pager instead of directly printed. The default value for |
|
278 | 278 | this is 0, which means IPython will auto-detect your screen size every |
|
279 | 279 | time it needs to print certain potentially long strings (this doesn't |
|
280 | 280 | change the behavior of the 'print' keyword, it's only triggered |
|
281 | 281 | internally). If for some reason this isn't working well (it needs |
|
282 | 282 | curses support), specify it yourself. Otherwise don't change the |
|
283 | 283 | default.""", |
|
284 | 284 | ) |
|
285 | 285 | term_title = CBool(False, config=True, |
|
286 | 286 | help="Enable auto setting the terminal title." |
|
287 | 287 | ) |
|
288 | 288 | |
|
289 | 289 | # This `using_paste_magics` is used to detect whether the code is being |
|
290 | 290 | # executed via paste magics functions |
|
291 | 291 | using_paste_magics = CBool(False) |
|
292 | 292 | |
|
293 | 293 | # In the terminal, GUI control is done via PyOS_InputHook |
|
294 | 294 | @staticmethod |
|
295 | 295 | def enable_gui(gui=None, app=None): |
|
296 | 296 | """Switch amongst GUI input hooks by name. |
|
297 | 297 | """ |
|
298 | 298 | # Deferred import |
|
299 | 299 | from IPython.lib.inputhook import enable_gui as real_enable_gui |
|
300 | 300 | try: |
|
301 | 301 | return real_enable_gui(gui, app) |
|
302 | 302 | except ValueError as e: |
|
303 | 303 | raise UsageError("%s" % e) |
|
304 | 304 | |
|
305 | 305 | def __init__(self, config=None, ipython_dir=None, profile_dir=None, |
|
306 | 306 | user_ns=None, user_module=None, custom_exceptions=((),None), |
|
307 | 307 | usage=None, banner1=None, banner2=None, display_banner=None, |
|
308 | 308 | **kwargs): |
|
309 | 309 | |
|
310 | 310 | super(TerminalInteractiveShell, self).__init__( |
|
311 | 311 | config=config, ipython_dir=ipython_dir, profile_dir=profile_dir, user_ns=user_ns, |
|
312 | 312 | user_module=user_module, custom_exceptions=custom_exceptions, |
|
313 | 313 | **kwargs |
|
314 | 314 | ) |
|
315 | 315 | # use os.system instead of utils.process.system by default, |
|
316 | 316 | # because piped system doesn't make sense in the Terminal: |
|
317 | 317 | self.system = self.system_raw |
|
318 | 318 | |
|
319 | 319 | self.init_term_title() |
|
320 | 320 | self.init_usage(usage) |
|
321 | 321 | self.init_banner(banner1, banner2, display_banner) |
|
322 | 322 | |
|
323 | 323 | #------------------------------------------------------------------------- |
|
324 | 324 | # Overrides of init stages |
|
325 | 325 | #------------------------------------------------------------------------- |
|
326 | 326 | |
|
327 | 327 | def init_display_formatter(self): |
|
328 | 328 | super(TerminalInteractiveShell, self).init_display_formatter() |
|
329 | 329 | # terminal only supports plaintext |
|
330 | 330 | self.display_formatter.active_types = ['text/plain'] |
|
331 | 331 | |
|
332 | 332 | #------------------------------------------------------------------------- |
|
333 | 333 | # Things related to the terminal |
|
334 | 334 | #------------------------------------------------------------------------- |
|
335 | 335 | |
|
336 | 336 | @property |
|
337 | 337 | def usable_screen_length(self): |
|
338 | 338 | if self.screen_length == 0: |
|
339 | 339 | return 0 |
|
340 | 340 | else: |
|
341 | 341 | num_lines_bot = self.separate_in.count('\n')+1 |
|
342 | 342 | return self.screen_length - num_lines_bot |
|
343 | 343 | |
|
344 | 344 | def init_term_title(self): |
|
345 | 345 | # Enable or disable the terminal title. |
|
346 | 346 | if self.term_title: |
|
347 | 347 | toggle_set_term_title(True) |
|
348 | 348 | set_term_title('IPython: ' + abbrev_cwd()) |
|
349 | 349 | else: |
|
350 | 350 | toggle_set_term_title(False) |
|
351 | 351 | |
|
352 | 352 | #------------------------------------------------------------------------- |
|
353 | 353 | # Things related to aliases |
|
354 | 354 | #------------------------------------------------------------------------- |
|
355 | 355 | |
|
356 | 356 | def init_alias(self): |
|
357 | 357 | # The parent class defines aliases that can be safely used with any |
|
358 | 358 | # frontend. |
|
359 | 359 | super(TerminalInteractiveShell, self).init_alias() |
|
360 | 360 | |
|
361 | 361 | # Now define aliases that only make sense on the terminal, because they |
|
362 | 362 | # need direct access to the console in a way that we can't emulate in |
|
363 | 363 | # GUI or web frontend |
|
364 | 364 | if os.name == 'posix': |
|
365 | 365 | aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'), |
|
366 | 366 | ('man', 'man')] |
|
367 | 367 | elif os.name == 'nt': |
|
368 | 368 | aliases = [('cls', 'cls')] |
|
369 | 369 | |
|
370 | 370 | |
|
371 | 371 | for name, cmd in aliases: |
|
372 | self.alias_manager.define_alias(name, cmd) | |
|
372 | self.alias_manager.soft_define_alias(name, cmd) | |
|
373 | 373 | |
|
374 | 374 | #------------------------------------------------------------------------- |
|
375 | 375 | # Things related to the banner and usage |
|
376 | 376 | #------------------------------------------------------------------------- |
|
377 | 377 | |
|
378 | 378 | def _banner1_changed(self): |
|
379 | 379 | self.compute_banner() |
|
380 | 380 | |
|
381 | 381 | def _banner2_changed(self): |
|
382 | 382 | self.compute_banner() |
|
383 | 383 | |
|
384 | 384 | def _term_title_changed(self, name, new_value): |
|
385 | 385 | self.init_term_title() |
|
386 | 386 | |
|
387 | 387 | def init_banner(self, banner1, banner2, display_banner): |
|
388 | 388 | if banner1 is not None: |
|
389 | 389 | self.banner1 = banner1 |
|
390 | 390 | if banner2 is not None: |
|
391 | 391 | self.banner2 = banner2 |
|
392 | 392 | if display_banner is not None: |
|
393 | 393 | self.display_banner = display_banner |
|
394 | 394 | self.compute_banner() |
|
395 | 395 | |
|
396 | 396 | def show_banner(self, banner=None): |
|
397 | 397 | if banner is None: |
|
398 | 398 | banner = self.banner |
|
399 | 399 | self.write(banner) |
|
400 | 400 | |
|
401 | 401 | def compute_banner(self): |
|
402 | 402 | self.banner = self.banner1 |
|
403 | 403 | if self.profile and self.profile != 'default': |
|
404 | 404 | self.banner += '\nIPython profile: %s\n' % self.profile |
|
405 | 405 | if self.banner2: |
|
406 | 406 | self.banner += '\n' + self.banner2 |
|
407 | 407 | |
|
408 | 408 | def init_usage(self, usage=None): |
|
409 | 409 | if usage is None: |
|
410 | 410 | self.usage = interactive_usage |
|
411 | 411 | else: |
|
412 | 412 | self.usage = usage |
|
413 | 413 | |
|
414 | 414 | #------------------------------------------------------------------------- |
|
415 | 415 | # Mainloop and code execution logic |
|
416 | 416 | #------------------------------------------------------------------------- |
|
417 | 417 | |
|
418 | 418 | def mainloop(self, display_banner=None): |
|
419 | 419 | """Start the mainloop. |
|
420 | 420 | |
|
421 | 421 | If an optional banner argument is given, it will override the |
|
422 | 422 | internally created default banner. |
|
423 | 423 | """ |
|
424 | 424 | |
|
425 | 425 | with self.builtin_trap, self.display_trap: |
|
426 | 426 | |
|
427 | 427 | while 1: |
|
428 | 428 | try: |
|
429 | 429 | self.interact(display_banner=display_banner) |
|
430 | 430 | #self.interact_with_readline() |
|
431 | 431 | # XXX for testing of a readline-decoupled repl loop, call |
|
432 | 432 | # interact_with_readline above |
|
433 | 433 | break |
|
434 | 434 | except KeyboardInterrupt: |
|
435 | 435 | # this should not be necessary, but KeyboardInterrupt |
|
436 | 436 | # handling seems rather unpredictable... |
|
437 | 437 | self.write("\nKeyboardInterrupt in interact()\n") |
|
438 | 438 | |
|
439 | 439 | def _replace_rlhist_multiline(self, source_raw, hlen_before_cell): |
|
440 | 440 | """Store multiple lines as a single entry in history""" |
|
441 | 441 | |
|
442 | 442 | # do nothing without readline or disabled multiline |
|
443 | 443 | if not self.has_readline or not self.multiline_history: |
|
444 | 444 | return hlen_before_cell |
|
445 | 445 | |
|
446 | 446 | # windows rl has no remove_history_item |
|
447 | 447 | if not hasattr(self.readline, "remove_history_item"): |
|
448 | 448 | return hlen_before_cell |
|
449 | 449 | |
|
450 | 450 | # skip empty cells |
|
451 | 451 | if not source_raw.rstrip(): |
|
452 | 452 | return hlen_before_cell |
|
453 | 453 | |
|
454 | 454 | # nothing changed do nothing, e.g. when rl removes consecutive dups |
|
455 | 455 | hlen = self.readline.get_current_history_length() |
|
456 | 456 | if hlen == hlen_before_cell: |
|
457 | 457 | return hlen_before_cell |
|
458 | 458 | |
|
459 | 459 | for i in range(hlen - hlen_before_cell): |
|
460 | 460 | self.readline.remove_history_item(hlen - i - 1) |
|
461 | 461 | stdin_encoding = get_stream_enc(sys.stdin, 'utf-8') |
|
462 | 462 | self.readline.add_history(py3compat.unicode_to_str(source_raw.rstrip(), |
|
463 | 463 | stdin_encoding)) |
|
464 | 464 | return self.readline.get_current_history_length() |
|
465 | 465 | |
|
466 | 466 | def interact(self, display_banner=None): |
|
467 | 467 | """Closely emulate the interactive Python console.""" |
|
468 | 468 | |
|
469 | 469 | # batch run -> do not interact |
|
470 | 470 | if self.exit_now: |
|
471 | 471 | return |
|
472 | 472 | |
|
473 | 473 | if display_banner is None: |
|
474 | 474 | display_banner = self.display_banner |
|
475 | 475 | |
|
476 | 476 | if isinstance(display_banner, basestring): |
|
477 | 477 | self.show_banner(display_banner) |
|
478 | 478 | elif display_banner: |
|
479 | 479 | self.show_banner() |
|
480 | 480 | |
|
481 | 481 | more = False |
|
482 | 482 | |
|
483 | 483 | if self.has_readline: |
|
484 | 484 | self.readline_startup_hook(self.pre_readline) |
|
485 | 485 | hlen_b4_cell = self.readline.get_current_history_length() |
|
486 | 486 | else: |
|
487 | 487 | hlen_b4_cell = 0 |
|
488 | 488 | # exit_now is set by a call to %Exit or %Quit, through the |
|
489 | 489 | # ask_exit callback. |
|
490 | 490 | |
|
491 | 491 | while not self.exit_now: |
|
492 | 492 | self.hooks.pre_prompt_hook() |
|
493 | 493 | if more: |
|
494 | 494 | try: |
|
495 | 495 | prompt = self.prompt_manager.render('in2') |
|
496 | 496 | except: |
|
497 | 497 | self.showtraceback() |
|
498 | 498 | if self.autoindent: |
|
499 | 499 | self.rl_do_indent = True |
|
500 | 500 | |
|
501 | 501 | else: |
|
502 | 502 | try: |
|
503 | 503 | prompt = self.separate_in + self.prompt_manager.render('in') |
|
504 | 504 | except: |
|
505 | 505 | self.showtraceback() |
|
506 | 506 | try: |
|
507 | 507 | line = self.raw_input(prompt) |
|
508 | 508 | if self.exit_now: |
|
509 | 509 | # quick exit on sys.std[in|out] close |
|
510 | 510 | break |
|
511 | 511 | if self.autoindent: |
|
512 | 512 | self.rl_do_indent = False |
|
513 | 513 | |
|
514 | 514 | except KeyboardInterrupt: |
|
515 | 515 | #double-guard against keyboardinterrupts during kbdint handling |
|
516 | 516 | try: |
|
517 | 517 | self.write('\nKeyboardInterrupt\n') |
|
518 | 518 | source_raw = self.input_splitter.source_raw_reset()[1] |
|
519 | 519 | hlen_b4_cell = \ |
|
520 | 520 | self._replace_rlhist_multiline(source_raw, hlen_b4_cell) |
|
521 | 521 | more = False |
|
522 | 522 | except KeyboardInterrupt: |
|
523 | 523 | pass |
|
524 | 524 | except EOFError: |
|
525 | 525 | if self.autoindent: |
|
526 | 526 | self.rl_do_indent = False |
|
527 | 527 | if self.has_readline: |
|
528 | 528 | self.readline_startup_hook(None) |
|
529 | 529 | self.write('\n') |
|
530 | 530 | self.exit() |
|
531 | 531 | except bdb.BdbQuit: |
|
532 | 532 | warn('The Python debugger has exited with a BdbQuit exception.\n' |
|
533 | 533 | 'Because of how pdb handles the stack, it is impossible\n' |
|
534 | 534 | 'for IPython to properly format this particular exception.\n' |
|
535 | 535 | 'IPython will resume normal operation.') |
|
536 | 536 | except: |
|
537 | 537 | # exceptions here are VERY RARE, but they can be triggered |
|
538 | 538 | # asynchronously by signal handlers, for example. |
|
539 | 539 | self.showtraceback() |
|
540 | 540 | else: |
|
541 | 541 | self.input_splitter.push(line) |
|
542 | 542 | more = self.input_splitter.push_accepts_more() |
|
543 | 543 | if (self.SyntaxTB.last_syntax_error and |
|
544 | 544 | self.autoedit_syntax): |
|
545 | 545 | self.edit_syntax_error() |
|
546 | 546 | if not more: |
|
547 | 547 | source_raw = self.input_splitter.source_raw_reset()[1] |
|
548 | 548 | self.run_cell(source_raw, store_history=True) |
|
549 | 549 | hlen_b4_cell = \ |
|
550 | 550 | self._replace_rlhist_multiline(source_raw, hlen_b4_cell) |
|
551 | 551 | |
|
552 | 552 | # Turn off the exit flag, so the mainloop can be restarted if desired |
|
553 | 553 | self.exit_now = False |
|
554 | 554 | |
|
555 | 555 | def raw_input(self, prompt=''): |
|
556 | 556 | """Write a prompt and read a line. |
|
557 | 557 | |
|
558 | 558 | The returned line does not include the trailing newline. |
|
559 | 559 | When the user enters the EOF key sequence, EOFError is raised. |
|
560 | 560 | |
|
561 | 561 | Optional inputs: |
|
562 | 562 | |
|
563 | 563 | - prompt(''): a string to be printed to prompt the user. |
|
564 | 564 | |
|
565 | 565 | - continue_prompt(False): whether this line is the first one or a |
|
566 | 566 | continuation in a sequence of inputs. |
|
567 | 567 | """ |
|
568 | 568 | # Code run by the user may have modified the readline completer state. |
|
569 | 569 | # We must ensure that our completer is back in place. |
|
570 | 570 | |
|
571 | 571 | if self.has_readline: |
|
572 | 572 | self.set_readline_completer() |
|
573 | 573 | |
|
574 | 574 | # raw_input expects str, but we pass it unicode sometimes |
|
575 | 575 | prompt = py3compat.cast_bytes_py2(prompt) |
|
576 | 576 | |
|
577 | 577 | try: |
|
578 | 578 | line = py3compat.str_to_unicode(self.raw_input_original(prompt)) |
|
579 | 579 | except ValueError: |
|
580 | 580 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" |
|
581 | 581 | " or sys.stdout.close()!\nExiting IPython!\n") |
|
582 | 582 | self.ask_exit() |
|
583 | 583 | return "" |
|
584 | 584 | |
|
585 | 585 | # Try to be reasonably smart about not re-indenting pasted input more |
|
586 | 586 | # than necessary. We do this by trimming out the auto-indent initial |
|
587 | 587 | # spaces, if the user's actual input started itself with whitespace. |
|
588 | 588 | if self.autoindent: |
|
589 | 589 | if num_ini_spaces(line) > self.indent_current_nsp: |
|
590 | 590 | line = line[self.indent_current_nsp:] |
|
591 | 591 | self.indent_current_nsp = 0 |
|
592 | 592 | |
|
593 | 593 | return line |
|
594 | 594 | |
|
595 | 595 | #------------------------------------------------------------------------- |
|
596 | 596 | # Methods to support auto-editing of SyntaxErrors. |
|
597 | 597 | #------------------------------------------------------------------------- |
|
598 | 598 | |
|
599 | 599 | def edit_syntax_error(self): |
|
600 | 600 | """The bottom half of the syntax error handler called in the main loop. |
|
601 | 601 | |
|
602 | 602 | Loop until syntax error is fixed or user cancels. |
|
603 | 603 | """ |
|
604 | 604 | |
|
605 | 605 | while self.SyntaxTB.last_syntax_error: |
|
606 | 606 | # copy and clear last_syntax_error |
|
607 | 607 | err = self.SyntaxTB.clear_err_state() |
|
608 | 608 | if not self._should_recompile(err): |
|
609 | 609 | return |
|
610 | 610 | try: |
|
611 | 611 | # may set last_syntax_error again if a SyntaxError is raised |
|
612 | 612 | self.safe_execfile(err.filename,self.user_ns) |
|
613 | 613 | except: |
|
614 | 614 | self.showtraceback() |
|
615 | 615 | else: |
|
616 | 616 | try: |
|
617 | 617 | f = open(err.filename) |
|
618 | 618 | try: |
|
619 | 619 | # This should be inside a display_trap block and I |
|
620 | 620 | # think it is. |
|
621 | 621 | sys.displayhook(f.read()) |
|
622 | 622 | finally: |
|
623 | 623 | f.close() |
|
624 | 624 | except: |
|
625 | 625 | self.showtraceback() |
|
626 | 626 | |
|
627 | 627 | def _should_recompile(self,e): |
|
628 | 628 | """Utility routine for edit_syntax_error""" |
|
629 | 629 | |
|
630 | 630 | if e.filename in ('<ipython console>','<input>','<string>', |
|
631 | 631 | '<console>','<BackgroundJob compilation>', |
|
632 | 632 | None): |
|
633 | 633 | |
|
634 | 634 | return False |
|
635 | 635 | try: |
|
636 | 636 | if (self.autoedit_syntax and |
|
637 | 637 | not self.ask_yes_no('Return to editor to correct syntax error? ' |
|
638 | 638 | '[Y/n] ','y')): |
|
639 | 639 | return False |
|
640 | 640 | except EOFError: |
|
641 | 641 | return False |
|
642 | 642 | |
|
643 | 643 | def int0(x): |
|
644 | 644 | try: |
|
645 | 645 | return int(x) |
|
646 | 646 | except TypeError: |
|
647 | 647 | return 0 |
|
648 | 648 | # always pass integer line and offset values to editor hook |
|
649 | 649 | try: |
|
650 | 650 | self.hooks.fix_error_editor(e.filename, |
|
651 | 651 | int0(e.lineno),int0(e.offset),e.msg) |
|
652 | 652 | except TryNext: |
|
653 | 653 | warn('Could not open editor') |
|
654 | 654 | return False |
|
655 | 655 | return True |
|
656 | 656 | |
|
657 | 657 | #------------------------------------------------------------------------- |
|
658 | 658 | # Things related to exiting |
|
659 | 659 | #------------------------------------------------------------------------- |
|
660 | 660 | |
|
661 | 661 | def ask_exit(self): |
|
662 | 662 | """ Ask the shell to exit. Can be overiden and used as a callback. """ |
|
663 | 663 | self.exit_now = True |
|
664 | 664 | |
|
665 | 665 | def exit(self): |
|
666 | 666 | """Handle interactive exit. |
|
667 | 667 | |
|
668 | 668 | This method calls the ask_exit callback.""" |
|
669 | 669 | if self.confirm_exit: |
|
670 | 670 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
671 | 671 | self.ask_exit() |
|
672 | 672 | else: |
|
673 | 673 | self.ask_exit() |
|
674 | 674 | |
|
675 | 675 | #------------------------------------------------------------------------- |
|
676 | 676 | # Things related to magics |
|
677 | 677 | #------------------------------------------------------------------------- |
|
678 | 678 | |
|
679 | 679 | def init_magics(self): |
|
680 | 680 | super(TerminalInteractiveShell, self).init_magics() |
|
681 | 681 | self.register_magics(TerminalMagics) |
|
682 | 682 | |
|
683 | 683 | def showindentationerror(self): |
|
684 | 684 | super(TerminalInteractiveShell, self).showindentationerror() |
|
685 | 685 | if not self.using_paste_magics: |
|
686 | 686 | print("If you want to paste code into IPython, try the " |
|
687 | 687 | "%paste and %cpaste magic functions.") |
|
688 | 688 | |
|
689 | 689 | |
|
690 | 690 | InteractiveShellABC.register(TerminalInteractiveShell) |
General Comments 0
You need to be logged in to leave comments.
Login now