Show More
The requested changes are too big and content was truncated. Show full diff
@@ -0,0 +1,64 b'' | |||
|
1 | """ | |
|
2 | Inputhook for running the original asyncio event loop while we're waiting for | |
|
3 | input. | |
|
4 | ||
|
5 | By default, in IPython, we run the prompt with a different asyncio event loop, | |
|
6 | because otherwise we risk that people are freezing the prompt by scheduling bad | |
|
7 | coroutines. E.g., a coroutine that does a while/true and never yield back | |
|
8 | control to the loop. We can't cancel that. | |
|
9 | ||
|
10 | However, sometimes we want the asyncio loop to keep running while waiting for | |
|
11 | a prompt. | |
|
12 | ||
|
13 | The following example will print the numbers from 1 to 10 above the prompt, | |
|
14 | while we are waiting for input. (This works also because we use | |
|
15 | prompt_toolkit`s `patch_stdout`):: | |
|
16 | ||
|
17 | In [1]: import asyncio | |
|
18 | ||
|
19 | In [2]: %gui asyncio | |
|
20 | ||
|
21 | In [3]: async def f(): | |
|
22 | ...: for i in range(10): | |
|
23 | ...: await asyncio.sleep(1) | |
|
24 | ...: print(i) | |
|
25 | ||
|
26 | ||
|
27 | In [4]: asyncio.ensure_future(f()) | |
|
28 | ||
|
29 | """ | |
|
30 | import asyncio | |
|
31 | from prompt_toolkit import __version__ as ptk_version | |
|
32 | ||
|
33 | PTK3 = ptk_version.startswith('3.') | |
|
34 | ||
|
35 | ||
|
36 | # Keep reference to the original asyncio loop, because getting the event loop | |
|
37 | # within the input hook would return the other loop. | |
|
38 | loop = asyncio.get_event_loop() | |
|
39 | ||
|
40 | ||
|
41 | def inputhook(context): | |
|
42 | """ | |
|
43 | Inputhook for asyncio event loop integration. | |
|
44 | """ | |
|
45 | # For prompt_toolkit 3.0, this input hook literally doesn't do anything. | |
|
46 | # The event loop integration here is implemented in `interactiveshell.py` | |
|
47 | # by running the prompt itself in the current asyncio loop. The main reason | |
|
48 | # for this is that nesting asyncio event loops is unreliable. | |
|
49 | if PTK3: | |
|
50 | return | |
|
51 | ||
|
52 | # For prompt_toolkit 2.0, we can run the current asyncio event loop, | |
|
53 | # because prompt_toolkit 2.0 uses a different event loop internally. | |
|
54 | ||
|
55 | def stop(): | |
|
56 | loop.stop() | |
|
57 | ||
|
58 | fileno = context.fileno() | |
|
59 | loop.add_reader(fileno, stop) | |
|
60 | try: | |
|
61 | loop.run_forever() | |
|
62 | finally: | |
|
63 | loop.remove_reader(fileno) | |
|
64 |
|
1 | NO CONTENT: new file 100644 | |
The requested commit or file is too big and content was truncated. Show full diff |
@@ -1,226 +1,228 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """sys.excepthook for IPython itself, leaves a detailed report on disk. |
|
3 | 3 | |
|
4 | 4 | Authors: |
|
5 | 5 | |
|
6 | 6 | * Fernando Perez |
|
7 | 7 | * Brian E. Granger |
|
8 | 8 | """ |
|
9 | 9 | |
|
10 | 10 | #----------------------------------------------------------------------------- |
|
11 | 11 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
12 | 12 | # Copyright (C) 2008-2011 The IPython Development Team |
|
13 | 13 | # |
|
14 | 14 | # Distributed under the terms of the BSD License. The full license is in |
|
15 | 15 | # the file COPYING, distributed as part of this software. |
|
16 | 16 | #----------------------------------------------------------------------------- |
|
17 | 17 | |
|
18 | 18 | #----------------------------------------------------------------------------- |
|
19 | 19 | # Imports |
|
20 | 20 | #----------------------------------------------------------------------------- |
|
21 | 21 | |
|
22 | 22 | import os |
|
23 | 23 | import sys |
|
24 | 24 | import traceback |
|
25 | 25 | from pprint import pformat |
|
26 | 26 | |
|
27 | 27 | from IPython.core import ultratb |
|
28 | 28 | from IPython.core.release import author_email |
|
29 | 29 | from IPython.utils.sysinfo import sys_info |
|
30 | 30 | from IPython.utils.py3compat import input |
|
31 | 31 | |
|
32 | from IPython.core.release import __version__ as version | |
|
33 | ||
|
32 | 34 | #----------------------------------------------------------------------------- |
|
33 | 35 | # Code |
|
34 | 36 | #----------------------------------------------------------------------------- |
|
35 | 37 | |
|
36 | 38 | # Template for the user message. |
|
37 | 39 | _default_message_template = """\ |
|
38 | 40 | Oops, {app_name} crashed. We do our best to make it stable, but... |
|
39 | 41 | |
|
40 | 42 | A crash report was automatically generated with the following information: |
|
41 | 43 | - A verbatim copy of the crash traceback. |
|
42 | 44 | - A copy of your input history during this session. |
|
43 | 45 | - Data on your current {app_name} configuration. |
|
44 | 46 | |
|
45 | 47 | It was left in the file named: |
|
46 | 48 | \t'{crash_report_fname}' |
|
47 | 49 | If you can email this file to the developers, the information in it will help |
|
48 | 50 | them in understanding and correcting the problem. |
|
49 | 51 | |
|
50 | 52 | You can mail it to: {contact_name} at {contact_email} |
|
51 | 53 | with the subject '{app_name} Crash Report'. |
|
52 | 54 | |
|
53 | 55 | If you want to do it now, the following command will work (under Unix): |
|
54 | 56 | mail -s '{app_name} Crash Report' {contact_email} < {crash_report_fname} |
|
55 | 57 | |
|
56 | 58 | In your email, please also include information about: |
|
57 | 59 | - The operating system under which the crash happened: Linux, macOS, Windows, |
|
58 | 60 | other, and which exact version (for example: Ubuntu 16.04.3, macOS 10.13.2, |
|
59 | 61 | Windows 10 Pro), and whether it is 32-bit or 64-bit; |
|
60 | 62 | - How {app_name} was installed: using pip or conda, from GitHub, as part of |
|
61 | 63 | a Docker container, or other, providing more detail if possible; |
|
62 | 64 | - How to reproduce the crash: what exact sequence of instructions can one |
|
63 | 65 | input to get the same crash? Ideally, find a minimal yet complete sequence |
|
64 | 66 | of instructions that yields the crash. |
|
65 | 67 | |
|
66 | 68 | To ensure accurate tracking of this issue, please file a report about it at: |
|
67 | 69 | {bug_tracker} |
|
68 | 70 | """ |
|
69 | 71 | |
|
70 | 72 | _lite_message_template = """ |
|
71 | If you suspect this is an IPython bug, please report it at: | |
|
73 | If you suspect this is an IPython {version} bug, please report it at: | |
|
72 | 74 | https://github.com/ipython/ipython/issues |
|
73 | 75 | or send an email to the mailing list at {email} |
|
74 | 76 | |
|
75 | 77 | You can print a more detailed traceback right now with "%tb", or use "%debug" |
|
76 | 78 | to interactively debug it. |
|
77 | 79 | |
|
78 | 80 | Extra-detailed tracebacks for bug-reporting purposes can be enabled via: |
|
79 | 81 | {config}Application.verbose_crash=True |
|
80 | 82 | """ |
|
81 | 83 | |
|
82 | 84 | |
|
83 | 85 | class CrashHandler(object): |
|
84 | 86 | """Customizable crash handlers for IPython applications. |
|
85 | 87 | |
|
86 | 88 | Instances of this class provide a :meth:`__call__` method which can be |
|
87 | 89 | used as a ``sys.excepthook``. The :meth:`__call__` signature is:: |
|
88 | 90 | |
|
89 | 91 | def __call__(self, etype, evalue, etb) |
|
90 | 92 | """ |
|
91 | 93 | |
|
92 | 94 | message_template = _default_message_template |
|
93 | 95 | section_sep = '\n\n'+'*'*75+'\n\n' |
|
94 | 96 | |
|
95 | 97 | def __init__(self, app, contact_name=None, contact_email=None, |
|
96 | 98 | bug_tracker=None, show_crash_traceback=True, call_pdb=False): |
|
97 | 99 | """Create a new crash handler |
|
98 | 100 | |
|
99 | 101 | Parameters |
|
100 | 102 | ---------- |
|
101 | 103 | app : Application |
|
102 | 104 | A running :class:`Application` instance, which will be queried at |
|
103 | 105 | crash time for internal information. |
|
104 | 106 | |
|
105 | 107 | contact_name : str |
|
106 | 108 | A string with the name of the person to contact. |
|
107 | 109 | |
|
108 | 110 | contact_email : str |
|
109 | 111 | A string with the email address of the contact. |
|
110 | 112 | |
|
111 | 113 | bug_tracker : str |
|
112 | 114 | A string with the URL for your project's bug tracker. |
|
113 | 115 | |
|
114 | 116 | show_crash_traceback : bool |
|
115 | 117 | If false, don't print the crash traceback on stderr, only generate |
|
116 | 118 | the on-disk report |
|
117 | 119 | |
|
118 | 120 | Non-argument instance attributes: |
|
119 | 121 | |
|
120 | 122 | These instances contain some non-argument attributes which allow for |
|
121 | 123 | further customization of the crash handler's behavior. Please see the |
|
122 | 124 | source for further details. |
|
123 | 125 | """ |
|
124 | 126 | self.crash_report_fname = "Crash_report_%s.txt" % app.name |
|
125 | 127 | self.app = app |
|
126 | 128 | self.call_pdb = call_pdb |
|
127 | 129 | #self.call_pdb = True # dbg |
|
128 | 130 | self.show_crash_traceback = show_crash_traceback |
|
129 | 131 | self.info = dict(app_name = app.name, |
|
130 | 132 | contact_name = contact_name, |
|
131 | 133 | contact_email = contact_email, |
|
132 | 134 | bug_tracker = bug_tracker, |
|
133 | 135 | crash_report_fname = self.crash_report_fname) |
|
134 | 136 | |
|
135 | 137 | |
|
136 | 138 | def __call__(self, etype, evalue, etb): |
|
137 | 139 | """Handle an exception, call for compatible with sys.excepthook""" |
|
138 | 140 | |
|
139 | 141 | # do not allow the crash handler to be called twice without reinstalling it |
|
140 | 142 | # this prevents unlikely errors in the crash handling from entering an |
|
141 | 143 | # infinite loop. |
|
142 | 144 | sys.excepthook = sys.__excepthook__ |
|
143 | 145 | |
|
144 | 146 | # Report tracebacks shouldn't use color in general (safer for users) |
|
145 | 147 | color_scheme = 'NoColor' |
|
146 | 148 | |
|
147 | 149 | # Use this ONLY for developer debugging (keep commented out for release) |
|
148 | 150 | #color_scheme = 'Linux' # dbg |
|
149 | 151 | try: |
|
150 | 152 | rptdir = self.app.ipython_dir |
|
151 | 153 | except: |
|
152 | 154 | rptdir = os.getcwd() |
|
153 | 155 | if rptdir is None or not os.path.isdir(rptdir): |
|
154 | 156 | rptdir = os.getcwd() |
|
155 | 157 | report_name = os.path.join(rptdir,self.crash_report_fname) |
|
156 | 158 | # write the report filename into the instance dict so it can get |
|
157 | 159 | # properly expanded out in the user message template |
|
158 | 160 | self.crash_report_fname = report_name |
|
159 | 161 | self.info['crash_report_fname'] = report_name |
|
160 | 162 | TBhandler = ultratb.VerboseTB( |
|
161 | 163 | color_scheme=color_scheme, |
|
162 | 164 | long_header=1, |
|
163 | 165 | call_pdb=self.call_pdb, |
|
164 | 166 | ) |
|
165 | 167 | if self.call_pdb: |
|
166 | 168 | TBhandler(etype,evalue,etb) |
|
167 | 169 | return |
|
168 | 170 | else: |
|
169 | 171 | traceback = TBhandler.text(etype,evalue,etb,context=31) |
|
170 | 172 | |
|
171 | 173 | # print traceback to screen |
|
172 | 174 | if self.show_crash_traceback: |
|
173 | 175 | print(traceback, file=sys.stderr) |
|
174 | 176 | |
|
175 | 177 | # and generate a complete report on disk |
|
176 | 178 | try: |
|
177 | 179 | report = open(report_name,'w') |
|
178 | 180 | except: |
|
179 | 181 | print('Could not create crash report on disk.', file=sys.stderr) |
|
180 | 182 | return |
|
181 | 183 | |
|
182 | 184 | with report: |
|
183 | 185 | # Inform user on stderr of what happened |
|
184 | 186 | print('\n'+'*'*70+'\n', file=sys.stderr) |
|
185 | 187 | print(self.message_template.format(**self.info), file=sys.stderr) |
|
186 | 188 | |
|
187 | 189 | # Construct report on disk |
|
188 | 190 | report.write(self.make_report(traceback)) |
|
189 | 191 | |
|
190 | 192 | input("Hit <Enter> to quit (your terminal may close):") |
|
191 | 193 | |
|
192 | 194 | def make_report(self,traceback): |
|
193 | 195 | """Return a string containing a crash report.""" |
|
194 | 196 | |
|
195 | 197 | sec_sep = self.section_sep |
|
196 | 198 | |
|
197 | 199 | report = ['*'*75+'\n\n'+'IPython post-mortem report\n\n'] |
|
198 | 200 | rpt_add = report.append |
|
199 | 201 | rpt_add(sys_info()) |
|
200 | 202 | |
|
201 | 203 | try: |
|
202 | 204 | config = pformat(self.app.config) |
|
203 | 205 | rpt_add(sec_sep) |
|
204 | 206 | rpt_add('Application name: %s\n\n' % self.app_name) |
|
205 | 207 | rpt_add('Current user configuration structure:\n\n') |
|
206 | 208 | rpt_add(config) |
|
207 | 209 | except: |
|
208 | 210 | pass |
|
209 | 211 | rpt_add(sec_sep+'Crash traceback:\n\n' + traceback) |
|
210 | 212 | |
|
211 | 213 | return ''.join(report) |
|
212 | 214 | |
|
213 | 215 | |
|
214 | 216 | def crash_handler_lite(etype, evalue, tb): |
|
215 | 217 | """a light excepthook, adding a small message to the usual traceback""" |
|
216 | 218 | traceback.print_exception(etype, evalue, tb) |
|
217 | 219 | |
|
218 | 220 | from IPython.core.interactiveshell import InteractiveShell |
|
219 | 221 | if InteractiveShell.initialized(): |
|
220 | 222 | # we are in a Shell environment, give %magic example |
|
221 | 223 | config = "%config " |
|
222 | 224 | else: |
|
223 | 225 | # we are not in a shell, show generic config |
|
224 | 226 | config = "c." |
|
225 | print(_lite_message_template.format(email=author_email, config=config), file=sys.stderr) | |
|
227 | print(_lite_message_template.format(email=author_email, config=config, version=version), file=sys.stderr) | |
|
226 | 228 |
@@ -1,325 +1,325 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Displayhook for IPython. |
|
3 | 3 | |
|
4 | 4 | This defines a callable class that IPython uses for `sys.displayhook`. |
|
5 | 5 | """ |
|
6 | 6 | |
|
7 | 7 | # Copyright (c) IPython Development Team. |
|
8 | 8 | # Distributed under the terms of the Modified BSD License. |
|
9 | 9 | |
|
10 | 10 | import builtins as builtin_mod |
|
11 | 11 | import sys |
|
12 | 12 | import io as _io |
|
13 | 13 | import tokenize |
|
14 | 14 | |
|
15 | 15 | from traitlets.config.configurable import Configurable |
|
16 | 16 | from traitlets import Instance, Float |
|
17 | 17 | from warnings import warn |
|
18 | 18 | |
|
19 | 19 | # TODO: Move the various attributes (cache_size, [others now moved]). Some |
|
20 | 20 | # of these are also attributes of InteractiveShell. They should be on ONE object |
|
21 | 21 | # only and the other objects should ask that one object for their values. |
|
22 | 22 | |
|
23 | 23 | class DisplayHook(Configurable): |
|
24 | 24 | """The custom IPython displayhook to replace sys.displayhook. |
|
25 | 25 | |
|
26 | 26 | This class does many things, but the basic idea is that it is a callable |
|
27 | 27 | that gets called anytime user code returns a value. |
|
28 | 28 | """ |
|
29 | 29 | |
|
30 | 30 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', |
|
31 | 31 | allow_none=True) |
|
32 | 32 | exec_result = Instance('IPython.core.interactiveshell.ExecutionResult', |
|
33 | 33 | allow_none=True) |
|
34 | 34 | cull_fraction = Float(0.2) |
|
35 | 35 | |
|
36 | 36 | def __init__(self, shell=None, cache_size=1000, **kwargs): |
|
37 | 37 | super(DisplayHook, self).__init__(shell=shell, **kwargs) |
|
38 | 38 | cache_size_min = 3 |
|
39 | 39 | if cache_size <= 0: |
|
40 | 40 | self.do_full_cache = 0 |
|
41 | 41 | cache_size = 0 |
|
42 | 42 | elif cache_size < cache_size_min: |
|
43 | 43 | self.do_full_cache = 0 |
|
44 | 44 | cache_size = 0 |
|
45 | 45 | warn('caching was disabled (min value for cache size is %s).' % |
|
46 | 46 | cache_size_min,stacklevel=3) |
|
47 | 47 | else: |
|
48 | 48 | self.do_full_cache = 1 |
|
49 | 49 | |
|
50 | 50 | self.cache_size = cache_size |
|
51 | 51 | |
|
52 | 52 | # we need a reference to the user-level namespace |
|
53 | 53 | self.shell = shell |
|
54 | 54 | |
|
55 | 55 | self._,self.__,self.___ = '','','' |
|
56 | 56 | |
|
57 | 57 | # these are deliberately global: |
|
58 | 58 | to_user_ns = {'_':self._,'__':self.__,'___':self.___} |
|
59 | 59 | self.shell.user_ns.update(to_user_ns) |
|
60 | 60 | |
|
61 | 61 | @property |
|
62 | 62 | def prompt_count(self): |
|
63 | 63 | return self.shell.execution_count |
|
64 | 64 | |
|
65 | 65 | #------------------------------------------------------------------------- |
|
66 | 66 | # Methods used in __call__. Override these methods to modify the behavior |
|
67 | 67 | # of the displayhook. |
|
68 | 68 | #------------------------------------------------------------------------- |
|
69 | 69 | |
|
70 | 70 | def check_for_underscore(self): |
|
71 | 71 | """Check if the user has set the '_' variable by hand.""" |
|
72 | 72 | # If something injected a '_' variable in __builtin__, delete |
|
73 | 73 | # ipython's automatic one so we don't clobber that. gettext() in |
|
74 | 74 | # particular uses _, so we need to stay away from it. |
|
75 | 75 | if '_' in builtin_mod.__dict__: |
|
76 | 76 | try: |
|
77 | 77 | user_value = self.shell.user_ns['_'] |
|
78 | 78 | if user_value is not self._: |
|
79 | 79 | return |
|
80 | 80 | del self.shell.user_ns['_'] |
|
81 | 81 | except KeyError: |
|
82 | 82 | pass |
|
83 | 83 | |
|
84 | 84 | def quiet(self): |
|
85 | 85 | """Should we silence the display hook because of ';'?""" |
|
86 | 86 | # do not print output if input ends in ';' |
|
87 | 87 | |
|
88 | 88 | try: |
|
89 | 89 | cell = self.shell.history_manager.input_hist_parsed[-1] |
|
90 | 90 | except IndexError: |
|
91 | 91 | # some uses of ipshellembed may fail here |
|
92 | 92 | return False |
|
93 | 93 | |
|
94 | 94 | sio = _io.StringIO(cell) |
|
95 | 95 | tokens = list(tokenize.generate_tokens(sio.readline)) |
|
96 | 96 | |
|
97 | 97 | for token in reversed(tokens): |
|
98 | 98 | if token[0] in (tokenize.ENDMARKER, tokenize.NL, tokenize.NEWLINE, tokenize.COMMENT): |
|
99 | 99 | continue |
|
100 | 100 | if (token[0] == tokenize.OP) and (token[1] == ';'): |
|
101 | 101 | return True |
|
102 | 102 | else: |
|
103 | 103 | return False |
|
104 | 104 | |
|
105 | 105 | def start_displayhook(self): |
|
106 | 106 | """Start the displayhook, initializing resources.""" |
|
107 | 107 | pass |
|
108 | 108 | |
|
109 | 109 | def write_output_prompt(self): |
|
110 | 110 | """Write the output prompt. |
|
111 | 111 | |
|
112 | 112 | The default implementation simply writes the prompt to |
|
113 | 113 | ``sys.stdout``. |
|
114 | 114 | """ |
|
115 | 115 | # Use write, not print which adds an extra space. |
|
116 | 116 | sys.stdout.write(self.shell.separate_out) |
|
117 | 117 | outprompt = 'Out[{}]: '.format(self.shell.execution_count) |
|
118 | 118 | if self.do_full_cache: |
|
119 | 119 | sys.stdout.write(outprompt) |
|
120 | 120 | |
|
121 | 121 | def compute_format_data(self, result): |
|
122 | 122 | """Compute format data of the object to be displayed. |
|
123 | 123 | |
|
124 | 124 | The format data is a generalization of the :func:`repr` of an object. |
|
125 | 125 | In the default implementation the format data is a :class:`dict` of |
|
126 | 126 | key value pair where the keys are valid MIME types and the values |
|
127 | 127 | are JSON'able data structure containing the raw data for that MIME |
|
128 | 128 | type. It is up to frontends to determine pick a MIME to to use and |
|
129 | 129 | display that data in an appropriate manner. |
|
130 | 130 | |
|
131 | 131 | This method only computes the format data for the object and should |
|
132 | 132 | NOT actually print or write that to a stream. |
|
133 | 133 | |
|
134 | 134 | Parameters |
|
135 | 135 | ---------- |
|
136 | 136 | result : object |
|
137 | 137 | The Python object passed to the display hook, whose format will be |
|
138 | 138 | computed. |
|
139 | 139 | |
|
140 | 140 | Returns |
|
141 | 141 | ------- |
|
142 | 142 | (format_dict, md_dict) : dict |
|
143 | 143 | format_dict is a :class:`dict` whose keys are valid MIME types and values are |
|
144 | 144 | JSON'able raw data for that MIME type. It is recommended that |
|
145 | 145 | all return values of this should always include the "text/plain" |
|
146 | 146 | MIME type representation of the object. |
|
147 | 147 | md_dict is a :class:`dict` with the same MIME type keys |
|
148 | 148 | of metadata associated with each output. |
|
149 | 149 | |
|
150 | 150 | """ |
|
151 | 151 | return self.shell.display_formatter.format(result) |
|
152 | 152 | |
|
153 | 153 | # This can be set to True by the write_output_prompt method in a subclass |
|
154 | 154 | prompt_end_newline = False |
|
155 | 155 | |
|
156 | def write_format_data(self, format_dict, md_dict=None): | |
|
156 | def write_format_data(self, format_dict, md_dict=None) -> None: | |
|
157 | 157 | """Write the format data dict to the frontend. |
|
158 | 158 | |
|
159 | 159 | This default version of this method simply writes the plain text |
|
160 | 160 | representation of the object to ``sys.stdout``. Subclasses should |
|
161 | 161 | override this method to send the entire `format_dict` to the |
|
162 | 162 | frontends. |
|
163 | 163 | |
|
164 | 164 | Parameters |
|
165 | 165 | ---------- |
|
166 | 166 | format_dict : dict |
|
167 | 167 | The format dict for the object passed to `sys.displayhook`. |
|
168 | 168 | md_dict : dict (optional) |
|
169 | 169 | The metadata dict to be associated with the display data. |
|
170 | 170 | """ |
|
171 | 171 | if 'text/plain' not in format_dict: |
|
172 | 172 | # nothing to do |
|
173 | 173 | return |
|
174 | 174 | # We want to print because we want to always make sure we have a |
|
175 | 175 | # newline, even if all the prompt separators are ''. This is the |
|
176 | 176 | # standard IPython behavior. |
|
177 | 177 | result_repr = format_dict['text/plain'] |
|
178 | 178 | if '\n' in result_repr: |
|
179 | 179 | # So that multi-line strings line up with the left column of |
|
180 | 180 | # the screen, instead of having the output prompt mess up |
|
181 | 181 | # their first line. |
|
182 | 182 | # We use the prompt template instead of the expanded prompt |
|
183 | 183 | # because the expansion may add ANSI escapes that will interfere |
|
184 | 184 | # with our ability to determine whether or not we should add |
|
185 | 185 | # a newline. |
|
186 | 186 | if not self.prompt_end_newline: |
|
187 | 187 | # But avoid extraneous empty lines. |
|
188 | 188 | result_repr = '\n' + result_repr |
|
189 | 189 | |
|
190 | 190 | try: |
|
191 | 191 | print(result_repr) |
|
192 | 192 | except UnicodeEncodeError: |
|
193 | 193 | # If a character is not supported by the terminal encoding replace |
|
194 | 194 | # it with its \u or \x representation |
|
195 | 195 | print(result_repr.encode(sys.stdout.encoding,'backslashreplace').decode(sys.stdout.encoding)) |
|
196 | 196 | |
|
197 | 197 | def update_user_ns(self, result): |
|
198 | 198 | """Update user_ns with various things like _, __, _1, etc.""" |
|
199 | 199 | |
|
200 | 200 | # Avoid recursive reference when displaying _oh/Out |
|
201 | 201 | if self.cache_size and result is not self.shell.user_ns['_oh']: |
|
202 | 202 | if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache: |
|
203 | 203 | self.cull_cache() |
|
204 | 204 | |
|
205 | 205 | # Don't overwrite '_' and friends if '_' is in __builtin__ |
|
206 | 206 | # (otherwise we cause buggy behavior for things like gettext). and |
|
207 | 207 | # do not overwrite _, __ or ___ if one of these has been assigned |
|
208 | 208 | # by the user. |
|
209 | 209 | update_unders = True |
|
210 | 210 | for unders in ['_'*i for i in range(1,4)]: |
|
211 | 211 | if not unders in self.shell.user_ns: |
|
212 | 212 | continue |
|
213 | 213 | if getattr(self, unders) is not self.shell.user_ns.get(unders): |
|
214 | 214 | update_unders = False |
|
215 | 215 | |
|
216 | 216 | self.___ = self.__ |
|
217 | 217 | self.__ = self._ |
|
218 | 218 | self._ = result |
|
219 | 219 | |
|
220 | 220 | if ('_' not in builtin_mod.__dict__) and (update_unders): |
|
221 | 221 | self.shell.push({'_':self._, |
|
222 | 222 | '__':self.__, |
|
223 | 223 | '___':self.___}, interactive=False) |
|
224 | 224 | |
|
225 | 225 | # hackish access to top-level namespace to create _1,_2... dynamically |
|
226 | 226 | to_main = {} |
|
227 | 227 | if self.do_full_cache: |
|
228 | 228 | new_result = '_%s' % self.prompt_count |
|
229 | 229 | to_main[new_result] = result |
|
230 | 230 | self.shell.push(to_main, interactive=False) |
|
231 | 231 | self.shell.user_ns['_oh'][self.prompt_count] = result |
|
232 | 232 | |
|
233 | 233 | def fill_exec_result(self, result): |
|
234 | 234 | if self.exec_result is not None: |
|
235 | 235 | self.exec_result.result = result |
|
236 | 236 | |
|
237 | 237 | def log_output(self, format_dict): |
|
238 | 238 | """Log the output.""" |
|
239 | 239 | if 'text/plain' not in format_dict: |
|
240 | 240 | # nothing to do |
|
241 | 241 | return |
|
242 | 242 | if self.shell.logger.log_output: |
|
243 | 243 | self.shell.logger.log_write(format_dict['text/plain'], 'output') |
|
244 | 244 | self.shell.history_manager.output_hist_reprs[self.prompt_count] = \ |
|
245 | 245 | format_dict['text/plain'] |
|
246 | 246 | |
|
247 | 247 | def finish_displayhook(self): |
|
248 | 248 | """Finish up all displayhook activities.""" |
|
249 | 249 | sys.stdout.write(self.shell.separate_out2) |
|
250 | 250 | sys.stdout.flush() |
|
251 | 251 | |
|
252 | 252 | def __call__(self, result=None): |
|
253 | 253 | """Printing with history cache management. |
|
254 | 254 | |
|
255 | 255 | This is invoked every time the interpreter needs to print, and is |
|
256 | 256 | activated by setting the variable sys.displayhook to it. |
|
257 | 257 | """ |
|
258 | 258 | self.check_for_underscore() |
|
259 | 259 | if result is not None and not self.quiet(): |
|
260 | 260 | self.start_displayhook() |
|
261 | 261 | self.write_output_prompt() |
|
262 | 262 | format_dict, md_dict = self.compute_format_data(result) |
|
263 | 263 | self.update_user_ns(result) |
|
264 | 264 | self.fill_exec_result(result) |
|
265 | 265 | if format_dict: |
|
266 | 266 | self.write_format_data(format_dict, md_dict) |
|
267 | 267 | self.log_output(format_dict) |
|
268 | 268 | self.finish_displayhook() |
|
269 | 269 | |
|
270 | 270 | def cull_cache(self): |
|
271 | 271 | """Output cache is full, cull the oldest entries""" |
|
272 | 272 | oh = self.shell.user_ns.get('_oh', {}) |
|
273 | 273 | sz = len(oh) |
|
274 | 274 | cull_count = max(int(sz * self.cull_fraction), 2) |
|
275 | 275 | warn('Output cache limit (currently {sz} entries) hit.\n' |
|
276 | 276 | 'Flushing oldest {cull_count} entries.'.format(sz=sz, cull_count=cull_count)) |
|
277 | 277 | |
|
278 | 278 | for i, n in enumerate(sorted(oh)): |
|
279 | 279 | if i >= cull_count: |
|
280 | 280 | break |
|
281 | 281 | self.shell.user_ns.pop('_%i' % n, None) |
|
282 | 282 | oh.pop(n, None) |
|
283 | 283 | |
|
284 | 284 | |
|
285 | 285 | def flush(self): |
|
286 | 286 | if not self.do_full_cache: |
|
287 | 287 | raise ValueError("You shouldn't have reached the cache flush " |
|
288 | 288 | "if full caching is not enabled!") |
|
289 | 289 | # delete auto-generated vars from global namespace |
|
290 | 290 | |
|
291 | 291 | for n in range(1,self.prompt_count + 1): |
|
292 | 292 | key = '_'+repr(n) |
|
293 | 293 | try: |
|
294 | 294 | del self.shell.user_ns[key] |
|
295 | 295 | except: pass |
|
296 | 296 | # In some embedded circumstances, the user_ns doesn't have the |
|
297 | 297 | # '_oh' key set up. |
|
298 | 298 | oh = self.shell.user_ns.get('_oh', None) |
|
299 | 299 | if oh is not None: |
|
300 | 300 | oh.clear() |
|
301 | 301 | |
|
302 | 302 | # Release our own references to objects: |
|
303 | 303 | self._, self.__, self.___ = '', '', '' |
|
304 | 304 | |
|
305 | 305 | if '_' not in builtin_mod.__dict__: |
|
306 | 306 | self.shell.user_ns.update({'_':self._,'__':self.__,'___':self.___}) |
|
307 | 307 | import gc |
|
308 | 308 | # TODO: Is this really needed? |
|
309 | 309 | # IronPython blocks here forever |
|
310 | 310 | if sys.platform != "cli": |
|
311 | 311 | gc.collect() |
|
312 | 312 | |
|
313 | 313 | |
|
314 | 314 | class CapturingDisplayHook(object): |
|
315 | 315 | def __init__(self, shell, outputs=None): |
|
316 | 316 | self.shell = shell |
|
317 | 317 | if outputs is None: |
|
318 | 318 | outputs = [] |
|
319 | 319 | self.outputs = outputs |
|
320 | 320 | |
|
321 | 321 | def __call__(self, result=None): |
|
322 | 322 | if result is None: |
|
323 | 323 | return |
|
324 | 324 | format_dict, md_dict = self.shell.display_formatter.format(result) |
|
325 | 325 | self.outputs.append({ 'data': format_dict, 'metadata': md_dict }) |
@@ -1,125 +1,138 b'' | |||
|
1 | 1 | """An interface for publishing rich data to frontends. |
|
2 | 2 | |
|
3 | 3 | There are two components of the display system: |
|
4 | 4 | |
|
5 | 5 | * Display formatters, which take a Python object and compute the |
|
6 | 6 | representation of the object in various formats (text, HTML, SVG, etc.). |
|
7 | 7 | * The display publisher that is used to send the representation data to the |
|
8 | 8 | various frontends. |
|
9 | 9 | |
|
10 | 10 | This module defines the logic display publishing. The display publisher uses |
|
11 | 11 | the ``display_data`` message type that is defined in the IPython messaging |
|
12 | 12 | spec. |
|
13 | 13 | """ |
|
14 | 14 | |
|
15 | 15 | # Copyright (c) IPython Development Team. |
|
16 | 16 | # Distributed under the terms of the Modified BSD License. |
|
17 | 17 | |
|
18 | 18 | |
|
19 | 19 | import sys |
|
20 | 20 | |
|
21 | 21 | from traitlets.config.configurable import Configurable |
|
22 | from traitlets import List | |
|
22 | from traitlets import List, Dict | |
|
23 | 23 | |
|
24 | 24 | # This used to be defined here - it is imported for backwards compatibility |
|
25 | 25 | from .display import publish_display_data |
|
26 | 26 | |
|
27 | 27 | #----------------------------------------------------------------------------- |
|
28 | 28 | # Main payload class |
|
29 | 29 | #----------------------------------------------------------------------------- |
|
30 | 30 | |
|
31 | ||
|
31 | 32 | class DisplayPublisher(Configurable): |
|
32 | 33 | """A traited class that publishes display data to frontends. |
|
33 | 34 | |
|
34 | 35 | Instances of this class are created by the main IPython object and should |
|
35 | 36 | be accessed there. |
|
36 | 37 | """ |
|
37 | 38 | |
|
39 | def __init__(self, shell=None, *args, **kwargs): | |
|
40 | self.shell = shell | |
|
41 | super().__init__(*args, **kwargs) | |
|
42 | ||
|
38 | 43 | def _validate_data(self, data, metadata=None): |
|
39 | 44 | """Validate the display data. |
|
40 | 45 | |
|
41 | 46 | Parameters |
|
42 | 47 | ---------- |
|
43 | 48 | data : dict |
|
44 | 49 | The formata data dictionary. |
|
45 | 50 | metadata : dict |
|
46 | 51 | Any metadata for the data. |
|
47 | 52 | """ |
|
48 | 53 | |
|
49 | 54 | if not isinstance(data, dict): |
|
50 | 55 | raise TypeError('data must be a dict, got: %r' % data) |
|
51 | 56 | if metadata is not None: |
|
52 | 57 | if not isinstance(metadata, dict): |
|
53 | 58 | raise TypeError('metadata must be a dict, got: %r' % data) |
|
54 | 59 | |
|
55 | 60 | # use * to indicate transient, update are keyword-only |
|
56 | def publish(self, data, metadata=None, source=None, *, transient=None, update=False, **kwargs): | |
|
61 | def publish(self, data, metadata=None, source=None, *, transient=None, update=False, **kwargs) -> None: | |
|
57 | 62 | """Publish data and metadata to all frontends. |
|
58 | 63 | |
|
59 | 64 | See the ``display_data`` message in the messaging documentation for |
|
60 | 65 | more details about this message type. |
|
61 | 66 | |
|
62 | 67 | The following MIME types are currently implemented: |
|
63 | 68 | |
|
64 | 69 | * text/plain |
|
65 | 70 | * text/html |
|
66 | 71 | * text/markdown |
|
67 | 72 | * text/latex |
|
68 | 73 | * application/json |
|
69 | 74 | * application/javascript |
|
70 | 75 | * image/png |
|
71 | 76 | * image/jpeg |
|
72 | 77 | * image/svg+xml |
|
73 | 78 | |
|
74 | 79 | Parameters |
|
75 | 80 | ---------- |
|
76 | 81 | data : dict |
|
77 | 82 | A dictionary having keys that are valid MIME types (like |
|
78 | 83 | 'text/plain' or 'image/svg+xml') and values that are the data for |
|
79 | 84 | that MIME type. The data itself must be a JSON'able data |
|
80 | 85 | structure. Minimally all data should have the 'text/plain' data, |
|
81 | 86 | which can be displayed by all frontends. If more than the plain |
|
82 | 87 | text is given, it is up to the frontend to decide which |
|
83 | 88 | representation to use. |
|
84 | 89 | metadata : dict |
|
85 | 90 | A dictionary for metadata related to the data. This can contain |
|
86 | 91 | arbitrary key, value pairs that frontends can use to interpret |
|
87 | 92 | the data. Metadata specific to each mime-type can be specified |
|
88 | 93 | in the metadata dict with the same mime-type keys as |
|
89 | 94 | the data itself. |
|
90 | 95 | source : str, deprecated |
|
91 | 96 | Unused. |
|
92 | 97 | transient: dict, keyword-only |
|
93 | 98 | A dictionary for transient data. |
|
94 | 99 | Data in this dictionary should not be persisted as part of saving this output. |
|
95 | 100 | Examples include 'display_id'. |
|
96 | 101 | update: bool, keyword-only, default: False |
|
97 | 102 | If True, only update existing outputs with the same display_id, |
|
98 | 103 | rather than creating a new output. |
|
99 | 104 | """ |
|
100 | 105 | |
|
101 | # The default is to simply write the plain text data using sys.stdout. | |
|
106 | handlers = {} | |
|
107 | if self.shell is not None: | |
|
108 | handlers = getattr(self.shell, 'mime_renderers', {}) | |
|
109 | ||
|
110 | for mime, handler in handlers.items(): | |
|
111 | if mime in data: | |
|
112 | handler(data[mime], metadata.get(mime, None)) | |
|
113 | return | |
|
114 | ||
|
102 | 115 | if 'text/plain' in data: |
|
103 | 116 | print(data['text/plain']) |
|
104 | 117 | |
|
105 | 118 | def clear_output(self, wait=False): |
|
106 | 119 | """Clear the output of the cell receiving output.""" |
|
107 | 120 | print('\033[2K\r', end='') |
|
108 | 121 | sys.stdout.flush() |
|
109 | 122 | print('\033[2K\r', end='') |
|
110 | 123 | sys.stderr.flush() |
|
111 | 124 | |
|
112 | 125 | |
|
113 | 126 | class CapturingDisplayPublisher(DisplayPublisher): |
|
114 | 127 | """A DisplayPublisher that stores""" |
|
115 | 128 | outputs = List() |
|
116 | 129 | |
|
117 | 130 | def publish(self, data, metadata=None, source=None, *, transient=None, update=False): |
|
118 | 131 | self.outputs.append({'data':data, 'metadata':metadata, |
|
119 | 132 | 'transient':transient, 'update':update}) |
|
120 | 133 | |
|
121 | 134 | def clear_output(self, wait=False): |
|
122 | 135 | super(CapturingDisplayPublisher, self).clear_output(wait) |
|
123 | 136 | |
|
124 | 137 | # empty the list, *do not* reassign a new list |
|
125 | 138 | self.outputs.clear() |
@@ -1,3701 +1,3701 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Main IPython class.""" |
|
3 | 3 | |
|
4 | 4 | #----------------------------------------------------------------------------- |
|
5 | 5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> |
|
6 | 6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
7 | 7 | # Copyright (C) 2008-2011 The IPython Development Team |
|
8 | 8 | # |
|
9 | 9 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | 10 | # the file COPYING, distributed as part of this software. |
|
11 | 11 | #----------------------------------------------------------------------------- |
|
12 | 12 | |
|
13 | 13 | |
|
14 | 14 | import abc |
|
15 | 15 | import ast |
|
16 | 16 | import asyncio |
|
17 | 17 | import atexit |
|
18 | 18 | import builtins as builtin_mod |
|
19 | 19 | import functools |
|
20 | 20 | import inspect |
|
21 | 21 | import os |
|
22 | 22 | import re |
|
23 | 23 | import runpy |
|
24 | 24 | import sys |
|
25 | 25 | import tempfile |
|
26 | 26 | import traceback |
|
27 | 27 | import types |
|
28 | 28 | import subprocess |
|
29 | 29 | import warnings |
|
30 | 30 | from io import open as io_open |
|
31 | 31 | |
|
32 | 32 | from pickleshare import PickleShareDB |
|
33 | 33 | |
|
34 | 34 | from traitlets.config.configurable import SingletonConfigurable |
|
35 | 35 | from traitlets.utils.importstring import import_item |
|
36 | 36 | from IPython.core import oinspect |
|
37 | 37 | from IPython.core import magic |
|
38 | 38 | from IPython.core import page |
|
39 | 39 | from IPython.core import prefilter |
|
40 | 40 | from IPython.core import ultratb |
|
41 | 41 | from IPython.core.alias import Alias, AliasManager |
|
42 | 42 | from IPython.core.autocall import ExitAutocall |
|
43 | 43 | from IPython.core.builtin_trap import BuiltinTrap |
|
44 | 44 | from IPython.core.events import EventManager, available_events |
|
45 | 45 | from IPython.core.compilerop import CachingCompiler, check_linecache_ipython |
|
46 | 46 | from IPython.core.debugger import Pdb |
|
47 | 47 | from IPython.core.display_trap import DisplayTrap |
|
48 | 48 | from IPython.core.displayhook import DisplayHook |
|
49 | 49 | from IPython.core.displaypub import DisplayPublisher |
|
50 | 50 | from IPython.core.error import InputRejected, UsageError |
|
51 | 51 | from IPython.core.extensions import ExtensionManager |
|
52 | 52 | from IPython.core.formatters import DisplayFormatter |
|
53 | 53 | from IPython.core.history import HistoryManager |
|
54 | 54 | from IPython.core.inputtransformer2 import ESC_MAGIC, ESC_MAGIC2 |
|
55 | 55 | from IPython.core.logger import Logger |
|
56 | 56 | from IPython.core.macro import Macro |
|
57 | 57 | from IPython.core.payload import PayloadManager |
|
58 | 58 | from IPython.core.prefilter import PrefilterManager |
|
59 | 59 | from IPython.core.profiledir import ProfileDir |
|
60 | 60 | from IPython.core.usage import default_banner |
|
61 | 61 | from IPython.display import display |
|
62 | 62 | from IPython.testing.skipdoctest import skip_doctest |
|
63 | 63 | from IPython.utils import PyColorize |
|
64 | 64 | from IPython.utils import io |
|
65 | 65 | from IPython.utils import py3compat |
|
66 | 66 | from IPython.utils import openpy |
|
67 | 67 | from IPython.utils.decorators import undoc |
|
68 | 68 | from IPython.utils.io import ask_yes_no |
|
69 | 69 | from IPython.utils.ipstruct import Struct |
|
70 | 70 | from IPython.paths import get_ipython_dir |
|
71 | 71 | from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists |
|
72 | 72 | from IPython.utils.process import system, getoutput |
|
73 | 73 | from IPython.utils.strdispatch import StrDispatch |
|
74 | 74 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
75 | 75 | from IPython.utils.text import format_screen, LSString, SList, DollarFormatter |
|
76 | 76 | from IPython.utils.tempdir import TemporaryDirectory |
|
77 | 77 | from traitlets import ( |
|
78 | 78 | Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type, |
|
79 | 79 | observe, default, validate, Any |
|
80 | 80 | ) |
|
81 | 81 | from warnings import warn |
|
82 | 82 | from logging import error |
|
83 | 83 | import IPython.core.hooks |
|
84 | 84 | |
|
85 | 85 | from typing import List as ListType, Tuple |
|
86 | 86 | from ast import AST |
|
87 | 87 | |
|
88 | 88 | # NoOpContext is deprecated, but ipykernel imports it from here. |
|
89 | 89 | # See https://github.com/ipython/ipykernel/issues/157 |
|
90 | 90 | from IPython.utils.contexts import NoOpContext |
|
91 | 91 | |
|
92 | 92 | try: |
|
93 | 93 | import docrepr.sphinxify as sphx |
|
94 | 94 | |
|
95 | 95 | def sphinxify(doc): |
|
96 | 96 | with TemporaryDirectory() as dirname: |
|
97 | 97 | return { |
|
98 | 98 | 'text/html': sphx.sphinxify(doc, dirname), |
|
99 | 99 | 'text/plain': doc |
|
100 | 100 | } |
|
101 | 101 | except ImportError: |
|
102 | 102 | sphinxify = None |
|
103 | 103 | |
|
104 | 104 | |
|
105 | 105 | class ProvisionalWarning(DeprecationWarning): |
|
106 | 106 | """ |
|
107 | 107 | Warning class for unstable features |
|
108 | 108 | """ |
|
109 | 109 | pass |
|
110 | 110 | |
|
111 | 111 | if sys.version_info > (3,8): |
|
112 | 112 | from ast import Module |
|
113 | 113 | else : |
|
114 | 114 | # mock the new API, ignore second argument |
|
115 | 115 | # see https://github.com/ipython/ipython/issues/11590 |
|
116 | 116 | from ast import Module as OriginalModule |
|
117 | 117 | Module = lambda nodelist, type_ignores: OriginalModule(nodelist) |
|
118 | 118 | |
|
119 | 119 | if sys.version_info > (3,6): |
|
120 | 120 | _assign_nodes = (ast.AugAssign, ast.AnnAssign, ast.Assign) |
|
121 | 121 | _single_targets_nodes = (ast.AugAssign, ast.AnnAssign) |
|
122 | 122 | else: |
|
123 | 123 | _assign_nodes = (ast.AugAssign, ast.Assign ) |
|
124 | 124 | _single_targets_nodes = (ast.AugAssign, ) |
|
125 | 125 | |
|
126 | 126 | #----------------------------------------------------------------------------- |
|
127 | 127 | # Await Helpers |
|
128 | 128 | #----------------------------------------------------------------------------- |
|
129 | 129 | |
|
130 | 130 | def removed_co_newlocals(function:types.FunctionType) -> types.FunctionType: |
|
131 | 131 | """Return a function that do not create a new local scope. |
|
132 | 132 | |
|
133 | 133 | Given a function, create a clone of this function where the co_newlocal flag |
|
134 | 134 | has been removed, making this function code actually run in the sourounding |
|
135 | 135 | scope. |
|
136 | 136 | |
|
137 | 137 | We need this in order to run asynchronous code in user level namespace. |
|
138 | 138 | """ |
|
139 | 139 | from types import CodeType, FunctionType |
|
140 | 140 | CO_NEWLOCALS = 0x0002 |
|
141 | 141 | code = function.__code__ |
|
142 | 142 | new_co_flags = code.co_flags & ~CO_NEWLOCALS |
|
143 | 143 | if sys.version_info > (3, 8, 0, 'alpha', 3): |
|
144 | 144 | new_code = code.replace(co_flags=new_co_flags) |
|
145 | 145 | else: |
|
146 | 146 | new_code = CodeType( |
|
147 | 147 | code.co_argcount, |
|
148 | 148 | code.co_kwonlyargcount, |
|
149 | 149 | code.co_nlocals, |
|
150 | 150 | code.co_stacksize, |
|
151 | 151 | new_co_flags, |
|
152 | 152 | code.co_code, |
|
153 | 153 | code.co_consts, |
|
154 | 154 | code.co_names, |
|
155 | 155 | code.co_varnames, |
|
156 | 156 | code.co_filename, |
|
157 | 157 | code.co_name, |
|
158 | 158 | code.co_firstlineno, |
|
159 | 159 | code.co_lnotab, |
|
160 | 160 | code.co_freevars, |
|
161 | 161 | code.co_cellvars |
|
162 | 162 | ) |
|
163 | 163 | return FunctionType(new_code, globals(), function.__name__, function.__defaults__) |
|
164 | 164 | |
|
165 | 165 | |
|
166 | 166 | # we still need to run things using the asyncio eventloop, but there is no |
|
167 | 167 | # async integration |
|
168 | 168 | from .async_helpers import (_asyncio_runner, _asyncify, _pseudo_sync_runner) |
|
169 | 169 | from .async_helpers import _curio_runner, _trio_runner, _should_be_async |
|
170 | 170 | |
|
171 | 171 | |
|
172 | 172 | def _ast_asyncify(cell:str, wrapper_name:str) -> ast.Module: |
|
173 | 173 | """ |
|
174 | 174 | Parse a cell with top-level await and modify the AST to be able to run it later. |
|
175 | 175 | |
|
176 | 176 | Parameter |
|
177 | 177 | --------- |
|
178 | 178 | |
|
179 | 179 | cell: str |
|
180 | 180 | The code cell to asyncronify |
|
181 | 181 | wrapper_name: str |
|
182 | 182 | The name of the function to be used to wrap the passed `cell`. It is |
|
183 | 183 | advised to **not** use a python identifier in order to not pollute the |
|
184 | 184 | global namespace in which the function will be ran. |
|
185 | 185 | |
|
186 | 186 | Return |
|
187 | 187 | ------ |
|
188 | 188 | |
|
189 | 189 | A module object AST containing **one** function named `wrapper_name`. |
|
190 | 190 | |
|
191 | 191 | The given code is wrapped in a async-def function, parsed into an AST, and |
|
192 | 192 | the resulting function definition AST is modified to return the last |
|
193 | 193 | expression. |
|
194 | 194 | |
|
195 | 195 | The last expression or await node is moved into a return statement at the |
|
196 | 196 | end of the function, and removed from its original location. If the last |
|
197 | 197 | node is not Expr or Await nothing is done. |
|
198 | 198 | |
|
199 | 199 | The function `__code__` will need to be later modified (by |
|
200 | 200 | ``removed_co_newlocals``) in a subsequent step to not create new `locals()` |
|
201 | 201 | meaning that the local and global scope are the same, ie as if the body of |
|
202 | 202 | the function was at module level. |
|
203 | 203 | |
|
204 | 204 | Lastly a call to `locals()` is made just before the last expression of the |
|
205 | 205 | function, or just after the last assignment or statement to make sure the |
|
206 | 206 | global dict is updated as python function work with a local fast cache which |
|
207 | 207 | is updated only on `local()` calls. |
|
208 | 208 | """ |
|
209 | 209 | |
|
210 | 210 | from ast import Expr, Await, Return |
|
211 | 211 | if sys.version_info >= (3,8): |
|
212 | 212 | return ast.parse(cell) |
|
213 | 213 | tree = ast.parse(_asyncify(cell)) |
|
214 | 214 | |
|
215 | 215 | function_def = tree.body[0] |
|
216 | 216 | function_def.name = wrapper_name |
|
217 | 217 | try_block = function_def.body[0] |
|
218 | 218 | lastexpr = try_block.body[-1] |
|
219 | 219 | if isinstance(lastexpr, (Expr, Await)): |
|
220 | 220 | try_block.body[-1] = Return(lastexpr.value) |
|
221 | 221 | ast.fix_missing_locations(tree) |
|
222 | 222 | return tree |
|
223 | 223 | #----------------------------------------------------------------------------- |
|
224 | 224 | # Globals |
|
225 | 225 | #----------------------------------------------------------------------------- |
|
226 | 226 | |
|
227 | 227 | # compiled regexps for autoindent management |
|
228 | 228 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
229 | 229 | |
|
230 | 230 | #----------------------------------------------------------------------------- |
|
231 | 231 | # Utilities |
|
232 | 232 | #----------------------------------------------------------------------------- |
|
233 | 233 | |
|
234 | 234 | @undoc |
|
235 | 235 | def softspace(file, newvalue): |
|
236 | 236 | """Copied from code.py, to remove the dependency""" |
|
237 | 237 | |
|
238 | 238 | oldvalue = 0 |
|
239 | 239 | try: |
|
240 | 240 | oldvalue = file.softspace |
|
241 | 241 | except AttributeError: |
|
242 | 242 | pass |
|
243 | 243 | try: |
|
244 | 244 | file.softspace = newvalue |
|
245 | 245 | except (AttributeError, TypeError): |
|
246 | 246 | # "attribute-less object" or "read-only attributes" |
|
247 | 247 | pass |
|
248 | 248 | return oldvalue |
|
249 | 249 | |
|
250 | 250 | @undoc |
|
251 | 251 | def no_op(*a, **kw): |
|
252 | 252 | pass |
|
253 | 253 | |
|
254 | 254 | |
|
255 | 255 | class SpaceInInput(Exception): pass |
|
256 | 256 | |
|
257 | 257 | |
|
258 | 258 | def get_default_colors(): |
|
259 | 259 | "DEPRECATED" |
|
260 | 260 | warn('get_default_color is deprecated since IPython 5.0, and returns `Neutral` on all platforms.', |
|
261 | 261 | DeprecationWarning, stacklevel=2) |
|
262 | 262 | return 'Neutral' |
|
263 | 263 | |
|
264 | 264 | |
|
265 | 265 | class SeparateUnicode(Unicode): |
|
266 | 266 | r"""A Unicode subclass to validate separate_in, separate_out, etc. |
|
267 | 267 | |
|
268 | 268 | This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``. |
|
269 | 269 | """ |
|
270 | 270 | |
|
271 | 271 | def validate(self, obj, value): |
|
272 | 272 | if value == '0': value = '' |
|
273 | 273 | value = value.replace('\\n','\n') |
|
274 | 274 | return super(SeparateUnicode, self).validate(obj, value) |
|
275 | 275 | |
|
276 | 276 | |
|
277 | 277 | @undoc |
|
278 | 278 | class DummyMod(object): |
|
279 | 279 | """A dummy module used for IPython's interactive module when |
|
280 | 280 | a namespace must be assigned to the module's __dict__.""" |
|
281 | 281 | __spec__ = None |
|
282 | 282 | |
|
283 | 283 | |
|
284 | 284 | class ExecutionInfo(object): |
|
285 | 285 | """The arguments used for a call to :meth:`InteractiveShell.run_cell` |
|
286 | 286 | |
|
287 | 287 | Stores information about what is going to happen. |
|
288 | 288 | """ |
|
289 | 289 | raw_cell = None |
|
290 | 290 | store_history = False |
|
291 | 291 | silent = False |
|
292 | 292 | shell_futures = True |
|
293 | 293 | |
|
294 | 294 | def __init__(self, raw_cell, store_history, silent, shell_futures): |
|
295 | 295 | self.raw_cell = raw_cell |
|
296 | 296 | self.store_history = store_history |
|
297 | 297 | self.silent = silent |
|
298 | 298 | self.shell_futures = shell_futures |
|
299 | 299 | |
|
300 | 300 | def __repr__(self): |
|
301 | 301 | name = self.__class__.__qualname__ |
|
302 | 302 | raw_cell = ((self.raw_cell[:50] + '..') |
|
303 | 303 | if len(self.raw_cell) > 50 else self.raw_cell) |
|
304 | 304 | return '<%s object at %x, raw_cell="%s" store_history=%s silent=%s shell_futures=%s>' %\ |
|
305 | 305 | (name, id(self), raw_cell, self.store_history, self.silent, self.shell_futures) |
|
306 | 306 | |
|
307 | 307 | |
|
308 | 308 | class ExecutionResult(object): |
|
309 | 309 | """The result of a call to :meth:`InteractiveShell.run_cell` |
|
310 | 310 | |
|
311 | 311 | Stores information about what took place. |
|
312 | 312 | """ |
|
313 | 313 | execution_count = None |
|
314 | 314 | error_before_exec = None |
|
315 | 315 | error_in_exec = None |
|
316 | 316 | info = None |
|
317 | 317 | result = None |
|
318 | 318 | |
|
319 | 319 | def __init__(self, info): |
|
320 | 320 | self.info = info |
|
321 | 321 | |
|
322 | 322 | @property |
|
323 | 323 | def success(self): |
|
324 | 324 | return (self.error_before_exec is None) and (self.error_in_exec is None) |
|
325 | 325 | |
|
326 | 326 | def raise_error(self): |
|
327 | 327 | """Reraises error if `success` is `False`, otherwise does nothing""" |
|
328 | 328 | if self.error_before_exec is not None: |
|
329 | 329 | raise self.error_before_exec |
|
330 | 330 | if self.error_in_exec is not None: |
|
331 | 331 | raise self.error_in_exec |
|
332 | 332 | |
|
333 | 333 | def __repr__(self): |
|
334 | 334 | name = self.__class__.__qualname__ |
|
335 | 335 | return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s info=%s result=%s>' %\ |
|
336 | 336 | (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.info), repr(self.result)) |
|
337 | 337 | |
|
338 | 338 | |
|
339 | 339 | class InteractiveShell(SingletonConfigurable): |
|
340 | 340 | """An enhanced, interactive shell for Python.""" |
|
341 | 341 | |
|
342 | 342 | _instance = None |
|
343 | 343 | |
|
344 | 344 | ast_transformers = List([], help= |
|
345 | 345 | """ |
|
346 | 346 | A list of ast.NodeTransformer subclass instances, which will be applied |
|
347 | 347 | to user input before code is run. |
|
348 | 348 | """ |
|
349 | 349 | ).tag(config=True) |
|
350 | 350 | |
|
351 | 351 | autocall = Enum((0,1,2), default_value=0, help= |
|
352 | 352 | """ |
|
353 | 353 | Make IPython automatically call any callable object even if you didn't |
|
354 | 354 | type explicit parentheses. For example, 'str 43' becomes 'str(43)' |
|
355 | 355 | automatically. The value can be '0' to disable the feature, '1' for |
|
356 | 356 | 'smart' autocall, where it is not applied if there are no more |
|
357 | 357 | arguments on the line, and '2' for 'full' autocall, where all callable |
|
358 | 358 | objects are automatically called (even if no arguments are present). |
|
359 | 359 | """ |
|
360 | 360 | ).tag(config=True) |
|
361 | 361 | |
|
362 | 362 | autoindent = Bool(True, help= |
|
363 | 363 | """ |
|
364 | 364 | Autoindent IPython code entered interactively. |
|
365 | 365 | """ |
|
366 | 366 | ).tag(config=True) |
|
367 | 367 | |
|
368 | 368 | autoawait = Bool(True, help= |
|
369 | 369 | """ |
|
370 | 370 | Automatically run await statement in the top level repl. |
|
371 | 371 | """ |
|
372 | 372 | ).tag(config=True) |
|
373 | 373 | |
|
374 | 374 | loop_runner_map ={ |
|
375 | 375 | 'asyncio':(_asyncio_runner, True), |
|
376 | 376 | 'curio':(_curio_runner, True), |
|
377 | 377 | 'trio':(_trio_runner, True), |
|
378 | 378 | 'sync': (_pseudo_sync_runner, False) |
|
379 | 379 | } |
|
380 | 380 | |
|
381 | 381 | loop_runner = Any(default_value="IPython.core.interactiveshell._asyncio_runner", |
|
382 | 382 | allow_none=True, |
|
383 | 383 | help="""Select the loop runner that will be used to execute top-level asynchronous code""" |
|
384 | 384 | ).tag(config=True) |
|
385 | 385 | |
|
386 | 386 | @default('loop_runner') |
|
387 | 387 | def _default_loop_runner(self): |
|
388 | 388 | return import_item("IPython.core.interactiveshell._asyncio_runner") |
|
389 | 389 | |
|
390 | 390 | @validate('loop_runner') |
|
391 | 391 | def _import_runner(self, proposal): |
|
392 | 392 | if isinstance(proposal.value, str): |
|
393 | 393 | if proposal.value in self.loop_runner_map: |
|
394 | 394 | runner, autoawait = self.loop_runner_map[proposal.value] |
|
395 | 395 | self.autoawait = autoawait |
|
396 | 396 | return runner |
|
397 | 397 | runner = import_item(proposal.value) |
|
398 | 398 | if not callable(runner): |
|
399 | 399 | raise ValueError('loop_runner must be callable') |
|
400 | 400 | return runner |
|
401 | 401 | if not callable(proposal.value): |
|
402 | 402 | raise ValueError('loop_runner must be callable') |
|
403 | 403 | return proposal.value |
|
404 | 404 | |
|
405 | 405 | automagic = Bool(True, help= |
|
406 | 406 | """ |
|
407 | 407 | Enable magic commands to be called without the leading %. |
|
408 | 408 | """ |
|
409 | 409 | ).tag(config=True) |
|
410 | 410 | |
|
411 | 411 | banner1 = Unicode(default_banner, |
|
412 | 412 | help="""The part of the banner to be printed before the profile""" |
|
413 | 413 | ).tag(config=True) |
|
414 | 414 | banner2 = Unicode('', |
|
415 | 415 | help="""The part of the banner to be printed after the profile""" |
|
416 | 416 | ).tag(config=True) |
|
417 | 417 | |
|
418 | 418 | cache_size = Integer(1000, help= |
|
419 | 419 | """ |
|
420 | 420 | Set the size of the output cache. The default is 1000, you can |
|
421 | 421 | change it permanently in your config file. Setting it to 0 completely |
|
422 | 422 | disables the caching system, and the minimum value accepted is 3 (if |
|
423 | 423 | you provide a value less than 3, it is reset to 0 and a warning is |
|
424 | 424 | issued). This limit is defined because otherwise you'll spend more |
|
425 | 425 | time re-flushing a too small cache than working |
|
426 | 426 | """ |
|
427 | 427 | ).tag(config=True) |
|
428 | 428 | color_info = Bool(True, help= |
|
429 | 429 | """ |
|
430 | 430 | Use colors for displaying information about objects. Because this |
|
431 | 431 | information is passed through a pager (like 'less'), and some pagers |
|
432 | 432 | get confused with color codes, this capability can be turned off. |
|
433 | 433 | """ |
|
434 | 434 | ).tag(config=True) |
|
435 | 435 | colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'), |
|
436 | 436 | default_value='Neutral', |
|
437 | 437 | help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)." |
|
438 | 438 | ).tag(config=True) |
|
439 | 439 | debug = Bool(False).tag(config=True) |
|
440 | 440 | disable_failing_post_execute = Bool(False, |
|
441 | 441 | help="Don't call post-execute functions that have failed in the past." |
|
442 | 442 | ).tag(config=True) |
|
443 | 443 | display_formatter = Instance(DisplayFormatter, allow_none=True) |
|
444 | 444 | displayhook_class = Type(DisplayHook) |
|
445 | 445 | display_pub_class = Type(DisplayPublisher) |
|
446 | 446 | |
|
447 | 447 | sphinxify_docstring = Bool(False, help= |
|
448 | 448 | """ |
|
449 | 449 | Enables rich html representation of docstrings. (This requires the |
|
450 | 450 | docrepr module). |
|
451 | 451 | """).tag(config=True) |
|
452 | 452 | |
|
453 | 453 | @observe("sphinxify_docstring") |
|
454 | 454 | def _sphinxify_docstring_changed(self, change): |
|
455 | 455 | if change['new']: |
|
456 | 456 | warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning) |
|
457 | 457 | |
|
458 | 458 | enable_html_pager = Bool(False, help= |
|
459 | 459 | """ |
|
460 | 460 | (Provisional API) enables html representation in mime bundles sent |
|
461 | 461 | to pagers. |
|
462 | 462 | """).tag(config=True) |
|
463 | 463 | |
|
464 | 464 | @observe("enable_html_pager") |
|
465 | 465 | def _enable_html_pager_changed(self, change): |
|
466 | 466 | if change['new']: |
|
467 | 467 | warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning) |
|
468 | 468 | |
|
469 | 469 | data_pub_class = None |
|
470 | 470 | |
|
471 | 471 | exit_now = Bool(False) |
|
472 | 472 | exiter = Instance(ExitAutocall) |
|
473 | 473 | @default('exiter') |
|
474 | 474 | def _exiter_default(self): |
|
475 | 475 | return ExitAutocall(self) |
|
476 | 476 | # Monotonically increasing execution counter |
|
477 | 477 | execution_count = Integer(1) |
|
478 | 478 | filename = Unicode("<ipython console>") |
|
479 | 479 | ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__ |
|
480 | 480 | |
|
481 | 481 | # Used to transform cells before running them, and check whether code is complete |
|
482 | 482 | input_transformer_manager = Instance('IPython.core.inputtransformer2.TransformerManager', |
|
483 | 483 | ()) |
|
484 | 484 | |
|
485 | 485 | @property |
|
486 | 486 | def input_transformers_cleanup(self): |
|
487 | 487 | return self.input_transformer_manager.cleanup_transforms |
|
488 | 488 | |
|
489 | 489 | input_transformers_post = List([], |
|
490 | 490 | help="A list of string input transformers, to be applied after IPython's " |
|
491 | 491 | "own input transformations." |
|
492 | 492 | ) |
|
493 | 493 | |
|
494 | 494 | @property |
|
495 | 495 | def input_splitter(self): |
|
496 | 496 | """Make this available for backward compatibility (pre-7.0 release) with existing code. |
|
497 | 497 | |
|
498 | 498 | For example, ipykernel ipykernel currently uses |
|
499 | 499 | `shell.input_splitter.check_complete` |
|
500 | 500 | """ |
|
501 | 501 | from warnings import warn |
|
502 | 502 | warn("`input_splitter` is deprecated since IPython 7.0, prefer `input_transformer_manager`.", |
|
503 | 503 | DeprecationWarning, stacklevel=2 |
|
504 | 504 | ) |
|
505 | 505 | return self.input_transformer_manager |
|
506 | 506 | |
|
507 | 507 | logstart = Bool(False, help= |
|
508 | 508 | """ |
|
509 | 509 | Start logging to the default log file in overwrite mode. |
|
510 | 510 | Use `logappend` to specify a log file to **append** logs to. |
|
511 | 511 | """ |
|
512 | 512 | ).tag(config=True) |
|
513 | 513 | logfile = Unicode('', help= |
|
514 | 514 | """ |
|
515 | 515 | The name of the logfile to use. |
|
516 | 516 | """ |
|
517 | 517 | ).tag(config=True) |
|
518 | 518 | logappend = Unicode('', help= |
|
519 | 519 | """ |
|
520 | 520 | Start logging to the given file in append mode. |
|
521 | 521 | Use `logfile` to specify a log file to **overwrite** logs to. |
|
522 | 522 | """ |
|
523 | 523 | ).tag(config=True) |
|
524 | 524 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
525 | 525 | ).tag(config=True) |
|
526 | 526 | pdb = Bool(False, help= |
|
527 | 527 | """ |
|
528 | 528 | Automatically call the pdb debugger after every exception. |
|
529 | 529 | """ |
|
530 | 530 | ).tag(config=True) |
|
531 | 531 | display_page = Bool(False, |
|
532 | 532 | help="""If True, anything that would be passed to the pager |
|
533 | 533 | will be displayed as regular output instead.""" |
|
534 | 534 | ).tag(config=True) |
|
535 | 535 | |
|
536 | 536 | # deprecated prompt traits: |
|
537 | 537 | |
|
538 | 538 | prompt_in1 = Unicode('In [\\#]: ', |
|
539 | 539 | help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." |
|
540 | 540 | ).tag(config=True) |
|
541 | 541 | prompt_in2 = Unicode(' .\\D.: ', |
|
542 | 542 | help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." |
|
543 | 543 | ).tag(config=True) |
|
544 | 544 | prompt_out = Unicode('Out[\\#]: ', |
|
545 | 545 | help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." |
|
546 | 546 | ).tag(config=True) |
|
547 | 547 | prompts_pad_left = Bool(True, |
|
548 | 548 | help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." |
|
549 | 549 | ).tag(config=True) |
|
550 | 550 | |
|
551 | 551 | @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left') |
|
552 | 552 | def _prompt_trait_changed(self, change): |
|
553 | 553 | name = change['name'] |
|
554 | 554 | warn("InteractiveShell.{name} is deprecated since IPython 4.0" |
|
555 | 555 | " and ignored since 5.0, set TerminalInteractiveShell.prompts" |
|
556 | 556 | " object directly.".format(name=name)) |
|
557 | 557 | |
|
558 | 558 | # protect against weird cases where self.config may not exist: |
|
559 | 559 | |
|
560 | 560 | show_rewritten_input = Bool(True, |
|
561 | 561 | help="Show rewritten input, e.g. for autocall." |
|
562 | 562 | ).tag(config=True) |
|
563 | 563 | |
|
564 | 564 | quiet = Bool(False).tag(config=True) |
|
565 | 565 | |
|
566 | 566 | history_length = Integer(10000, |
|
567 | 567 | help='Total length of command history' |
|
568 | 568 | ).tag(config=True) |
|
569 | 569 | |
|
570 | 570 | history_load_length = Integer(1000, help= |
|
571 | 571 | """ |
|
572 | 572 | The number of saved history entries to be loaded |
|
573 | 573 | into the history buffer at startup. |
|
574 | 574 | """ |
|
575 | 575 | ).tag(config=True) |
|
576 | 576 | |
|
577 | 577 | ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none', 'last_expr_or_assign'], |
|
578 | 578 | default_value='last_expr', |
|
579 | 579 | help=""" |
|
580 | 580 | 'all', 'last', 'last_expr' or 'none', 'last_expr_or_assign' specifying |
|
581 | 581 | which nodes should be run interactively (displaying output from expressions). |
|
582 | 582 | """ |
|
583 | 583 | ).tag(config=True) |
|
584 | 584 | |
|
585 | 585 | # TODO: this part of prompt management should be moved to the frontends. |
|
586 | 586 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' |
|
587 | 587 | separate_in = SeparateUnicode('\n').tag(config=True) |
|
588 | 588 | separate_out = SeparateUnicode('').tag(config=True) |
|
589 | 589 | separate_out2 = SeparateUnicode('').tag(config=True) |
|
590 | 590 | wildcards_case_sensitive = Bool(True).tag(config=True) |
|
591 | 591 | xmode = CaselessStrEnum(('Context', 'Plain', 'Verbose', 'Minimal'), |
|
592 | 592 | default_value='Context', |
|
593 | 593 | help="Switch modes for the IPython exception handlers." |
|
594 | 594 | ).tag(config=True) |
|
595 | 595 | |
|
596 | 596 | # Subcomponents of InteractiveShell |
|
597 | 597 | alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True) |
|
598 | 598 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True) |
|
599 | 599 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True) |
|
600 | 600 | display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True) |
|
601 | 601 | extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True) |
|
602 | 602 | payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True) |
|
603 | 603 | history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True) |
|
604 | 604 | magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True) |
|
605 | 605 | |
|
606 | 606 | profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True) |
|
607 | 607 | @property |
|
608 | 608 | def profile(self): |
|
609 | 609 | if self.profile_dir is not None: |
|
610 | 610 | name = os.path.basename(self.profile_dir.location) |
|
611 | 611 | return name.replace('profile_','') |
|
612 | 612 | |
|
613 | 613 | |
|
614 | 614 | # Private interface |
|
615 | 615 | _post_execute = Dict() |
|
616 | 616 | |
|
617 | 617 | # Tracks any GUI loop loaded for pylab |
|
618 | 618 | pylab_gui_select = None |
|
619 | 619 | |
|
620 | 620 | last_execution_succeeded = Bool(True, help='Did last executed command succeeded') |
|
621 | 621 | |
|
622 | 622 | last_execution_result = Instance('IPython.core.interactiveshell.ExecutionResult', help='Result of executing the last command', allow_none=True) |
|
623 | 623 | |
|
624 | 624 | def __init__(self, ipython_dir=None, profile_dir=None, |
|
625 | 625 | user_module=None, user_ns=None, |
|
626 | 626 | custom_exceptions=((), None), **kwargs): |
|
627 | 627 | |
|
628 | 628 | # This is where traits with a config_key argument are updated |
|
629 | 629 | # from the values on config. |
|
630 | 630 | super(InteractiveShell, self).__init__(**kwargs) |
|
631 | 631 | if 'PromptManager' in self.config: |
|
632 | 632 | warn('As of IPython 5.0 `PromptManager` config will have no effect' |
|
633 | 633 | ' and has been replaced by TerminalInteractiveShell.prompts_class') |
|
634 | 634 | self.configurables = [self] |
|
635 | 635 | |
|
636 | 636 | # These are relatively independent and stateless |
|
637 | 637 | self.init_ipython_dir(ipython_dir) |
|
638 | 638 | self.init_profile_dir(profile_dir) |
|
639 | 639 | self.init_instance_attrs() |
|
640 | 640 | self.init_environment() |
|
641 | 641 | |
|
642 | 642 | # Check if we're in a virtualenv, and set up sys.path. |
|
643 | 643 | self.init_virtualenv() |
|
644 | 644 | |
|
645 | 645 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
646 | 646 | self.init_create_namespaces(user_module, user_ns) |
|
647 | 647 | # This has to be done after init_create_namespaces because it uses |
|
648 | 648 | # something in self.user_ns, but before init_sys_modules, which |
|
649 | 649 | # is the first thing to modify sys. |
|
650 | 650 | # TODO: When we override sys.stdout and sys.stderr before this class |
|
651 | 651 | # is created, we are saving the overridden ones here. Not sure if this |
|
652 | 652 | # is what we want to do. |
|
653 | 653 | self.save_sys_module_state() |
|
654 | 654 | self.init_sys_modules() |
|
655 | 655 | |
|
656 | 656 | # While we're trying to have each part of the code directly access what |
|
657 | 657 | # it needs without keeping redundant references to objects, we have too |
|
658 | 658 | # much legacy code that expects ip.db to exist. |
|
659 | 659 | self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db')) |
|
660 | 660 | |
|
661 | 661 | self.init_history() |
|
662 | 662 | self.init_encoding() |
|
663 | 663 | self.init_prefilter() |
|
664 | 664 | |
|
665 | 665 | self.init_syntax_highlighting() |
|
666 | 666 | self.init_hooks() |
|
667 | 667 | self.init_events() |
|
668 | 668 | self.init_pushd_popd_magic() |
|
669 | 669 | self.init_user_ns() |
|
670 | 670 | self.init_logger() |
|
671 | 671 | self.init_builtins() |
|
672 | 672 | |
|
673 | 673 | # The following was in post_config_initialization |
|
674 | 674 | self.init_inspector() |
|
675 | 675 | self.raw_input_original = input |
|
676 | 676 | self.init_completer() |
|
677 | 677 | # TODO: init_io() needs to happen before init_traceback handlers |
|
678 | 678 | # because the traceback handlers hardcode the stdout/stderr streams. |
|
679 | 679 | # This logic in in debugger.Pdb and should eventually be changed. |
|
680 | 680 | self.init_io() |
|
681 | 681 | self.init_traceback_handlers(custom_exceptions) |
|
682 | 682 | self.init_prompts() |
|
683 | 683 | self.init_display_formatter() |
|
684 | 684 | self.init_display_pub() |
|
685 | 685 | self.init_data_pub() |
|
686 | 686 | self.init_displayhook() |
|
687 | 687 | self.init_magics() |
|
688 | 688 | self.init_alias() |
|
689 | 689 | self.init_logstart() |
|
690 | 690 | self.init_pdb() |
|
691 | 691 | self.init_extension_manager() |
|
692 | 692 | self.init_payload() |
|
693 | 693 | self.init_deprecation_warnings() |
|
694 | 694 | self.hooks.late_startup_hook() |
|
695 | 695 | self.events.trigger('shell_initialized', self) |
|
696 | 696 | atexit.register(self.atexit_operations) |
|
697 | 697 | |
|
698 | 698 | def get_ipython(self): |
|
699 | 699 | """Return the currently running IPython instance.""" |
|
700 | 700 | return self |
|
701 | 701 | |
|
702 | 702 | #------------------------------------------------------------------------- |
|
703 | 703 | # Trait changed handlers |
|
704 | 704 | #------------------------------------------------------------------------- |
|
705 | 705 | @observe('ipython_dir') |
|
706 | 706 | def _ipython_dir_changed(self, change): |
|
707 | 707 | ensure_dir_exists(change['new']) |
|
708 | 708 | |
|
709 | 709 | def set_autoindent(self,value=None): |
|
710 | 710 | """Set the autoindent flag. |
|
711 | 711 | |
|
712 | 712 | If called with no arguments, it acts as a toggle.""" |
|
713 | 713 | if value is None: |
|
714 | 714 | self.autoindent = not self.autoindent |
|
715 | 715 | else: |
|
716 | 716 | self.autoindent = value |
|
717 | 717 | |
|
718 | 718 | #------------------------------------------------------------------------- |
|
719 | 719 | # init_* methods called by __init__ |
|
720 | 720 | #------------------------------------------------------------------------- |
|
721 | 721 | |
|
722 | 722 | def init_ipython_dir(self, ipython_dir): |
|
723 | 723 | if ipython_dir is not None: |
|
724 | 724 | self.ipython_dir = ipython_dir |
|
725 | 725 | return |
|
726 | 726 | |
|
727 | 727 | self.ipython_dir = get_ipython_dir() |
|
728 | 728 | |
|
729 | 729 | def init_profile_dir(self, profile_dir): |
|
730 | 730 | if profile_dir is not None: |
|
731 | 731 | self.profile_dir = profile_dir |
|
732 | 732 | return |
|
733 | 733 | self.profile_dir =\ |
|
734 | 734 | ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default') |
|
735 | 735 | |
|
736 | 736 | def init_instance_attrs(self): |
|
737 | 737 | self.more = False |
|
738 | 738 | |
|
739 | 739 | # command compiler |
|
740 | 740 | self.compile = CachingCompiler() |
|
741 | 741 | |
|
742 | 742 | # Make an empty namespace, which extension writers can rely on both |
|
743 | 743 | # existing and NEVER being used by ipython itself. This gives them a |
|
744 | 744 | # convenient location for storing additional information and state |
|
745 | 745 | # their extensions may require, without fear of collisions with other |
|
746 | 746 | # ipython names that may develop later. |
|
747 | 747 | self.meta = Struct() |
|
748 | 748 | |
|
749 | 749 | # Temporary files used for various purposes. Deleted at exit. |
|
750 | 750 | self.tempfiles = [] |
|
751 | 751 | self.tempdirs = [] |
|
752 | 752 | |
|
753 | 753 | # keep track of where we started running (mainly for crash post-mortem) |
|
754 | 754 | # This is not being used anywhere currently. |
|
755 | 755 | self.starting_dir = os.getcwd() |
|
756 | 756 | |
|
757 | 757 | # Indentation management |
|
758 | 758 | self.indent_current_nsp = 0 |
|
759 | 759 | |
|
760 | 760 | # Dict to track post-execution functions that have been registered |
|
761 | 761 | self._post_execute = {} |
|
762 | 762 | |
|
763 | 763 | def init_environment(self): |
|
764 | 764 | """Any changes we need to make to the user's environment.""" |
|
765 | 765 | pass |
|
766 | 766 | |
|
767 | 767 | def init_encoding(self): |
|
768 | 768 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
769 | 769 | # under Win32 have it set to None, and we need to have a known valid |
|
770 | 770 | # encoding to use in the raw_input() method |
|
771 | 771 | try: |
|
772 | 772 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
773 | 773 | except AttributeError: |
|
774 | 774 | self.stdin_encoding = 'ascii' |
|
775 | 775 | |
|
776 | 776 | |
|
777 | 777 | @observe('colors') |
|
778 | 778 | def init_syntax_highlighting(self, changes=None): |
|
779 | 779 | # Python source parser/formatter for syntax highlighting |
|
780 | 780 | pyformat = PyColorize.Parser(style=self.colors, parent=self).format |
|
781 | 781 | self.pycolorize = lambda src: pyformat(src,'str') |
|
782 | 782 | |
|
783 | 783 | def refresh_style(self): |
|
784 | 784 | # No-op here, used in subclass |
|
785 | 785 | pass |
|
786 | 786 | |
|
787 | 787 | def init_pushd_popd_magic(self): |
|
788 | 788 | # for pushd/popd management |
|
789 | 789 | self.home_dir = get_home_dir() |
|
790 | 790 | |
|
791 | 791 | self.dir_stack = [] |
|
792 | 792 | |
|
793 | 793 | def init_logger(self): |
|
794 | 794 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', |
|
795 | 795 | logmode='rotate') |
|
796 | 796 | |
|
797 | 797 | def init_logstart(self): |
|
798 | 798 | """Initialize logging in case it was requested at the command line. |
|
799 | 799 | """ |
|
800 | 800 | if self.logappend: |
|
801 | 801 | self.magic('logstart %s append' % self.logappend) |
|
802 | 802 | elif self.logfile: |
|
803 | 803 | self.magic('logstart %s' % self.logfile) |
|
804 | 804 | elif self.logstart: |
|
805 | 805 | self.magic('logstart') |
|
806 | 806 | |
|
807 | 807 | def init_deprecation_warnings(self): |
|
808 | 808 | """ |
|
809 | 809 | register default filter for deprecation warning. |
|
810 | 810 | |
|
811 | 811 | This will allow deprecation warning of function used interactively to show |
|
812 | 812 | warning to users, and still hide deprecation warning from libraries import. |
|
813 | 813 | """ |
|
814 | 814 | if sys.version_info < (3,7): |
|
815 | 815 | warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__")) |
|
816 | 816 | |
|
817 | 817 | |
|
818 | 818 | def init_builtins(self): |
|
819 | 819 | # A single, static flag that we set to True. Its presence indicates |
|
820 | 820 | # that an IPython shell has been created, and we make no attempts at |
|
821 | 821 | # removing on exit or representing the existence of more than one |
|
822 | 822 | # IPython at a time. |
|
823 | 823 | builtin_mod.__dict__['__IPYTHON__'] = True |
|
824 | 824 | builtin_mod.__dict__['display'] = display |
|
825 | 825 | |
|
826 | 826 | self.builtin_trap = BuiltinTrap(shell=self) |
|
827 | 827 | |
|
828 | 828 | @observe('colors') |
|
829 | 829 | def init_inspector(self, changes=None): |
|
830 | 830 | # Object inspector |
|
831 | 831 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
832 | 832 | PyColorize.ANSICodeColors, |
|
833 | 833 | self.colors, |
|
834 | 834 | self.object_info_string_level) |
|
835 | 835 | |
|
836 | 836 | def init_io(self): |
|
837 | 837 | # This will just use sys.stdout and sys.stderr. If you want to |
|
838 | 838 | # override sys.stdout and sys.stderr themselves, you need to do that |
|
839 | 839 | # *before* instantiating this class, because io holds onto |
|
840 | 840 | # references to the underlying streams. |
|
841 | 841 | # io.std* are deprecated, but don't show our own deprecation warnings |
|
842 | 842 | # during initialization of the deprecated API. |
|
843 | 843 | with warnings.catch_warnings(): |
|
844 | 844 | warnings.simplefilter('ignore', DeprecationWarning) |
|
845 | 845 | io.stdout = io.IOStream(sys.stdout) |
|
846 | 846 | io.stderr = io.IOStream(sys.stderr) |
|
847 | 847 | |
|
848 | 848 | def init_prompts(self): |
|
849 | 849 | # Set system prompts, so that scripts can decide if they are running |
|
850 | 850 | # interactively. |
|
851 | 851 | sys.ps1 = 'In : ' |
|
852 | 852 | sys.ps2 = '...: ' |
|
853 | 853 | sys.ps3 = 'Out: ' |
|
854 | 854 | |
|
855 | 855 | def init_display_formatter(self): |
|
856 | 856 | self.display_formatter = DisplayFormatter(parent=self) |
|
857 | 857 | self.configurables.append(self.display_formatter) |
|
858 | 858 | |
|
859 | 859 | def init_display_pub(self): |
|
860 | self.display_pub = self.display_pub_class(parent=self) | |
|
860 | self.display_pub = self.display_pub_class(parent=self, shell=self) | |
|
861 | 861 | self.configurables.append(self.display_pub) |
|
862 | 862 | |
|
863 | 863 | def init_data_pub(self): |
|
864 | 864 | if not self.data_pub_class: |
|
865 | 865 | self.data_pub = None |
|
866 | 866 | return |
|
867 | 867 | self.data_pub = self.data_pub_class(parent=self) |
|
868 | 868 | self.configurables.append(self.data_pub) |
|
869 | 869 | |
|
870 | 870 | def init_displayhook(self): |
|
871 | 871 | # Initialize displayhook, set in/out prompts and printing system |
|
872 | 872 | self.displayhook = self.displayhook_class( |
|
873 | 873 | parent=self, |
|
874 | 874 | shell=self, |
|
875 | 875 | cache_size=self.cache_size, |
|
876 | 876 | ) |
|
877 | 877 | self.configurables.append(self.displayhook) |
|
878 | 878 | # This is a context manager that installs/revmoes the displayhook at |
|
879 | 879 | # the appropriate time. |
|
880 | 880 | self.display_trap = DisplayTrap(hook=self.displayhook) |
|
881 | 881 | |
|
882 | 882 | def init_virtualenv(self): |
|
883 | 883 | """Add a virtualenv to sys.path so the user can import modules from it. |
|
884 | 884 | This isn't perfect: it doesn't use the Python interpreter with which the |
|
885 | 885 | virtualenv was built, and it ignores the --no-site-packages option. A |
|
886 | 886 | warning will appear suggesting the user installs IPython in the |
|
887 | 887 | virtualenv, but for many cases, it probably works well enough. |
|
888 | 888 | |
|
889 | 889 | Adapted from code snippets online. |
|
890 | 890 | |
|
891 | 891 | http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv |
|
892 | 892 | """ |
|
893 | 893 | if 'VIRTUAL_ENV' not in os.environ: |
|
894 | 894 | # Not in a virtualenv |
|
895 | 895 | return |
|
896 | 896 | |
|
897 | 897 | p = os.path.normcase(sys.executable) |
|
898 | 898 | p_venv = os.path.normcase(os.environ['VIRTUAL_ENV']) |
|
899 | 899 | |
|
900 | 900 | # executable path should end like /bin/python or \\scripts\\python.exe |
|
901 | 901 | p_exe_up2 = os.path.dirname(os.path.dirname(p)) |
|
902 | 902 | if p_exe_up2 and os.path.exists(p_venv) and os.path.samefile(p_exe_up2, p_venv): |
|
903 | 903 | # Our exe is inside the virtualenv, don't need to do anything. |
|
904 | 904 | return |
|
905 | 905 | |
|
906 | 906 | # fallback venv detection: |
|
907 | 907 | # stdlib venv may symlink sys.executable, so we can't use realpath. |
|
908 | 908 | # but others can symlink *to* the venv Python, so we can't just use sys.executable. |
|
909 | 909 | # So we just check every item in the symlink tree (generally <= 3) |
|
910 | 910 | paths = [p] |
|
911 | 911 | while os.path.islink(p): |
|
912 | 912 | p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p))) |
|
913 | 913 | paths.append(p) |
|
914 | 914 | |
|
915 | 915 | # In Cygwin paths like "c:\..." and '\cygdrive\c\...' are possible |
|
916 | 916 | if p_venv.startswith('\\cygdrive'): |
|
917 | 917 | p_venv = p_venv[11:] |
|
918 | 918 | elif len(p_venv) >= 2 and p_venv[1] == ':': |
|
919 | 919 | p_venv = p_venv[2:] |
|
920 | 920 | |
|
921 | 921 | if any(p_venv in p for p in paths): |
|
922 | 922 | # Running properly in the virtualenv, don't need to do anything |
|
923 | 923 | return |
|
924 | 924 | |
|
925 | 925 | warn("Attempting to work in a virtualenv. If you encounter problems, please " |
|
926 | 926 | "install IPython inside the virtualenv.") |
|
927 | 927 | if sys.platform == "win32": |
|
928 | 928 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages') |
|
929 | 929 | else: |
|
930 | 930 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib', |
|
931 | 931 | 'python%d.%d' % sys.version_info[:2], 'site-packages') |
|
932 | 932 | |
|
933 | 933 | import site |
|
934 | 934 | sys.path.insert(0, virtual_env) |
|
935 | 935 | site.addsitedir(virtual_env) |
|
936 | 936 | |
|
937 | 937 | #------------------------------------------------------------------------- |
|
938 | 938 | # Things related to injections into the sys module |
|
939 | 939 | #------------------------------------------------------------------------- |
|
940 | 940 | |
|
941 | 941 | def save_sys_module_state(self): |
|
942 | 942 | """Save the state of hooks in the sys module. |
|
943 | 943 | |
|
944 | 944 | This has to be called after self.user_module is created. |
|
945 | 945 | """ |
|
946 | 946 | self._orig_sys_module_state = {'stdin': sys.stdin, |
|
947 | 947 | 'stdout': sys.stdout, |
|
948 | 948 | 'stderr': sys.stderr, |
|
949 | 949 | 'excepthook': sys.excepthook} |
|
950 | 950 | self._orig_sys_modules_main_name = self.user_module.__name__ |
|
951 | 951 | self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__) |
|
952 | 952 | |
|
953 | 953 | def restore_sys_module_state(self): |
|
954 | 954 | """Restore the state of the sys module.""" |
|
955 | 955 | try: |
|
956 | 956 | for k, v in self._orig_sys_module_state.items(): |
|
957 | 957 | setattr(sys, k, v) |
|
958 | 958 | except AttributeError: |
|
959 | 959 | pass |
|
960 | 960 | # Reset what what done in self.init_sys_modules |
|
961 | 961 | if self._orig_sys_modules_main_mod is not None: |
|
962 | 962 | sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod |
|
963 | 963 | |
|
964 | 964 | #------------------------------------------------------------------------- |
|
965 | 965 | # Things related to the banner |
|
966 | 966 | #------------------------------------------------------------------------- |
|
967 | 967 | |
|
968 | 968 | @property |
|
969 | 969 | def banner(self): |
|
970 | 970 | banner = self.banner1 |
|
971 | 971 | if self.profile and self.profile != 'default': |
|
972 | 972 | banner += '\nIPython profile: %s\n' % self.profile |
|
973 | 973 | if self.banner2: |
|
974 | 974 | banner += '\n' + self.banner2 |
|
975 | 975 | return banner |
|
976 | 976 | |
|
977 | 977 | def show_banner(self, banner=None): |
|
978 | 978 | if banner is None: |
|
979 | 979 | banner = self.banner |
|
980 | 980 | sys.stdout.write(banner) |
|
981 | 981 | |
|
982 | 982 | #------------------------------------------------------------------------- |
|
983 | 983 | # Things related to hooks |
|
984 | 984 | #------------------------------------------------------------------------- |
|
985 | 985 | |
|
986 | 986 | def init_hooks(self): |
|
987 | 987 | # hooks holds pointers used for user-side customizations |
|
988 | 988 | self.hooks = Struct() |
|
989 | 989 | |
|
990 | 990 | self.strdispatchers = {} |
|
991 | 991 | |
|
992 | 992 | # Set all default hooks, defined in the IPython.hooks module. |
|
993 | 993 | hooks = IPython.core.hooks |
|
994 | 994 | for hook_name in hooks.__all__: |
|
995 | 995 | # default hooks have priority 100, i.e. low; user hooks should have |
|
996 | 996 | # 0-100 priority |
|
997 | 997 | self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False) |
|
998 | 998 | |
|
999 | 999 | if self.display_page: |
|
1000 | 1000 | self.set_hook('show_in_pager', page.as_hook(page.display_page), 90) |
|
1001 | 1001 | |
|
1002 | 1002 | def set_hook(self,name,hook, priority=50, str_key=None, re_key=None, |
|
1003 | 1003 | _warn_deprecated=True): |
|
1004 | 1004 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
1005 | 1005 | |
|
1006 | 1006 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
1007 | 1007 | adding your function to one of these hooks, you can modify IPython's |
|
1008 | 1008 | behavior to call at runtime your own routines.""" |
|
1009 | 1009 | |
|
1010 | 1010 | # At some point in the future, this should validate the hook before it |
|
1011 | 1011 | # accepts it. Probably at least check that the hook takes the number |
|
1012 | 1012 | # of args it's supposed to. |
|
1013 | 1013 | |
|
1014 | 1014 | f = types.MethodType(hook,self) |
|
1015 | 1015 | |
|
1016 | 1016 | # check if the hook is for strdispatcher first |
|
1017 | 1017 | if str_key is not None: |
|
1018 | 1018 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
1019 | 1019 | sdp.add_s(str_key, f, priority ) |
|
1020 | 1020 | self.strdispatchers[name] = sdp |
|
1021 | 1021 | return |
|
1022 | 1022 | if re_key is not None: |
|
1023 | 1023 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
1024 | 1024 | sdp.add_re(re.compile(re_key), f, priority ) |
|
1025 | 1025 | self.strdispatchers[name] = sdp |
|
1026 | 1026 | return |
|
1027 | 1027 | |
|
1028 | 1028 | dp = getattr(self.hooks, name, None) |
|
1029 | 1029 | if name not in IPython.core.hooks.__all__: |
|
1030 | 1030 | print("Warning! Hook '%s' is not one of %s" % \ |
|
1031 | 1031 | (name, IPython.core.hooks.__all__ )) |
|
1032 | 1032 | |
|
1033 | 1033 | if _warn_deprecated and (name in IPython.core.hooks.deprecated): |
|
1034 | 1034 | alternative = IPython.core.hooks.deprecated[name] |
|
1035 | 1035 | warn("Hook {} is deprecated. Use {} instead.".format(name, alternative), stacklevel=2) |
|
1036 | 1036 | |
|
1037 | 1037 | if not dp: |
|
1038 | 1038 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
1039 | 1039 | |
|
1040 | 1040 | try: |
|
1041 | 1041 | dp.add(f,priority) |
|
1042 | 1042 | except AttributeError: |
|
1043 | 1043 | # it was not commandchain, plain old func - replace |
|
1044 | 1044 | dp = f |
|
1045 | 1045 | |
|
1046 | 1046 | setattr(self.hooks,name, dp) |
|
1047 | 1047 | |
|
1048 | 1048 | #------------------------------------------------------------------------- |
|
1049 | 1049 | # Things related to events |
|
1050 | 1050 | #------------------------------------------------------------------------- |
|
1051 | 1051 | |
|
1052 | 1052 | def init_events(self): |
|
1053 | 1053 | self.events = EventManager(self, available_events) |
|
1054 | 1054 | |
|
1055 | 1055 | self.events.register("pre_execute", self._clear_warning_registry) |
|
1056 | 1056 | |
|
1057 | 1057 | def register_post_execute(self, func): |
|
1058 | 1058 | """DEPRECATED: Use ip.events.register('post_run_cell', func) |
|
1059 | 1059 | |
|
1060 | 1060 | Register a function for calling after code execution. |
|
1061 | 1061 | """ |
|
1062 | 1062 | warn("ip.register_post_execute is deprecated, use " |
|
1063 | 1063 | "ip.events.register('post_run_cell', func) instead.", stacklevel=2) |
|
1064 | 1064 | self.events.register('post_run_cell', func) |
|
1065 | 1065 | |
|
1066 | 1066 | def _clear_warning_registry(self): |
|
1067 | 1067 | # clear the warning registry, so that different code blocks with |
|
1068 | 1068 | # overlapping line number ranges don't cause spurious suppression of |
|
1069 | 1069 | # warnings (see gh-6611 for details) |
|
1070 | 1070 | if "__warningregistry__" in self.user_global_ns: |
|
1071 | 1071 | del self.user_global_ns["__warningregistry__"] |
|
1072 | 1072 | |
|
1073 | 1073 | #------------------------------------------------------------------------- |
|
1074 | 1074 | # Things related to the "main" module |
|
1075 | 1075 | #------------------------------------------------------------------------- |
|
1076 | 1076 | |
|
1077 | 1077 | def new_main_mod(self, filename, modname): |
|
1078 | 1078 | """Return a new 'main' module object for user code execution. |
|
1079 | 1079 | |
|
1080 | 1080 | ``filename`` should be the path of the script which will be run in the |
|
1081 | 1081 | module. Requests with the same filename will get the same module, with |
|
1082 | 1082 | its namespace cleared. |
|
1083 | 1083 | |
|
1084 | 1084 | ``modname`` should be the module name - normally either '__main__' or |
|
1085 | 1085 | the basename of the file without the extension. |
|
1086 | 1086 | |
|
1087 | 1087 | When scripts are executed via %run, we must keep a reference to their |
|
1088 | 1088 | __main__ module around so that Python doesn't |
|
1089 | 1089 | clear it, rendering references to module globals useless. |
|
1090 | 1090 | |
|
1091 | 1091 | This method keeps said reference in a private dict, keyed by the |
|
1092 | 1092 | absolute path of the script. This way, for multiple executions of the |
|
1093 | 1093 | same script we only keep one copy of the namespace (the last one), |
|
1094 | 1094 | thus preventing memory leaks from old references while allowing the |
|
1095 | 1095 | objects from the last execution to be accessible. |
|
1096 | 1096 | """ |
|
1097 | 1097 | filename = os.path.abspath(filename) |
|
1098 | 1098 | try: |
|
1099 | 1099 | main_mod = self._main_mod_cache[filename] |
|
1100 | 1100 | except KeyError: |
|
1101 | 1101 | main_mod = self._main_mod_cache[filename] = types.ModuleType( |
|
1102 | 1102 | modname, |
|
1103 | 1103 | doc="Module created for script run in IPython") |
|
1104 | 1104 | else: |
|
1105 | 1105 | main_mod.__dict__.clear() |
|
1106 | 1106 | main_mod.__name__ = modname |
|
1107 | 1107 | |
|
1108 | 1108 | main_mod.__file__ = filename |
|
1109 | 1109 | # It seems pydoc (and perhaps others) needs any module instance to |
|
1110 | 1110 | # implement a __nonzero__ method |
|
1111 | 1111 | main_mod.__nonzero__ = lambda : True |
|
1112 | 1112 | |
|
1113 | 1113 | return main_mod |
|
1114 | 1114 | |
|
1115 | 1115 | def clear_main_mod_cache(self): |
|
1116 | 1116 | """Clear the cache of main modules. |
|
1117 | 1117 | |
|
1118 | 1118 | Mainly for use by utilities like %reset. |
|
1119 | 1119 | |
|
1120 | 1120 | Examples |
|
1121 | 1121 | -------- |
|
1122 | 1122 | |
|
1123 | 1123 | In [15]: import IPython |
|
1124 | 1124 | |
|
1125 | 1125 | In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython') |
|
1126 | 1126 | |
|
1127 | 1127 | In [17]: len(_ip._main_mod_cache) > 0 |
|
1128 | 1128 | Out[17]: True |
|
1129 | 1129 | |
|
1130 | 1130 | In [18]: _ip.clear_main_mod_cache() |
|
1131 | 1131 | |
|
1132 | 1132 | In [19]: len(_ip._main_mod_cache) == 0 |
|
1133 | 1133 | Out[19]: True |
|
1134 | 1134 | """ |
|
1135 | 1135 | self._main_mod_cache.clear() |
|
1136 | 1136 | |
|
1137 | 1137 | #------------------------------------------------------------------------- |
|
1138 | 1138 | # Things related to debugging |
|
1139 | 1139 | #------------------------------------------------------------------------- |
|
1140 | 1140 | |
|
1141 | 1141 | def init_pdb(self): |
|
1142 | 1142 | # Set calling of pdb on exceptions |
|
1143 | 1143 | # self.call_pdb is a property |
|
1144 | 1144 | self.call_pdb = self.pdb |
|
1145 | 1145 | |
|
1146 | 1146 | def _get_call_pdb(self): |
|
1147 | 1147 | return self._call_pdb |
|
1148 | 1148 | |
|
1149 | 1149 | def _set_call_pdb(self,val): |
|
1150 | 1150 | |
|
1151 | 1151 | if val not in (0,1,False,True): |
|
1152 | 1152 | raise ValueError('new call_pdb value must be boolean') |
|
1153 | 1153 | |
|
1154 | 1154 | # store value in instance |
|
1155 | 1155 | self._call_pdb = val |
|
1156 | 1156 | |
|
1157 | 1157 | # notify the actual exception handlers |
|
1158 | 1158 | self.InteractiveTB.call_pdb = val |
|
1159 | 1159 | |
|
1160 | 1160 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
1161 | 1161 | 'Control auto-activation of pdb at exceptions') |
|
1162 | 1162 | |
|
1163 | 1163 | def debugger(self,force=False): |
|
1164 | 1164 | """Call the pdb debugger. |
|
1165 | 1165 | |
|
1166 | 1166 | Keywords: |
|
1167 | 1167 | |
|
1168 | 1168 | - force(False): by default, this routine checks the instance call_pdb |
|
1169 | 1169 | flag and does not actually invoke the debugger if the flag is false. |
|
1170 | 1170 | The 'force' option forces the debugger to activate even if the flag |
|
1171 | 1171 | is false. |
|
1172 | 1172 | """ |
|
1173 | 1173 | |
|
1174 | 1174 | if not (force or self.call_pdb): |
|
1175 | 1175 | return |
|
1176 | 1176 | |
|
1177 | 1177 | if not hasattr(sys,'last_traceback'): |
|
1178 | 1178 | error('No traceback has been produced, nothing to debug.') |
|
1179 | 1179 | return |
|
1180 | 1180 | |
|
1181 | 1181 | self.InteractiveTB.debugger(force=True) |
|
1182 | 1182 | |
|
1183 | 1183 | #------------------------------------------------------------------------- |
|
1184 | 1184 | # Things related to IPython's various namespaces |
|
1185 | 1185 | #------------------------------------------------------------------------- |
|
1186 | 1186 | default_user_namespaces = True |
|
1187 | 1187 | |
|
1188 | 1188 | def init_create_namespaces(self, user_module=None, user_ns=None): |
|
1189 | 1189 | # Create the namespace where the user will operate. user_ns is |
|
1190 | 1190 | # normally the only one used, and it is passed to the exec calls as |
|
1191 | 1191 | # the locals argument. But we do carry a user_global_ns namespace |
|
1192 | 1192 | # given as the exec 'globals' argument, This is useful in embedding |
|
1193 | 1193 | # situations where the ipython shell opens in a context where the |
|
1194 | 1194 | # distinction between locals and globals is meaningful. For |
|
1195 | 1195 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
1196 | 1196 | |
|
1197 | 1197 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
1198 | 1198 | # level as a dict instead of a module. This is a manual fix, but I |
|
1199 | 1199 | # should really track down where the problem is coming from. Alex |
|
1200 | 1200 | # Schmolck reported this problem first. |
|
1201 | 1201 | |
|
1202 | 1202 | # A useful post by Alex Martelli on this topic: |
|
1203 | 1203 | # Re: inconsistent value from __builtins__ |
|
1204 | 1204 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
1205 | 1205 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
1206 | 1206 | # Gruppen: comp.lang.python |
|
1207 | 1207 | |
|
1208 | 1208 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
1209 | 1209 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
1210 | 1210 | # > <type 'dict'> |
|
1211 | 1211 | # > >>> print type(__builtins__) |
|
1212 | 1212 | # > <type 'module'> |
|
1213 | 1213 | # > Is this difference in return value intentional? |
|
1214 | 1214 | |
|
1215 | 1215 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
1216 | 1216 | # or a module, and it's been that way for a long time. Whether it's |
|
1217 | 1217 | # intentional (or sensible), I don't know. In any case, the idea is |
|
1218 | 1218 | # that if you need to access the built-in namespace directly, you |
|
1219 | 1219 | # should start with "import __builtin__" (note, no 's') which will |
|
1220 | 1220 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
1221 | 1221 | |
|
1222 | 1222 | # These routines return a properly built module and dict as needed by |
|
1223 | 1223 | # the rest of the code, and can also be used by extension writers to |
|
1224 | 1224 | # generate properly initialized namespaces. |
|
1225 | 1225 | if (user_ns is not None) or (user_module is not None): |
|
1226 | 1226 | self.default_user_namespaces = False |
|
1227 | 1227 | self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns) |
|
1228 | 1228 | |
|
1229 | 1229 | # A record of hidden variables we have added to the user namespace, so |
|
1230 | 1230 | # we can list later only variables defined in actual interactive use. |
|
1231 | 1231 | self.user_ns_hidden = {} |
|
1232 | 1232 | |
|
1233 | 1233 | # Now that FakeModule produces a real module, we've run into a nasty |
|
1234 | 1234 | # problem: after script execution (via %run), the module where the user |
|
1235 | 1235 | # code ran is deleted. Now that this object is a true module (needed |
|
1236 | 1236 | # so doctest and other tools work correctly), the Python module |
|
1237 | 1237 | # teardown mechanism runs over it, and sets to None every variable |
|
1238 | 1238 | # present in that module. Top-level references to objects from the |
|
1239 | 1239 | # script survive, because the user_ns is updated with them. However, |
|
1240 | 1240 | # calling functions defined in the script that use other things from |
|
1241 | 1241 | # the script will fail, because the function's closure had references |
|
1242 | 1242 | # to the original objects, which are now all None. So we must protect |
|
1243 | 1243 | # these modules from deletion by keeping a cache. |
|
1244 | 1244 | # |
|
1245 | 1245 | # To avoid keeping stale modules around (we only need the one from the |
|
1246 | 1246 | # last run), we use a dict keyed with the full path to the script, so |
|
1247 | 1247 | # only the last version of the module is held in the cache. Note, |
|
1248 | 1248 | # however, that we must cache the module *namespace contents* (their |
|
1249 | 1249 | # __dict__). Because if we try to cache the actual modules, old ones |
|
1250 | 1250 | # (uncached) could be destroyed while still holding references (such as |
|
1251 | 1251 | # those held by GUI objects that tend to be long-lived)> |
|
1252 | 1252 | # |
|
1253 | 1253 | # The %reset command will flush this cache. See the cache_main_mod() |
|
1254 | 1254 | # and clear_main_mod_cache() methods for details on use. |
|
1255 | 1255 | |
|
1256 | 1256 | # This is the cache used for 'main' namespaces |
|
1257 | 1257 | self._main_mod_cache = {} |
|
1258 | 1258 | |
|
1259 | 1259 | # A table holding all the namespaces IPython deals with, so that |
|
1260 | 1260 | # introspection facilities can search easily. |
|
1261 | 1261 | self.ns_table = {'user_global':self.user_module.__dict__, |
|
1262 | 1262 | 'user_local':self.user_ns, |
|
1263 | 1263 | 'builtin':builtin_mod.__dict__ |
|
1264 | 1264 | } |
|
1265 | 1265 | |
|
1266 | 1266 | @property |
|
1267 | 1267 | def user_global_ns(self): |
|
1268 | 1268 | return self.user_module.__dict__ |
|
1269 | 1269 | |
|
1270 | 1270 | def prepare_user_module(self, user_module=None, user_ns=None): |
|
1271 | 1271 | """Prepare the module and namespace in which user code will be run. |
|
1272 | 1272 | |
|
1273 | 1273 | When IPython is started normally, both parameters are None: a new module |
|
1274 | 1274 | is created automatically, and its __dict__ used as the namespace. |
|
1275 | 1275 | |
|
1276 | 1276 | If only user_module is provided, its __dict__ is used as the namespace. |
|
1277 | 1277 | If only user_ns is provided, a dummy module is created, and user_ns |
|
1278 | 1278 | becomes the global namespace. If both are provided (as they may be |
|
1279 | 1279 | when embedding), user_ns is the local namespace, and user_module |
|
1280 | 1280 | provides the global namespace. |
|
1281 | 1281 | |
|
1282 | 1282 | Parameters |
|
1283 | 1283 | ---------- |
|
1284 | 1284 | user_module : module, optional |
|
1285 | 1285 | The current user module in which IPython is being run. If None, |
|
1286 | 1286 | a clean module will be created. |
|
1287 | 1287 | user_ns : dict, optional |
|
1288 | 1288 | A namespace in which to run interactive commands. |
|
1289 | 1289 | |
|
1290 | 1290 | Returns |
|
1291 | 1291 | ------- |
|
1292 | 1292 | A tuple of user_module and user_ns, each properly initialised. |
|
1293 | 1293 | """ |
|
1294 | 1294 | if user_module is None and user_ns is not None: |
|
1295 | 1295 | user_ns.setdefault("__name__", "__main__") |
|
1296 | 1296 | user_module = DummyMod() |
|
1297 | 1297 | user_module.__dict__ = user_ns |
|
1298 | 1298 | |
|
1299 | 1299 | if user_module is None: |
|
1300 | 1300 | user_module = types.ModuleType("__main__", |
|
1301 | 1301 | doc="Automatically created module for IPython interactive environment") |
|
1302 | 1302 | |
|
1303 | 1303 | # We must ensure that __builtin__ (without the final 's') is always |
|
1304 | 1304 | # available and pointing to the __builtin__ *module*. For more details: |
|
1305 | 1305 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
1306 | 1306 | user_module.__dict__.setdefault('__builtin__', builtin_mod) |
|
1307 | 1307 | user_module.__dict__.setdefault('__builtins__', builtin_mod) |
|
1308 | 1308 | |
|
1309 | 1309 | if user_ns is None: |
|
1310 | 1310 | user_ns = user_module.__dict__ |
|
1311 | 1311 | |
|
1312 | 1312 | return user_module, user_ns |
|
1313 | 1313 | |
|
1314 | 1314 | def init_sys_modules(self): |
|
1315 | 1315 | # We need to insert into sys.modules something that looks like a |
|
1316 | 1316 | # module but which accesses the IPython namespace, for shelve and |
|
1317 | 1317 | # pickle to work interactively. Normally they rely on getting |
|
1318 | 1318 | # everything out of __main__, but for embedding purposes each IPython |
|
1319 | 1319 | # instance has its own private namespace, so we can't go shoving |
|
1320 | 1320 | # everything into __main__. |
|
1321 | 1321 | |
|
1322 | 1322 | # note, however, that we should only do this for non-embedded |
|
1323 | 1323 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
1324 | 1324 | # namespace. Embedded instances, on the other hand, should not do |
|
1325 | 1325 | # this because they need to manage the user local/global namespaces |
|
1326 | 1326 | # only, but they live within a 'normal' __main__ (meaning, they |
|
1327 | 1327 | # shouldn't overtake the execution environment of the script they're |
|
1328 | 1328 | # embedded in). |
|
1329 | 1329 | |
|
1330 | 1330 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
1331 | 1331 | main_name = self.user_module.__name__ |
|
1332 | 1332 | sys.modules[main_name] = self.user_module |
|
1333 | 1333 | |
|
1334 | 1334 | def init_user_ns(self): |
|
1335 | 1335 | """Initialize all user-visible namespaces to their minimum defaults. |
|
1336 | 1336 | |
|
1337 | 1337 | Certain history lists are also initialized here, as they effectively |
|
1338 | 1338 | act as user namespaces. |
|
1339 | 1339 | |
|
1340 | 1340 | Notes |
|
1341 | 1341 | ----- |
|
1342 | 1342 | All data structures here are only filled in, they are NOT reset by this |
|
1343 | 1343 | method. If they were not empty before, data will simply be added to |
|
1344 | 1344 | them. |
|
1345 | 1345 | """ |
|
1346 | 1346 | # This function works in two parts: first we put a few things in |
|
1347 | 1347 | # user_ns, and we sync that contents into user_ns_hidden so that these |
|
1348 | 1348 | # initial variables aren't shown by %who. After the sync, we add the |
|
1349 | 1349 | # rest of what we *do* want the user to see with %who even on a new |
|
1350 | 1350 | # session (probably nothing, so they really only see their own stuff) |
|
1351 | 1351 | |
|
1352 | 1352 | # The user dict must *always* have a __builtin__ reference to the |
|
1353 | 1353 | # Python standard __builtin__ namespace, which must be imported. |
|
1354 | 1354 | # This is so that certain operations in prompt evaluation can be |
|
1355 | 1355 | # reliably executed with builtins. Note that we can NOT use |
|
1356 | 1356 | # __builtins__ (note the 's'), because that can either be a dict or a |
|
1357 | 1357 | # module, and can even mutate at runtime, depending on the context |
|
1358 | 1358 | # (Python makes no guarantees on it). In contrast, __builtin__ is |
|
1359 | 1359 | # always a module object, though it must be explicitly imported. |
|
1360 | 1360 | |
|
1361 | 1361 | # For more details: |
|
1362 | 1362 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
1363 | 1363 | ns = {} |
|
1364 | 1364 | |
|
1365 | 1365 | # make global variables for user access to the histories |
|
1366 | 1366 | ns['_ih'] = self.history_manager.input_hist_parsed |
|
1367 | 1367 | ns['_oh'] = self.history_manager.output_hist |
|
1368 | 1368 | ns['_dh'] = self.history_manager.dir_hist |
|
1369 | 1369 | |
|
1370 | 1370 | # user aliases to input and output histories. These shouldn't show up |
|
1371 | 1371 | # in %who, as they can have very large reprs. |
|
1372 | 1372 | ns['In'] = self.history_manager.input_hist_parsed |
|
1373 | 1373 | ns['Out'] = self.history_manager.output_hist |
|
1374 | 1374 | |
|
1375 | 1375 | # Store myself as the public api!!! |
|
1376 | 1376 | ns['get_ipython'] = self.get_ipython |
|
1377 | 1377 | |
|
1378 | 1378 | ns['exit'] = self.exiter |
|
1379 | 1379 | ns['quit'] = self.exiter |
|
1380 | 1380 | |
|
1381 | 1381 | # Sync what we've added so far to user_ns_hidden so these aren't seen |
|
1382 | 1382 | # by %who |
|
1383 | 1383 | self.user_ns_hidden.update(ns) |
|
1384 | 1384 | |
|
1385 | 1385 | # Anything put into ns now would show up in %who. Think twice before |
|
1386 | 1386 | # putting anything here, as we really want %who to show the user their |
|
1387 | 1387 | # stuff, not our variables. |
|
1388 | 1388 | |
|
1389 | 1389 | # Finally, update the real user's namespace |
|
1390 | 1390 | self.user_ns.update(ns) |
|
1391 | 1391 | |
|
1392 | 1392 | @property |
|
1393 | 1393 | def all_ns_refs(self): |
|
1394 | 1394 | """Get a list of references to all the namespace dictionaries in which |
|
1395 | 1395 | IPython might store a user-created object. |
|
1396 | 1396 | |
|
1397 | 1397 | Note that this does not include the displayhook, which also caches |
|
1398 | 1398 | objects from the output.""" |
|
1399 | 1399 | return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \ |
|
1400 | 1400 | [m.__dict__ for m in self._main_mod_cache.values()] |
|
1401 | 1401 | |
|
1402 | 1402 | def reset(self, new_session=True): |
|
1403 | 1403 | """Clear all internal namespaces, and attempt to release references to |
|
1404 | 1404 | user objects. |
|
1405 | 1405 | |
|
1406 | 1406 | If new_session is True, a new history session will be opened. |
|
1407 | 1407 | """ |
|
1408 | 1408 | # Clear histories |
|
1409 | 1409 | self.history_manager.reset(new_session) |
|
1410 | 1410 | # Reset counter used to index all histories |
|
1411 | 1411 | if new_session: |
|
1412 | 1412 | self.execution_count = 1 |
|
1413 | 1413 | |
|
1414 | 1414 | # Reset last execution result |
|
1415 | 1415 | self.last_execution_succeeded = True |
|
1416 | 1416 | self.last_execution_result = None |
|
1417 | 1417 | |
|
1418 | 1418 | # Flush cached output items |
|
1419 | 1419 | if self.displayhook.do_full_cache: |
|
1420 | 1420 | self.displayhook.flush() |
|
1421 | 1421 | |
|
1422 | 1422 | # The main execution namespaces must be cleared very carefully, |
|
1423 | 1423 | # skipping the deletion of the builtin-related keys, because doing so |
|
1424 | 1424 | # would cause errors in many object's __del__ methods. |
|
1425 | 1425 | if self.user_ns is not self.user_global_ns: |
|
1426 | 1426 | self.user_ns.clear() |
|
1427 | 1427 | ns = self.user_global_ns |
|
1428 | 1428 | drop_keys = set(ns.keys()) |
|
1429 | 1429 | drop_keys.discard('__builtin__') |
|
1430 | 1430 | drop_keys.discard('__builtins__') |
|
1431 | 1431 | drop_keys.discard('__name__') |
|
1432 | 1432 | for k in drop_keys: |
|
1433 | 1433 | del ns[k] |
|
1434 | 1434 | |
|
1435 | 1435 | self.user_ns_hidden.clear() |
|
1436 | 1436 | |
|
1437 | 1437 | # Restore the user namespaces to minimal usability |
|
1438 | 1438 | self.init_user_ns() |
|
1439 | 1439 | |
|
1440 | 1440 | # Restore the default and user aliases |
|
1441 | 1441 | self.alias_manager.clear_aliases() |
|
1442 | 1442 | self.alias_manager.init_aliases() |
|
1443 | 1443 | |
|
1444 | 1444 | # Now define aliases that only make sense on the terminal, because they |
|
1445 | 1445 | # need direct access to the console in a way that we can't emulate in |
|
1446 | 1446 | # GUI or web frontend |
|
1447 | 1447 | if os.name == 'posix': |
|
1448 | 1448 | for cmd in ('clear', 'more', 'less', 'man'): |
|
1449 | 1449 | if cmd not in self.magics_manager.magics['line']: |
|
1450 | 1450 | self.alias_manager.soft_define_alias(cmd, cmd) |
|
1451 | 1451 | |
|
1452 | 1452 | # Flush the private list of module references kept for script |
|
1453 | 1453 | # execution protection |
|
1454 | 1454 | self.clear_main_mod_cache() |
|
1455 | 1455 | |
|
1456 | 1456 | def del_var(self, varname, by_name=False): |
|
1457 | 1457 | """Delete a variable from the various namespaces, so that, as |
|
1458 | 1458 | far as possible, we're not keeping any hidden references to it. |
|
1459 | 1459 | |
|
1460 | 1460 | Parameters |
|
1461 | 1461 | ---------- |
|
1462 | 1462 | varname : str |
|
1463 | 1463 | The name of the variable to delete. |
|
1464 | 1464 | by_name : bool |
|
1465 | 1465 | If True, delete variables with the given name in each |
|
1466 | 1466 | namespace. If False (default), find the variable in the user |
|
1467 | 1467 | namespace, and delete references to it. |
|
1468 | 1468 | """ |
|
1469 | 1469 | if varname in ('__builtin__', '__builtins__'): |
|
1470 | 1470 | raise ValueError("Refusing to delete %s" % varname) |
|
1471 | 1471 | |
|
1472 | 1472 | ns_refs = self.all_ns_refs |
|
1473 | 1473 | |
|
1474 | 1474 | if by_name: # Delete by name |
|
1475 | 1475 | for ns in ns_refs: |
|
1476 | 1476 | try: |
|
1477 | 1477 | del ns[varname] |
|
1478 | 1478 | except KeyError: |
|
1479 | 1479 | pass |
|
1480 | 1480 | else: # Delete by object |
|
1481 | 1481 | try: |
|
1482 | 1482 | obj = self.user_ns[varname] |
|
1483 | 1483 | except KeyError: |
|
1484 | 1484 | raise NameError("name '%s' is not defined" % varname) |
|
1485 | 1485 | # Also check in output history |
|
1486 | 1486 | ns_refs.append(self.history_manager.output_hist) |
|
1487 | 1487 | for ns in ns_refs: |
|
1488 | 1488 | to_delete = [n for n, o in ns.items() if o is obj] |
|
1489 | 1489 | for name in to_delete: |
|
1490 | 1490 | del ns[name] |
|
1491 | 1491 | |
|
1492 | 1492 | # Ensure it is removed from the last execution result |
|
1493 | 1493 | if self.last_execution_result.result is obj: |
|
1494 | 1494 | self.last_execution_result = None |
|
1495 | 1495 | |
|
1496 | 1496 | # displayhook keeps extra references, but not in a dictionary |
|
1497 | 1497 | for name in ('_', '__', '___'): |
|
1498 | 1498 | if getattr(self.displayhook, name) is obj: |
|
1499 | 1499 | setattr(self.displayhook, name, None) |
|
1500 | 1500 | |
|
1501 | 1501 | def reset_selective(self, regex=None): |
|
1502 | 1502 | """Clear selective variables from internal namespaces based on a |
|
1503 | 1503 | specified regular expression. |
|
1504 | 1504 | |
|
1505 | 1505 | Parameters |
|
1506 | 1506 | ---------- |
|
1507 | 1507 | regex : string or compiled pattern, optional |
|
1508 | 1508 | A regular expression pattern that will be used in searching |
|
1509 | 1509 | variable names in the users namespaces. |
|
1510 | 1510 | """ |
|
1511 | 1511 | if regex is not None: |
|
1512 | 1512 | try: |
|
1513 | 1513 | m = re.compile(regex) |
|
1514 | 1514 | except TypeError: |
|
1515 | 1515 | raise TypeError('regex must be a string or compiled pattern') |
|
1516 | 1516 | # Search for keys in each namespace that match the given regex |
|
1517 | 1517 | # If a match is found, delete the key/value pair. |
|
1518 | 1518 | for ns in self.all_ns_refs: |
|
1519 | 1519 | for var in ns: |
|
1520 | 1520 | if m.search(var): |
|
1521 | 1521 | del ns[var] |
|
1522 | 1522 | |
|
1523 | 1523 | def push(self, variables, interactive=True): |
|
1524 | 1524 | """Inject a group of variables into the IPython user namespace. |
|
1525 | 1525 | |
|
1526 | 1526 | Parameters |
|
1527 | 1527 | ---------- |
|
1528 | 1528 | variables : dict, str or list/tuple of str |
|
1529 | 1529 | The variables to inject into the user's namespace. If a dict, a |
|
1530 | 1530 | simple update is done. If a str, the string is assumed to have |
|
1531 | 1531 | variable names separated by spaces. A list/tuple of str can also |
|
1532 | 1532 | be used to give the variable names. If just the variable names are |
|
1533 | 1533 | give (list/tuple/str) then the variable values looked up in the |
|
1534 | 1534 | callers frame. |
|
1535 | 1535 | interactive : bool |
|
1536 | 1536 | If True (default), the variables will be listed with the ``who`` |
|
1537 | 1537 | magic. |
|
1538 | 1538 | """ |
|
1539 | 1539 | vdict = None |
|
1540 | 1540 | |
|
1541 | 1541 | # We need a dict of name/value pairs to do namespace updates. |
|
1542 | 1542 | if isinstance(variables, dict): |
|
1543 | 1543 | vdict = variables |
|
1544 | 1544 | elif isinstance(variables, (str, list, tuple)): |
|
1545 | 1545 | if isinstance(variables, str): |
|
1546 | 1546 | vlist = variables.split() |
|
1547 | 1547 | else: |
|
1548 | 1548 | vlist = variables |
|
1549 | 1549 | vdict = {} |
|
1550 | 1550 | cf = sys._getframe(1) |
|
1551 | 1551 | for name in vlist: |
|
1552 | 1552 | try: |
|
1553 | 1553 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1554 | 1554 | except: |
|
1555 | 1555 | print('Could not get variable %s from %s' % |
|
1556 | 1556 | (name,cf.f_code.co_name)) |
|
1557 | 1557 | else: |
|
1558 | 1558 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1559 | 1559 | |
|
1560 | 1560 | # Propagate variables to user namespace |
|
1561 | 1561 | self.user_ns.update(vdict) |
|
1562 | 1562 | |
|
1563 | 1563 | # And configure interactive visibility |
|
1564 | 1564 | user_ns_hidden = self.user_ns_hidden |
|
1565 | 1565 | if interactive: |
|
1566 | 1566 | for name in vdict: |
|
1567 | 1567 | user_ns_hidden.pop(name, None) |
|
1568 | 1568 | else: |
|
1569 | 1569 | user_ns_hidden.update(vdict) |
|
1570 | 1570 | |
|
1571 | 1571 | def drop_by_id(self, variables): |
|
1572 | 1572 | """Remove a dict of variables from the user namespace, if they are the |
|
1573 | 1573 | same as the values in the dictionary. |
|
1574 | 1574 | |
|
1575 | 1575 | This is intended for use by extensions: variables that they've added can |
|
1576 | 1576 | be taken back out if they are unloaded, without removing any that the |
|
1577 | 1577 | user has overwritten. |
|
1578 | 1578 | |
|
1579 | 1579 | Parameters |
|
1580 | 1580 | ---------- |
|
1581 | 1581 | variables : dict |
|
1582 | 1582 | A dictionary mapping object names (as strings) to the objects. |
|
1583 | 1583 | """ |
|
1584 | 1584 | for name, obj in variables.items(): |
|
1585 | 1585 | if name in self.user_ns and self.user_ns[name] is obj: |
|
1586 | 1586 | del self.user_ns[name] |
|
1587 | 1587 | self.user_ns_hidden.pop(name, None) |
|
1588 | 1588 | |
|
1589 | 1589 | #------------------------------------------------------------------------- |
|
1590 | 1590 | # Things related to object introspection |
|
1591 | 1591 | #------------------------------------------------------------------------- |
|
1592 | 1592 | |
|
1593 | 1593 | def _ofind(self, oname, namespaces=None): |
|
1594 | 1594 | """Find an object in the available namespaces. |
|
1595 | 1595 | |
|
1596 | 1596 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
1597 | 1597 | |
|
1598 | 1598 | Has special code to detect magic functions. |
|
1599 | 1599 | """ |
|
1600 | 1600 | oname = oname.strip() |
|
1601 | 1601 | if not oname.startswith(ESC_MAGIC) and \ |
|
1602 | 1602 | not oname.startswith(ESC_MAGIC2) and \ |
|
1603 | 1603 | not all(a.isidentifier() for a in oname.split(".")): |
|
1604 | 1604 | return {'found': False} |
|
1605 | 1605 | |
|
1606 | 1606 | if namespaces is None: |
|
1607 | 1607 | # Namespaces to search in: |
|
1608 | 1608 | # Put them in a list. The order is important so that we |
|
1609 | 1609 | # find things in the same order that Python finds them. |
|
1610 | 1610 | namespaces = [ ('Interactive', self.user_ns), |
|
1611 | 1611 | ('Interactive (global)', self.user_global_ns), |
|
1612 | 1612 | ('Python builtin', builtin_mod.__dict__), |
|
1613 | 1613 | ] |
|
1614 | 1614 | |
|
1615 | 1615 | ismagic = False |
|
1616 | 1616 | isalias = False |
|
1617 | 1617 | found = False |
|
1618 | 1618 | ospace = None |
|
1619 | 1619 | parent = None |
|
1620 | 1620 | obj = None |
|
1621 | 1621 | |
|
1622 | 1622 | |
|
1623 | 1623 | # Look for the given name by splitting it in parts. If the head is |
|
1624 | 1624 | # found, then we look for all the remaining parts as members, and only |
|
1625 | 1625 | # declare success if we can find them all. |
|
1626 | 1626 | oname_parts = oname.split('.') |
|
1627 | 1627 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
1628 | 1628 | for nsname,ns in namespaces: |
|
1629 | 1629 | try: |
|
1630 | 1630 | obj = ns[oname_head] |
|
1631 | 1631 | except KeyError: |
|
1632 | 1632 | continue |
|
1633 | 1633 | else: |
|
1634 | 1634 | for idx, part in enumerate(oname_rest): |
|
1635 | 1635 | try: |
|
1636 | 1636 | parent = obj |
|
1637 | 1637 | # The last part is looked up in a special way to avoid |
|
1638 | 1638 | # descriptor invocation as it may raise or have side |
|
1639 | 1639 | # effects. |
|
1640 | 1640 | if idx == len(oname_rest) - 1: |
|
1641 | 1641 | obj = self._getattr_property(obj, part) |
|
1642 | 1642 | else: |
|
1643 | 1643 | obj = getattr(obj, part) |
|
1644 | 1644 | except: |
|
1645 | 1645 | # Blanket except b/c some badly implemented objects |
|
1646 | 1646 | # allow __getattr__ to raise exceptions other than |
|
1647 | 1647 | # AttributeError, which then crashes IPython. |
|
1648 | 1648 | break |
|
1649 | 1649 | else: |
|
1650 | 1650 | # If we finish the for loop (no break), we got all members |
|
1651 | 1651 | found = True |
|
1652 | 1652 | ospace = nsname |
|
1653 | 1653 | break # namespace loop |
|
1654 | 1654 | |
|
1655 | 1655 | # Try to see if it's magic |
|
1656 | 1656 | if not found: |
|
1657 | 1657 | obj = None |
|
1658 | 1658 | if oname.startswith(ESC_MAGIC2): |
|
1659 | 1659 | oname = oname.lstrip(ESC_MAGIC2) |
|
1660 | 1660 | obj = self.find_cell_magic(oname) |
|
1661 | 1661 | elif oname.startswith(ESC_MAGIC): |
|
1662 | 1662 | oname = oname.lstrip(ESC_MAGIC) |
|
1663 | 1663 | obj = self.find_line_magic(oname) |
|
1664 | 1664 | else: |
|
1665 | 1665 | # search without prefix, so run? will find %run? |
|
1666 | 1666 | obj = self.find_line_magic(oname) |
|
1667 | 1667 | if obj is None: |
|
1668 | 1668 | obj = self.find_cell_magic(oname) |
|
1669 | 1669 | if obj is not None: |
|
1670 | 1670 | found = True |
|
1671 | 1671 | ospace = 'IPython internal' |
|
1672 | 1672 | ismagic = True |
|
1673 | 1673 | isalias = isinstance(obj, Alias) |
|
1674 | 1674 | |
|
1675 | 1675 | # Last try: special-case some literals like '', [], {}, etc: |
|
1676 | 1676 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
1677 | 1677 | obj = eval(oname_head) |
|
1678 | 1678 | found = True |
|
1679 | 1679 | ospace = 'Interactive' |
|
1680 | 1680 | |
|
1681 | 1681 | return { |
|
1682 | 1682 | 'obj':obj, |
|
1683 | 1683 | 'found':found, |
|
1684 | 1684 | 'parent':parent, |
|
1685 | 1685 | 'ismagic':ismagic, |
|
1686 | 1686 | 'isalias':isalias, |
|
1687 | 1687 | 'namespace':ospace |
|
1688 | 1688 | } |
|
1689 | 1689 | |
|
1690 | 1690 | @staticmethod |
|
1691 | 1691 | def _getattr_property(obj, attrname): |
|
1692 | 1692 | """Property-aware getattr to use in object finding. |
|
1693 | 1693 | |
|
1694 | 1694 | If attrname represents a property, return it unevaluated (in case it has |
|
1695 | 1695 | side effects or raises an error. |
|
1696 | 1696 | |
|
1697 | 1697 | """ |
|
1698 | 1698 | if not isinstance(obj, type): |
|
1699 | 1699 | try: |
|
1700 | 1700 | # `getattr(type(obj), attrname)` is not guaranteed to return |
|
1701 | 1701 | # `obj`, but does so for property: |
|
1702 | 1702 | # |
|
1703 | 1703 | # property.__get__(self, None, cls) -> self |
|
1704 | 1704 | # |
|
1705 | 1705 | # The universal alternative is to traverse the mro manually |
|
1706 | 1706 | # searching for attrname in class dicts. |
|
1707 | 1707 | attr = getattr(type(obj), attrname) |
|
1708 | 1708 | except AttributeError: |
|
1709 | 1709 | pass |
|
1710 | 1710 | else: |
|
1711 | 1711 | # This relies on the fact that data descriptors (with both |
|
1712 | 1712 | # __get__ & __set__ magic methods) take precedence over |
|
1713 | 1713 | # instance-level attributes: |
|
1714 | 1714 | # |
|
1715 | 1715 | # class A(object): |
|
1716 | 1716 | # @property |
|
1717 | 1717 | # def foobar(self): return 123 |
|
1718 | 1718 | # a = A() |
|
1719 | 1719 | # a.__dict__['foobar'] = 345 |
|
1720 | 1720 | # a.foobar # == 123 |
|
1721 | 1721 | # |
|
1722 | 1722 | # So, a property may be returned right away. |
|
1723 | 1723 | if isinstance(attr, property): |
|
1724 | 1724 | return attr |
|
1725 | 1725 | |
|
1726 | 1726 | # Nothing helped, fall back. |
|
1727 | 1727 | return getattr(obj, attrname) |
|
1728 | 1728 | |
|
1729 | 1729 | def _object_find(self, oname, namespaces=None): |
|
1730 | 1730 | """Find an object and return a struct with info about it.""" |
|
1731 | 1731 | return Struct(self._ofind(oname, namespaces)) |
|
1732 | 1732 | |
|
1733 | 1733 | def _inspect(self, meth, oname, namespaces=None, **kw): |
|
1734 | 1734 | """Generic interface to the inspector system. |
|
1735 | 1735 | |
|
1736 | 1736 | This function is meant to be called by pdef, pdoc & friends. |
|
1737 | 1737 | """ |
|
1738 | 1738 | info = self._object_find(oname, namespaces) |
|
1739 | 1739 | docformat = sphinxify if self.sphinxify_docstring else None |
|
1740 | 1740 | if info.found: |
|
1741 | 1741 | pmethod = getattr(self.inspector, meth) |
|
1742 | 1742 | # TODO: only apply format_screen to the plain/text repr of the mime |
|
1743 | 1743 | # bundle. |
|
1744 | 1744 | formatter = format_screen if info.ismagic else docformat |
|
1745 | 1745 | if meth == 'pdoc': |
|
1746 | 1746 | pmethod(info.obj, oname, formatter) |
|
1747 | 1747 | elif meth == 'pinfo': |
|
1748 | 1748 | pmethod(info.obj, oname, formatter, info, |
|
1749 | 1749 | enable_html_pager=self.enable_html_pager, **kw) |
|
1750 | 1750 | else: |
|
1751 | 1751 | pmethod(info.obj, oname) |
|
1752 | 1752 | else: |
|
1753 | 1753 | print('Object `%s` not found.' % oname) |
|
1754 | 1754 | return 'not found' # so callers can take other action |
|
1755 | 1755 | |
|
1756 | 1756 | def object_inspect(self, oname, detail_level=0): |
|
1757 | 1757 | """Get object info about oname""" |
|
1758 | 1758 | with self.builtin_trap: |
|
1759 | 1759 | info = self._object_find(oname) |
|
1760 | 1760 | if info.found: |
|
1761 | 1761 | return self.inspector.info(info.obj, oname, info=info, |
|
1762 | 1762 | detail_level=detail_level |
|
1763 | 1763 | ) |
|
1764 | 1764 | else: |
|
1765 | 1765 | return oinspect.object_info(name=oname, found=False) |
|
1766 | 1766 | |
|
1767 | 1767 | def object_inspect_text(self, oname, detail_level=0): |
|
1768 | 1768 | """Get object info as formatted text""" |
|
1769 | 1769 | return self.object_inspect_mime(oname, detail_level)['text/plain'] |
|
1770 | 1770 | |
|
1771 | 1771 | def object_inspect_mime(self, oname, detail_level=0): |
|
1772 | 1772 | """Get object info as a mimebundle of formatted representations. |
|
1773 | 1773 | |
|
1774 | 1774 | A mimebundle is a dictionary, keyed by mime-type. |
|
1775 | 1775 | It must always have the key `'text/plain'`. |
|
1776 | 1776 | """ |
|
1777 | 1777 | with self.builtin_trap: |
|
1778 | 1778 | info = self._object_find(oname) |
|
1779 | 1779 | if info.found: |
|
1780 | 1780 | return self.inspector._get_info(info.obj, oname, info=info, |
|
1781 | 1781 | detail_level=detail_level |
|
1782 | 1782 | ) |
|
1783 | 1783 | else: |
|
1784 | 1784 | raise KeyError(oname) |
|
1785 | 1785 | |
|
1786 | 1786 | #------------------------------------------------------------------------- |
|
1787 | 1787 | # Things related to history management |
|
1788 | 1788 | #------------------------------------------------------------------------- |
|
1789 | 1789 | |
|
1790 | 1790 | def init_history(self): |
|
1791 | 1791 | """Sets up the command history, and starts regular autosaves.""" |
|
1792 | 1792 | self.history_manager = HistoryManager(shell=self, parent=self) |
|
1793 | 1793 | self.configurables.append(self.history_manager) |
|
1794 | 1794 | |
|
1795 | 1795 | #------------------------------------------------------------------------- |
|
1796 | 1796 | # Things related to exception handling and tracebacks (not debugging) |
|
1797 | 1797 | #------------------------------------------------------------------------- |
|
1798 | 1798 | |
|
1799 | 1799 | debugger_cls = Pdb |
|
1800 | 1800 | |
|
1801 | 1801 | def init_traceback_handlers(self, custom_exceptions): |
|
1802 | 1802 | # Syntax error handler. |
|
1803 | 1803 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self) |
|
1804 | 1804 | |
|
1805 | 1805 | # The interactive one is initialized with an offset, meaning we always |
|
1806 | 1806 | # want to remove the topmost item in the traceback, which is our own |
|
1807 | 1807 | # internal code. Valid modes: ['Plain','Context','Verbose','Minimal'] |
|
1808 | 1808 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1809 | 1809 | color_scheme='NoColor', |
|
1810 | 1810 | tb_offset = 1, |
|
1811 | 1811 | check_cache=check_linecache_ipython, |
|
1812 | 1812 | debugger_cls=self.debugger_cls, parent=self) |
|
1813 | 1813 | |
|
1814 | 1814 | # The instance will store a pointer to the system-wide exception hook, |
|
1815 | 1815 | # so that runtime code (such as magics) can access it. This is because |
|
1816 | 1816 | # during the read-eval loop, it may get temporarily overwritten. |
|
1817 | 1817 | self.sys_excepthook = sys.excepthook |
|
1818 | 1818 | |
|
1819 | 1819 | # and add any custom exception handlers the user may have specified |
|
1820 | 1820 | self.set_custom_exc(*custom_exceptions) |
|
1821 | 1821 | |
|
1822 | 1822 | # Set the exception mode |
|
1823 | 1823 | self.InteractiveTB.set_mode(mode=self.xmode) |
|
1824 | 1824 | |
|
1825 | 1825 | def set_custom_exc(self, exc_tuple, handler): |
|
1826 | 1826 | """set_custom_exc(exc_tuple, handler) |
|
1827 | 1827 | |
|
1828 | 1828 | Set a custom exception handler, which will be called if any of the |
|
1829 | 1829 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1830 | 1830 | run_code() method). |
|
1831 | 1831 | |
|
1832 | 1832 | Parameters |
|
1833 | 1833 | ---------- |
|
1834 | 1834 | |
|
1835 | 1835 | exc_tuple : tuple of exception classes |
|
1836 | 1836 | A *tuple* of exception classes, for which to call the defined |
|
1837 | 1837 | handler. It is very important that you use a tuple, and NOT A |
|
1838 | 1838 | LIST here, because of the way Python's except statement works. If |
|
1839 | 1839 | you only want to trap a single exception, use a singleton tuple:: |
|
1840 | 1840 | |
|
1841 | 1841 | exc_tuple == (MyCustomException,) |
|
1842 | 1842 | |
|
1843 | 1843 | handler : callable |
|
1844 | 1844 | handler must have the following signature:: |
|
1845 | 1845 | |
|
1846 | 1846 | def my_handler(self, etype, value, tb, tb_offset=None): |
|
1847 | 1847 | ... |
|
1848 | 1848 | return structured_traceback |
|
1849 | 1849 | |
|
1850 | 1850 | Your handler must return a structured traceback (a list of strings), |
|
1851 | 1851 | or None. |
|
1852 | 1852 | |
|
1853 | 1853 | This will be made into an instance method (via types.MethodType) |
|
1854 | 1854 | of IPython itself, and it will be called if any of the exceptions |
|
1855 | 1855 | listed in the exc_tuple are caught. If the handler is None, an |
|
1856 | 1856 | internal basic one is used, which just prints basic info. |
|
1857 | 1857 | |
|
1858 | 1858 | To protect IPython from crashes, if your handler ever raises an |
|
1859 | 1859 | exception or returns an invalid result, it will be immediately |
|
1860 | 1860 | disabled. |
|
1861 | 1861 | |
|
1862 | 1862 | WARNING: by putting in your own exception handler into IPython's main |
|
1863 | 1863 | execution loop, you run a very good chance of nasty crashes. This |
|
1864 | 1864 | facility should only be used if you really know what you are doing.""" |
|
1865 | 1865 | if not isinstance(exc_tuple, tuple): |
|
1866 | 1866 | raise TypeError("The custom exceptions must be given as a tuple.") |
|
1867 | 1867 | |
|
1868 | 1868 | def dummy_handler(self, etype, value, tb, tb_offset=None): |
|
1869 | 1869 | print('*** Simple custom exception handler ***') |
|
1870 | 1870 | print('Exception type :', etype) |
|
1871 | 1871 | print('Exception value:', value) |
|
1872 | 1872 | print('Traceback :', tb) |
|
1873 | 1873 | |
|
1874 | 1874 | def validate_stb(stb): |
|
1875 | 1875 | """validate structured traceback return type |
|
1876 | 1876 | |
|
1877 | 1877 | return type of CustomTB *should* be a list of strings, but allow |
|
1878 | 1878 | single strings or None, which are harmless. |
|
1879 | 1879 | |
|
1880 | 1880 | This function will *always* return a list of strings, |
|
1881 | 1881 | and will raise a TypeError if stb is inappropriate. |
|
1882 | 1882 | """ |
|
1883 | 1883 | msg = "CustomTB must return list of strings, not %r" % stb |
|
1884 | 1884 | if stb is None: |
|
1885 | 1885 | return [] |
|
1886 | 1886 | elif isinstance(stb, str): |
|
1887 | 1887 | return [stb] |
|
1888 | 1888 | elif not isinstance(stb, list): |
|
1889 | 1889 | raise TypeError(msg) |
|
1890 | 1890 | # it's a list |
|
1891 | 1891 | for line in stb: |
|
1892 | 1892 | # check every element |
|
1893 | 1893 | if not isinstance(line, str): |
|
1894 | 1894 | raise TypeError(msg) |
|
1895 | 1895 | return stb |
|
1896 | 1896 | |
|
1897 | 1897 | if handler is None: |
|
1898 | 1898 | wrapped = dummy_handler |
|
1899 | 1899 | else: |
|
1900 | 1900 | def wrapped(self,etype,value,tb,tb_offset=None): |
|
1901 | 1901 | """wrap CustomTB handler, to protect IPython from user code |
|
1902 | 1902 | |
|
1903 | 1903 | This makes it harder (but not impossible) for custom exception |
|
1904 | 1904 | handlers to crash IPython. |
|
1905 | 1905 | """ |
|
1906 | 1906 | try: |
|
1907 | 1907 | stb = handler(self,etype,value,tb,tb_offset=tb_offset) |
|
1908 | 1908 | return validate_stb(stb) |
|
1909 | 1909 | except: |
|
1910 | 1910 | # clear custom handler immediately |
|
1911 | 1911 | self.set_custom_exc((), None) |
|
1912 | 1912 | print("Custom TB Handler failed, unregistering", file=sys.stderr) |
|
1913 | 1913 | # show the exception in handler first |
|
1914 | 1914 | stb = self.InteractiveTB.structured_traceback(*sys.exc_info()) |
|
1915 | 1915 | print(self.InteractiveTB.stb2text(stb)) |
|
1916 | 1916 | print("The original exception:") |
|
1917 | 1917 | stb = self.InteractiveTB.structured_traceback( |
|
1918 | 1918 | (etype,value,tb), tb_offset=tb_offset |
|
1919 | 1919 | ) |
|
1920 | 1920 | return stb |
|
1921 | 1921 | |
|
1922 | 1922 | self.CustomTB = types.MethodType(wrapped,self) |
|
1923 | 1923 | self.custom_exceptions = exc_tuple |
|
1924 | 1924 | |
|
1925 | 1925 | def excepthook(self, etype, value, tb): |
|
1926 | 1926 | """One more defense for GUI apps that call sys.excepthook. |
|
1927 | 1927 | |
|
1928 | 1928 | GUI frameworks like wxPython trap exceptions and call |
|
1929 | 1929 | sys.excepthook themselves. I guess this is a feature that |
|
1930 | 1930 | enables them to keep running after exceptions that would |
|
1931 | 1931 | otherwise kill their mainloop. This is a bother for IPython |
|
1932 | 1932 | which excepts to catch all of the program exceptions with a try: |
|
1933 | 1933 | except: statement. |
|
1934 | 1934 | |
|
1935 | 1935 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1936 | 1936 | any app directly invokes sys.excepthook, it will look to the user like |
|
1937 | 1937 | IPython crashed. In order to work around this, we can disable the |
|
1938 | 1938 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1939 | 1939 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1940 | 1940 | call sys.excepthook will generate a regular-looking exception from |
|
1941 | 1941 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1942 | 1942 | crashes. |
|
1943 | 1943 | |
|
1944 | 1944 | This hook should be used sparingly, only in places which are not likely |
|
1945 | 1945 | to be true IPython errors. |
|
1946 | 1946 | """ |
|
1947 | 1947 | self.showtraceback((etype, value, tb), tb_offset=0) |
|
1948 | 1948 | |
|
1949 | 1949 | def _get_exc_info(self, exc_tuple=None): |
|
1950 | 1950 | """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc. |
|
1951 | 1951 | |
|
1952 | 1952 | Ensures sys.last_type,value,traceback hold the exc_info we found, |
|
1953 | 1953 | from whichever source. |
|
1954 | 1954 | |
|
1955 | 1955 | raises ValueError if none of these contain any information |
|
1956 | 1956 | """ |
|
1957 | 1957 | if exc_tuple is None: |
|
1958 | 1958 | etype, value, tb = sys.exc_info() |
|
1959 | 1959 | else: |
|
1960 | 1960 | etype, value, tb = exc_tuple |
|
1961 | 1961 | |
|
1962 | 1962 | if etype is None: |
|
1963 | 1963 | if hasattr(sys, 'last_type'): |
|
1964 | 1964 | etype, value, tb = sys.last_type, sys.last_value, \ |
|
1965 | 1965 | sys.last_traceback |
|
1966 | 1966 | |
|
1967 | 1967 | if etype is None: |
|
1968 | 1968 | raise ValueError("No exception to find") |
|
1969 | 1969 | |
|
1970 | 1970 | # Now store the exception info in sys.last_type etc. |
|
1971 | 1971 | # WARNING: these variables are somewhat deprecated and not |
|
1972 | 1972 | # necessarily safe to use in a threaded environment, but tools |
|
1973 | 1973 | # like pdb depend on their existence, so let's set them. If we |
|
1974 | 1974 | # find problems in the field, we'll need to revisit their use. |
|
1975 | 1975 | sys.last_type = etype |
|
1976 | 1976 | sys.last_value = value |
|
1977 | 1977 | sys.last_traceback = tb |
|
1978 | 1978 | |
|
1979 | 1979 | return etype, value, tb |
|
1980 | 1980 | |
|
1981 | 1981 | def show_usage_error(self, exc): |
|
1982 | 1982 | """Show a short message for UsageErrors |
|
1983 | 1983 | |
|
1984 | 1984 | These are special exceptions that shouldn't show a traceback. |
|
1985 | 1985 | """ |
|
1986 | 1986 | print("UsageError: %s" % exc, file=sys.stderr) |
|
1987 | 1987 | |
|
1988 | 1988 | def get_exception_only(self, exc_tuple=None): |
|
1989 | 1989 | """ |
|
1990 | 1990 | Return as a string (ending with a newline) the exception that |
|
1991 | 1991 | just occurred, without any traceback. |
|
1992 | 1992 | """ |
|
1993 | 1993 | etype, value, tb = self._get_exc_info(exc_tuple) |
|
1994 | 1994 | msg = traceback.format_exception_only(etype, value) |
|
1995 | 1995 | return ''.join(msg) |
|
1996 | 1996 | |
|
1997 | 1997 | def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None, |
|
1998 | 1998 | exception_only=False, running_compiled_code=False): |
|
1999 | 1999 | """Display the exception that just occurred. |
|
2000 | 2000 | |
|
2001 | 2001 | If nothing is known about the exception, this is the method which |
|
2002 | 2002 | should be used throughout the code for presenting user tracebacks, |
|
2003 | 2003 | rather than directly invoking the InteractiveTB object. |
|
2004 | 2004 | |
|
2005 | 2005 | A specific showsyntaxerror() also exists, but this method can take |
|
2006 | 2006 | care of calling it if needed, so unless you are explicitly catching a |
|
2007 | 2007 | SyntaxError exception, don't try to analyze the stack manually and |
|
2008 | 2008 | simply call this method.""" |
|
2009 | 2009 | |
|
2010 | 2010 | try: |
|
2011 | 2011 | try: |
|
2012 | 2012 | etype, value, tb = self._get_exc_info(exc_tuple) |
|
2013 | 2013 | except ValueError: |
|
2014 | 2014 | print('No traceback available to show.', file=sys.stderr) |
|
2015 | 2015 | return |
|
2016 | 2016 | |
|
2017 | 2017 | if issubclass(etype, SyntaxError): |
|
2018 | 2018 | # Though this won't be called by syntax errors in the input |
|
2019 | 2019 | # line, there may be SyntaxError cases with imported code. |
|
2020 | 2020 | self.showsyntaxerror(filename, running_compiled_code) |
|
2021 | 2021 | elif etype is UsageError: |
|
2022 | 2022 | self.show_usage_error(value) |
|
2023 | 2023 | else: |
|
2024 | 2024 | if exception_only: |
|
2025 | 2025 | stb = ['An exception has occurred, use %tb to see ' |
|
2026 | 2026 | 'the full traceback.\n'] |
|
2027 | 2027 | stb.extend(self.InteractiveTB.get_exception_only(etype, |
|
2028 | 2028 | value)) |
|
2029 | 2029 | else: |
|
2030 | 2030 | try: |
|
2031 | 2031 | # Exception classes can customise their traceback - we |
|
2032 | 2032 | # use this in IPython.parallel for exceptions occurring |
|
2033 | 2033 | # in the engines. This should return a list of strings. |
|
2034 | 2034 | stb = value._render_traceback_() |
|
2035 | 2035 | except Exception: |
|
2036 | 2036 | stb = self.InteractiveTB.structured_traceback(etype, |
|
2037 | 2037 | value, tb, tb_offset=tb_offset) |
|
2038 | 2038 | |
|
2039 | 2039 | self._showtraceback(etype, value, stb) |
|
2040 | 2040 | if self.call_pdb: |
|
2041 | 2041 | # drop into debugger |
|
2042 | 2042 | self.debugger(force=True) |
|
2043 | 2043 | return |
|
2044 | 2044 | |
|
2045 | 2045 | # Actually show the traceback |
|
2046 | 2046 | self._showtraceback(etype, value, stb) |
|
2047 | 2047 | |
|
2048 | 2048 | except KeyboardInterrupt: |
|
2049 | 2049 | print('\n' + self.get_exception_only(), file=sys.stderr) |
|
2050 | 2050 | |
|
2051 | 2051 | def _showtraceback(self, etype, evalue, stb): |
|
2052 | 2052 | """Actually show a traceback. |
|
2053 | 2053 | |
|
2054 | 2054 | Subclasses may override this method to put the traceback on a different |
|
2055 | 2055 | place, like a side channel. |
|
2056 | 2056 | """ |
|
2057 | 2057 | print(self.InteractiveTB.stb2text(stb)) |
|
2058 | 2058 | |
|
2059 | 2059 | def showsyntaxerror(self, filename=None, running_compiled_code=False): |
|
2060 | 2060 | """Display the syntax error that just occurred. |
|
2061 | 2061 | |
|
2062 | 2062 | This doesn't display a stack trace because there isn't one. |
|
2063 | 2063 | |
|
2064 | 2064 | If a filename is given, it is stuffed in the exception instead |
|
2065 | 2065 | of what was there before (because Python's parser always uses |
|
2066 | 2066 | "<string>" when reading from a string). |
|
2067 | 2067 | |
|
2068 | 2068 | If the syntax error occurred when running a compiled code (i.e. running_compile_code=True), |
|
2069 | 2069 | longer stack trace will be displayed. |
|
2070 | 2070 | """ |
|
2071 | 2071 | etype, value, last_traceback = self._get_exc_info() |
|
2072 | 2072 | |
|
2073 | 2073 | if filename and issubclass(etype, SyntaxError): |
|
2074 | 2074 | try: |
|
2075 | 2075 | value.filename = filename |
|
2076 | 2076 | except: |
|
2077 | 2077 | # Not the format we expect; leave it alone |
|
2078 | 2078 | pass |
|
2079 | 2079 | |
|
2080 | 2080 | # If the error occurred when executing compiled code, we should provide full stacktrace. |
|
2081 | 2081 | elist = traceback.extract_tb(last_traceback) if running_compiled_code else [] |
|
2082 | 2082 | stb = self.SyntaxTB.structured_traceback(etype, value, elist) |
|
2083 | 2083 | self._showtraceback(etype, value, stb) |
|
2084 | 2084 | |
|
2085 | 2085 | # This is overridden in TerminalInteractiveShell to show a message about |
|
2086 | 2086 | # the %paste magic. |
|
2087 | 2087 | def showindentationerror(self): |
|
2088 | 2088 | """Called by _run_cell when there's an IndentationError in code entered |
|
2089 | 2089 | at the prompt. |
|
2090 | 2090 | |
|
2091 | 2091 | This is overridden in TerminalInteractiveShell to show a message about |
|
2092 | 2092 | the %paste magic.""" |
|
2093 | 2093 | self.showsyntaxerror() |
|
2094 | 2094 | |
|
2095 | 2095 | #------------------------------------------------------------------------- |
|
2096 | 2096 | # Things related to readline |
|
2097 | 2097 | #------------------------------------------------------------------------- |
|
2098 | 2098 | |
|
2099 | 2099 | def init_readline(self): |
|
2100 | 2100 | """DEPRECATED |
|
2101 | 2101 | |
|
2102 | 2102 | Moved to terminal subclass, here only to simplify the init logic.""" |
|
2103 | 2103 | # Set a number of methods that depend on readline to be no-op |
|
2104 | 2104 | warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated', |
|
2105 | 2105 | DeprecationWarning, stacklevel=2) |
|
2106 | 2106 | self.set_custom_completer = no_op |
|
2107 | 2107 | |
|
2108 | 2108 | @skip_doctest |
|
2109 | 2109 | def set_next_input(self, s, replace=False): |
|
2110 | 2110 | """ Sets the 'default' input string for the next command line. |
|
2111 | 2111 | |
|
2112 | 2112 | Example:: |
|
2113 | 2113 | |
|
2114 | 2114 | In [1]: _ip.set_next_input("Hello Word") |
|
2115 | 2115 | In [2]: Hello Word_ # cursor is here |
|
2116 | 2116 | """ |
|
2117 | 2117 | self.rl_next_input = s |
|
2118 | 2118 | |
|
2119 | 2119 | def _indent_current_str(self): |
|
2120 | 2120 | """return the current level of indentation as a string""" |
|
2121 | 2121 | return self.input_splitter.get_indent_spaces() * ' ' |
|
2122 | 2122 | |
|
2123 | 2123 | #------------------------------------------------------------------------- |
|
2124 | 2124 | # Things related to text completion |
|
2125 | 2125 | #------------------------------------------------------------------------- |
|
2126 | 2126 | |
|
2127 | 2127 | def init_completer(self): |
|
2128 | 2128 | """Initialize the completion machinery. |
|
2129 | 2129 | |
|
2130 | 2130 | This creates completion machinery that can be used by client code, |
|
2131 | 2131 | either interactively in-process (typically triggered by the readline |
|
2132 | 2132 | library), programmatically (such as in test suites) or out-of-process |
|
2133 | 2133 | (typically over the network by remote frontends). |
|
2134 | 2134 | """ |
|
2135 | 2135 | from IPython.core.completer import IPCompleter |
|
2136 | 2136 | from IPython.core.completerlib import (module_completer, |
|
2137 | 2137 | magic_run_completer, cd_completer, reset_completer) |
|
2138 | 2138 | |
|
2139 | 2139 | self.Completer = IPCompleter(shell=self, |
|
2140 | 2140 | namespace=self.user_ns, |
|
2141 | 2141 | global_namespace=self.user_global_ns, |
|
2142 | 2142 | parent=self, |
|
2143 | 2143 | ) |
|
2144 | 2144 | self.configurables.append(self.Completer) |
|
2145 | 2145 | |
|
2146 | 2146 | # Add custom completers to the basic ones built into IPCompleter |
|
2147 | 2147 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
2148 | 2148 | self.strdispatchers['complete_command'] = sdisp |
|
2149 | 2149 | self.Completer.custom_completers = sdisp |
|
2150 | 2150 | |
|
2151 | 2151 | self.set_hook('complete_command', module_completer, str_key = 'import') |
|
2152 | 2152 | self.set_hook('complete_command', module_completer, str_key = 'from') |
|
2153 | 2153 | self.set_hook('complete_command', module_completer, str_key = '%aimport') |
|
2154 | 2154 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') |
|
2155 | 2155 | self.set_hook('complete_command', cd_completer, str_key = '%cd') |
|
2156 | 2156 | self.set_hook('complete_command', reset_completer, str_key = '%reset') |
|
2157 | 2157 | |
|
2158 | 2158 | @skip_doctest |
|
2159 | 2159 | def complete(self, text, line=None, cursor_pos=None): |
|
2160 | 2160 | """Return the completed text and a list of completions. |
|
2161 | 2161 | |
|
2162 | 2162 | Parameters |
|
2163 | 2163 | ---------- |
|
2164 | 2164 | |
|
2165 | 2165 | text : string |
|
2166 | 2166 | A string of text to be completed on. It can be given as empty and |
|
2167 | 2167 | instead a line/position pair are given. In this case, the |
|
2168 | 2168 | completer itself will split the line like readline does. |
|
2169 | 2169 | |
|
2170 | 2170 | line : string, optional |
|
2171 | 2171 | The complete line that text is part of. |
|
2172 | 2172 | |
|
2173 | 2173 | cursor_pos : int, optional |
|
2174 | 2174 | The position of the cursor on the input line. |
|
2175 | 2175 | |
|
2176 | 2176 | Returns |
|
2177 | 2177 | ------- |
|
2178 | 2178 | text : string |
|
2179 | 2179 | The actual text that was completed. |
|
2180 | 2180 | |
|
2181 | 2181 | matches : list |
|
2182 | 2182 | A sorted list with all possible completions. |
|
2183 | 2183 | |
|
2184 | 2184 | The optional arguments allow the completion to take more context into |
|
2185 | 2185 | account, and are part of the low-level completion API. |
|
2186 | 2186 | |
|
2187 | 2187 | This is a wrapper around the completion mechanism, similar to what |
|
2188 | 2188 | readline does at the command line when the TAB key is hit. By |
|
2189 | 2189 | exposing it as a method, it can be used by other non-readline |
|
2190 | 2190 | environments (such as GUIs) for text completion. |
|
2191 | 2191 | |
|
2192 | 2192 | Simple usage example: |
|
2193 | 2193 | |
|
2194 | 2194 | In [1]: x = 'hello' |
|
2195 | 2195 | |
|
2196 | 2196 | In [2]: _ip.complete('x.l') |
|
2197 | 2197 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) |
|
2198 | 2198 | """ |
|
2199 | 2199 | |
|
2200 | 2200 | # Inject names into __builtin__ so we can complete on the added names. |
|
2201 | 2201 | with self.builtin_trap: |
|
2202 | 2202 | return self.Completer.complete(text, line, cursor_pos) |
|
2203 | 2203 | |
|
2204 | 2204 | def set_custom_completer(self, completer, pos=0): |
|
2205 | 2205 | """Adds a new custom completer function. |
|
2206 | 2206 | |
|
2207 | 2207 | The position argument (defaults to 0) is the index in the completers |
|
2208 | 2208 | list where you want the completer to be inserted.""" |
|
2209 | 2209 | |
|
2210 | 2210 | newcomp = types.MethodType(completer,self.Completer) |
|
2211 | 2211 | self.Completer.matchers.insert(pos,newcomp) |
|
2212 | 2212 | |
|
2213 | 2213 | def set_completer_frame(self, frame=None): |
|
2214 | 2214 | """Set the frame of the completer.""" |
|
2215 | 2215 | if frame: |
|
2216 | 2216 | self.Completer.namespace = frame.f_locals |
|
2217 | 2217 | self.Completer.global_namespace = frame.f_globals |
|
2218 | 2218 | else: |
|
2219 | 2219 | self.Completer.namespace = self.user_ns |
|
2220 | 2220 | self.Completer.global_namespace = self.user_global_ns |
|
2221 | 2221 | |
|
2222 | 2222 | #------------------------------------------------------------------------- |
|
2223 | 2223 | # Things related to magics |
|
2224 | 2224 | #------------------------------------------------------------------------- |
|
2225 | 2225 | |
|
2226 | 2226 | def init_magics(self): |
|
2227 | 2227 | from IPython.core import magics as m |
|
2228 | 2228 | self.magics_manager = magic.MagicsManager(shell=self, |
|
2229 | 2229 | parent=self, |
|
2230 | 2230 | user_magics=m.UserMagics(self)) |
|
2231 | 2231 | self.configurables.append(self.magics_manager) |
|
2232 | 2232 | |
|
2233 | 2233 | # Expose as public API from the magics manager |
|
2234 | 2234 | self.register_magics = self.magics_manager.register |
|
2235 | 2235 | |
|
2236 | 2236 | self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics, |
|
2237 | 2237 | m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics, |
|
2238 | 2238 | m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics, |
|
2239 | 2239 | m.NamespaceMagics, m.OSMagics, m.PackagingMagics, |
|
2240 | 2240 | m.PylabMagics, m.ScriptMagics, |
|
2241 | 2241 | ) |
|
2242 | 2242 | self.register_magics(m.AsyncMagics) |
|
2243 | 2243 | |
|
2244 | 2244 | # Register Magic Aliases |
|
2245 | 2245 | mman = self.magics_manager |
|
2246 | 2246 | # FIXME: magic aliases should be defined by the Magics classes |
|
2247 | 2247 | # or in MagicsManager, not here |
|
2248 | 2248 | mman.register_alias('ed', 'edit') |
|
2249 | 2249 | mman.register_alias('hist', 'history') |
|
2250 | 2250 | mman.register_alias('rep', 'recall') |
|
2251 | 2251 | mman.register_alias('SVG', 'svg', 'cell') |
|
2252 | 2252 | mman.register_alias('HTML', 'html', 'cell') |
|
2253 | 2253 | mman.register_alias('file', 'writefile', 'cell') |
|
2254 | 2254 | |
|
2255 | 2255 | # FIXME: Move the color initialization to the DisplayHook, which |
|
2256 | 2256 | # should be split into a prompt manager and displayhook. We probably |
|
2257 | 2257 | # even need a centralize colors management object. |
|
2258 | 2258 | self.run_line_magic('colors', self.colors) |
|
2259 | 2259 | |
|
2260 | 2260 | # Defined here so that it's included in the documentation |
|
2261 | 2261 | @functools.wraps(magic.MagicsManager.register_function) |
|
2262 | 2262 | def register_magic_function(self, func, magic_kind='line', magic_name=None): |
|
2263 | 2263 | self.magics_manager.register_function(func, |
|
2264 | 2264 | magic_kind=magic_kind, magic_name=magic_name) |
|
2265 | 2265 | |
|
2266 | 2266 | def run_line_magic(self, magic_name, line, _stack_depth=1): |
|
2267 | 2267 | """Execute the given line magic. |
|
2268 | 2268 | |
|
2269 | 2269 | Parameters |
|
2270 | 2270 | ---------- |
|
2271 | 2271 | magic_name : str |
|
2272 | 2272 | Name of the desired magic function, without '%' prefix. |
|
2273 | 2273 | |
|
2274 | 2274 | line : str |
|
2275 | 2275 | The rest of the input line as a single string. |
|
2276 | 2276 | |
|
2277 | 2277 | _stack_depth : int |
|
2278 | 2278 | If run_line_magic() is called from magic() then _stack_depth=2. |
|
2279 | 2279 | This is added to ensure backward compatibility for use of 'get_ipython().magic()' |
|
2280 | 2280 | """ |
|
2281 | 2281 | fn = self.find_line_magic(magic_name) |
|
2282 | 2282 | if fn is None: |
|
2283 | 2283 | cm = self.find_cell_magic(magic_name) |
|
2284 | 2284 | etpl = "Line magic function `%%%s` not found%s." |
|
2285 | 2285 | extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, ' |
|
2286 | 2286 | 'did you mean that instead?)' % magic_name ) |
|
2287 | 2287 | raise UsageError(etpl % (magic_name, extra)) |
|
2288 | 2288 | else: |
|
2289 | 2289 | # Note: this is the distance in the stack to the user's frame. |
|
2290 | 2290 | # This will need to be updated if the internal calling logic gets |
|
2291 | 2291 | # refactored, or else we'll be expanding the wrong variables. |
|
2292 | 2292 | |
|
2293 | 2293 | # Determine stack_depth depending on where run_line_magic() has been called |
|
2294 | 2294 | stack_depth = _stack_depth |
|
2295 | 2295 | if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False): |
|
2296 | 2296 | # magic has opted out of var_expand |
|
2297 | 2297 | magic_arg_s = line |
|
2298 | 2298 | else: |
|
2299 | 2299 | magic_arg_s = self.var_expand(line, stack_depth) |
|
2300 | 2300 | # Put magic args in a list so we can call with f(*a) syntax |
|
2301 | 2301 | args = [magic_arg_s] |
|
2302 | 2302 | kwargs = {} |
|
2303 | 2303 | # Grab local namespace if we need it: |
|
2304 | 2304 | if getattr(fn, "needs_local_scope", False): |
|
2305 | 2305 | kwargs['local_ns'] = sys._getframe(stack_depth).f_locals |
|
2306 | 2306 | with self.builtin_trap: |
|
2307 | 2307 | result = fn(*args, **kwargs) |
|
2308 | 2308 | return result |
|
2309 | 2309 | |
|
2310 | 2310 | def run_cell_magic(self, magic_name, line, cell): |
|
2311 | 2311 | """Execute the given cell magic. |
|
2312 | 2312 | |
|
2313 | 2313 | Parameters |
|
2314 | 2314 | ---------- |
|
2315 | 2315 | magic_name : str |
|
2316 | 2316 | Name of the desired magic function, without '%' prefix. |
|
2317 | 2317 | |
|
2318 | 2318 | line : str |
|
2319 | 2319 | The rest of the first input line as a single string. |
|
2320 | 2320 | |
|
2321 | 2321 | cell : str |
|
2322 | 2322 | The body of the cell as a (possibly multiline) string. |
|
2323 | 2323 | """ |
|
2324 | 2324 | fn = self.find_cell_magic(magic_name) |
|
2325 | 2325 | if fn is None: |
|
2326 | 2326 | lm = self.find_line_magic(magic_name) |
|
2327 | 2327 | etpl = "Cell magic `%%{0}` not found{1}." |
|
2328 | 2328 | extra = '' if lm is None else (' (But line magic `%{0}` exists, ' |
|
2329 | 2329 | 'did you mean that instead?)'.format(magic_name)) |
|
2330 | 2330 | raise UsageError(etpl.format(magic_name, extra)) |
|
2331 | 2331 | elif cell == '': |
|
2332 | 2332 | message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name) |
|
2333 | 2333 | if self.find_line_magic(magic_name) is not None: |
|
2334 | 2334 | message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name) |
|
2335 | 2335 | raise UsageError(message) |
|
2336 | 2336 | else: |
|
2337 | 2337 | # Note: this is the distance in the stack to the user's frame. |
|
2338 | 2338 | # This will need to be updated if the internal calling logic gets |
|
2339 | 2339 | # refactored, or else we'll be expanding the wrong variables. |
|
2340 | 2340 | stack_depth = 2 |
|
2341 | 2341 | if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False): |
|
2342 | 2342 | # magic has opted out of var_expand |
|
2343 | 2343 | magic_arg_s = line |
|
2344 | 2344 | else: |
|
2345 | 2345 | magic_arg_s = self.var_expand(line, stack_depth) |
|
2346 | 2346 | kwargs = {} |
|
2347 | 2347 | if getattr(fn, "needs_local_scope", False): |
|
2348 | 2348 | kwargs['local_ns'] = self.user_ns |
|
2349 | 2349 | |
|
2350 | 2350 | with self.builtin_trap: |
|
2351 | 2351 | args = (magic_arg_s, cell) |
|
2352 | 2352 | result = fn(*args, **kwargs) |
|
2353 | 2353 | return result |
|
2354 | 2354 | |
|
2355 | 2355 | def find_line_magic(self, magic_name): |
|
2356 | 2356 | """Find and return a line magic by name. |
|
2357 | 2357 | |
|
2358 | 2358 | Returns None if the magic isn't found.""" |
|
2359 | 2359 | return self.magics_manager.magics['line'].get(magic_name) |
|
2360 | 2360 | |
|
2361 | 2361 | def find_cell_magic(self, magic_name): |
|
2362 | 2362 | """Find and return a cell magic by name. |
|
2363 | 2363 | |
|
2364 | 2364 | Returns None if the magic isn't found.""" |
|
2365 | 2365 | return self.magics_manager.magics['cell'].get(magic_name) |
|
2366 | 2366 | |
|
2367 | 2367 | def find_magic(self, magic_name, magic_kind='line'): |
|
2368 | 2368 | """Find and return a magic of the given type by name. |
|
2369 | 2369 | |
|
2370 | 2370 | Returns None if the magic isn't found.""" |
|
2371 | 2371 | return self.magics_manager.magics[magic_kind].get(magic_name) |
|
2372 | 2372 | |
|
2373 | 2373 | def magic(self, arg_s): |
|
2374 | 2374 | """DEPRECATED. Use run_line_magic() instead. |
|
2375 | 2375 | |
|
2376 | 2376 | Call a magic function by name. |
|
2377 | 2377 | |
|
2378 | 2378 | Input: a string containing the name of the magic function to call and |
|
2379 | 2379 | any additional arguments to be passed to the magic. |
|
2380 | 2380 | |
|
2381 | 2381 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
2382 | 2382 | prompt: |
|
2383 | 2383 | |
|
2384 | 2384 | In[1]: %name -opt foo bar |
|
2385 | 2385 | |
|
2386 | 2386 | To call a magic without arguments, simply use magic('name'). |
|
2387 | 2387 | |
|
2388 | 2388 | This provides a proper Python function to call IPython's magics in any |
|
2389 | 2389 | valid Python code you can type at the interpreter, including loops and |
|
2390 | 2390 | compound statements. |
|
2391 | 2391 | """ |
|
2392 | 2392 | # TODO: should we issue a loud deprecation warning here? |
|
2393 | 2393 | magic_name, _, magic_arg_s = arg_s.partition(' ') |
|
2394 | 2394 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
2395 | 2395 | return self.run_line_magic(magic_name, magic_arg_s, _stack_depth=2) |
|
2396 | 2396 | |
|
2397 | 2397 | #------------------------------------------------------------------------- |
|
2398 | 2398 | # Things related to macros |
|
2399 | 2399 | #------------------------------------------------------------------------- |
|
2400 | 2400 | |
|
2401 | 2401 | def define_macro(self, name, themacro): |
|
2402 | 2402 | """Define a new macro |
|
2403 | 2403 | |
|
2404 | 2404 | Parameters |
|
2405 | 2405 | ---------- |
|
2406 | 2406 | name : str |
|
2407 | 2407 | The name of the macro. |
|
2408 | 2408 | themacro : str or Macro |
|
2409 | 2409 | The action to do upon invoking the macro. If a string, a new |
|
2410 | 2410 | Macro object is created by passing the string to it. |
|
2411 | 2411 | """ |
|
2412 | 2412 | |
|
2413 | 2413 | from IPython.core import macro |
|
2414 | 2414 | |
|
2415 | 2415 | if isinstance(themacro, str): |
|
2416 | 2416 | themacro = macro.Macro(themacro) |
|
2417 | 2417 | if not isinstance(themacro, macro.Macro): |
|
2418 | 2418 | raise ValueError('A macro must be a string or a Macro instance.') |
|
2419 | 2419 | self.user_ns[name] = themacro |
|
2420 | 2420 | |
|
2421 | 2421 | #------------------------------------------------------------------------- |
|
2422 | 2422 | # Things related to the running of system commands |
|
2423 | 2423 | #------------------------------------------------------------------------- |
|
2424 | 2424 | |
|
2425 | 2425 | def system_piped(self, cmd): |
|
2426 | 2426 | """Call the given cmd in a subprocess, piping stdout/err |
|
2427 | 2427 | |
|
2428 | 2428 | Parameters |
|
2429 | 2429 | ---------- |
|
2430 | 2430 | cmd : str |
|
2431 | 2431 | Command to execute (can not end in '&', as background processes are |
|
2432 | 2432 | not supported. Should not be a command that expects input |
|
2433 | 2433 | other than simple text. |
|
2434 | 2434 | """ |
|
2435 | 2435 | if cmd.rstrip().endswith('&'): |
|
2436 | 2436 | # this is *far* from a rigorous test |
|
2437 | 2437 | # We do not support backgrounding processes because we either use |
|
2438 | 2438 | # pexpect or pipes to read from. Users can always just call |
|
2439 | 2439 | # os.system() or use ip.system=ip.system_raw |
|
2440 | 2440 | # if they really want a background process. |
|
2441 | 2441 | raise OSError("Background processes not supported.") |
|
2442 | 2442 | |
|
2443 | 2443 | # we explicitly do NOT return the subprocess status code, because |
|
2444 | 2444 | # a non-None value would trigger :func:`sys.displayhook` calls. |
|
2445 | 2445 | # Instead, we store the exit_code in user_ns. |
|
2446 | 2446 | self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1)) |
|
2447 | 2447 | |
|
2448 | 2448 | def system_raw(self, cmd): |
|
2449 | 2449 | """Call the given cmd in a subprocess using os.system on Windows or |
|
2450 | 2450 | subprocess.call using the system shell on other platforms. |
|
2451 | 2451 | |
|
2452 | 2452 | Parameters |
|
2453 | 2453 | ---------- |
|
2454 | 2454 | cmd : str |
|
2455 | 2455 | Command to execute. |
|
2456 | 2456 | """ |
|
2457 | 2457 | cmd = self.var_expand(cmd, depth=1) |
|
2458 | 2458 | # protect os.system from UNC paths on Windows, which it can't handle: |
|
2459 | 2459 | if sys.platform == 'win32': |
|
2460 | 2460 | from IPython.utils._process_win32 import AvoidUNCPath |
|
2461 | 2461 | with AvoidUNCPath() as path: |
|
2462 | 2462 | if path is not None: |
|
2463 | 2463 | cmd = '"pushd %s &&"%s' % (path, cmd) |
|
2464 | 2464 | try: |
|
2465 | 2465 | ec = os.system(cmd) |
|
2466 | 2466 | except KeyboardInterrupt: |
|
2467 | 2467 | print('\n' + self.get_exception_only(), file=sys.stderr) |
|
2468 | 2468 | ec = -2 |
|
2469 | 2469 | else: |
|
2470 | 2470 | # For posix the result of the subprocess.call() below is an exit |
|
2471 | 2471 | # code, which by convention is zero for success, positive for |
|
2472 | 2472 | # program failure. Exit codes above 128 are reserved for signals, |
|
2473 | 2473 | # and the formula for converting a signal to an exit code is usually |
|
2474 | 2474 | # signal_number+128. To more easily differentiate between exit |
|
2475 | 2475 | # codes and signals, ipython uses negative numbers. For instance |
|
2476 | 2476 | # since control-c is signal 2 but exit code 130, ipython's |
|
2477 | 2477 | # _exit_code variable will read -2. Note that some shells like |
|
2478 | 2478 | # csh and fish don't follow sh/bash conventions for exit codes. |
|
2479 | 2479 | executable = os.environ.get('SHELL', None) |
|
2480 | 2480 | try: |
|
2481 | 2481 | # Use env shell instead of default /bin/sh |
|
2482 | 2482 | ec = subprocess.call(cmd, shell=True, executable=executable) |
|
2483 | 2483 | except KeyboardInterrupt: |
|
2484 | 2484 | # intercept control-C; a long traceback is not useful here |
|
2485 | 2485 | print('\n' + self.get_exception_only(), file=sys.stderr) |
|
2486 | 2486 | ec = 130 |
|
2487 | 2487 | if ec > 128: |
|
2488 | 2488 | ec = -(ec - 128) |
|
2489 | 2489 | |
|
2490 | 2490 | # We explicitly do NOT return the subprocess status code, because |
|
2491 | 2491 | # a non-None value would trigger :func:`sys.displayhook` calls. |
|
2492 | 2492 | # Instead, we store the exit_code in user_ns. Note the semantics |
|
2493 | 2493 | # of _exit_code: for control-c, _exit_code == -signal.SIGNIT, |
|
2494 | 2494 | # but raising SystemExit(_exit_code) will give status 254! |
|
2495 | 2495 | self.user_ns['_exit_code'] = ec |
|
2496 | 2496 | |
|
2497 | 2497 | # use piped system by default, because it is better behaved |
|
2498 | 2498 | system = system_piped |
|
2499 | 2499 | |
|
2500 | 2500 | def getoutput(self, cmd, split=True, depth=0): |
|
2501 | 2501 | """Get output (possibly including stderr) from a subprocess. |
|
2502 | 2502 | |
|
2503 | 2503 | Parameters |
|
2504 | 2504 | ---------- |
|
2505 | 2505 | cmd : str |
|
2506 | 2506 | Command to execute (can not end in '&', as background processes are |
|
2507 | 2507 | not supported. |
|
2508 | 2508 | split : bool, optional |
|
2509 | 2509 | If True, split the output into an IPython SList. Otherwise, an |
|
2510 | 2510 | IPython LSString is returned. These are objects similar to normal |
|
2511 | 2511 | lists and strings, with a few convenience attributes for easier |
|
2512 | 2512 | manipulation of line-based output. You can use '?' on them for |
|
2513 | 2513 | details. |
|
2514 | 2514 | depth : int, optional |
|
2515 | 2515 | How many frames above the caller are the local variables which should |
|
2516 | 2516 | be expanded in the command string? The default (0) assumes that the |
|
2517 | 2517 | expansion variables are in the stack frame calling this function. |
|
2518 | 2518 | """ |
|
2519 | 2519 | if cmd.rstrip().endswith('&'): |
|
2520 | 2520 | # this is *far* from a rigorous test |
|
2521 | 2521 | raise OSError("Background processes not supported.") |
|
2522 | 2522 | out = getoutput(self.var_expand(cmd, depth=depth+1)) |
|
2523 | 2523 | if split: |
|
2524 | 2524 | out = SList(out.splitlines()) |
|
2525 | 2525 | else: |
|
2526 | 2526 | out = LSString(out) |
|
2527 | 2527 | return out |
|
2528 | 2528 | |
|
2529 | 2529 | #------------------------------------------------------------------------- |
|
2530 | 2530 | # Things related to aliases |
|
2531 | 2531 | #------------------------------------------------------------------------- |
|
2532 | 2532 | |
|
2533 | 2533 | def init_alias(self): |
|
2534 | 2534 | self.alias_manager = AliasManager(shell=self, parent=self) |
|
2535 | 2535 | self.configurables.append(self.alias_manager) |
|
2536 | 2536 | |
|
2537 | 2537 | #------------------------------------------------------------------------- |
|
2538 | 2538 | # Things related to extensions |
|
2539 | 2539 | #------------------------------------------------------------------------- |
|
2540 | 2540 | |
|
2541 | 2541 | def init_extension_manager(self): |
|
2542 | 2542 | self.extension_manager = ExtensionManager(shell=self, parent=self) |
|
2543 | 2543 | self.configurables.append(self.extension_manager) |
|
2544 | 2544 | |
|
2545 | 2545 | #------------------------------------------------------------------------- |
|
2546 | 2546 | # Things related to payloads |
|
2547 | 2547 | #------------------------------------------------------------------------- |
|
2548 | 2548 | |
|
2549 | 2549 | def init_payload(self): |
|
2550 | 2550 | self.payload_manager = PayloadManager(parent=self) |
|
2551 | 2551 | self.configurables.append(self.payload_manager) |
|
2552 | 2552 | |
|
2553 | 2553 | #------------------------------------------------------------------------- |
|
2554 | 2554 | # Things related to the prefilter |
|
2555 | 2555 | #------------------------------------------------------------------------- |
|
2556 | 2556 | |
|
2557 | 2557 | def init_prefilter(self): |
|
2558 | 2558 | self.prefilter_manager = PrefilterManager(shell=self, parent=self) |
|
2559 | 2559 | self.configurables.append(self.prefilter_manager) |
|
2560 | 2560 | # Ultimately this will be refactored in the new interpreter code, but |
|
2561 | 2561 | # for now, we should expose the main prefilter method (there's legacy |
|
2562 | 2562 | # code out there that may rely on this). |
|
2563 | 2563 | self.prefilter = self.prefilter_manager.prefilter_lines |
|
2564 | 2564 | |
|
2565 | 2565 | def auto_rewrite_input(self, cmd): |
|
2566 | 2566 | """Print to the screen the rewritten form of the user's command. |
|
2567 | 2567 | |
|
2568 | 2568 | This shows visual feedback by rewriting input lines that cause |
|
2569 | 2569 | automatic calling to kick in, like:: |
|
2570 | 2570 | |
|
2571 | 2571 | /f x |
|
2572 | 2572 | |
|
2573 | 2573 | into:: |
|
2574 | 2574 | |
|
2575 | 2575 | ------> f(x) |
|
2576 | 2576 | |
|
2577 | 2577 | after the user's input prompt. This helps the user understand that the |
|
2578 | 2578 | input line was transformed automatically by IPython. |
|
2579 | 2579 | """ |
|
2580 | 2580 | if not self.show_rewritten_input: |
|
2581 | 2581 | return |
|
2582 | 2582 | |
|
2583 | 2583 | # This is overridden in TerminalInteractiveShell to use fancy prompts |
|
2584 | 2584 | print("------> " + cmd) |
|
2585 | 2585 | |
|
2586 | 2586 | #------------------------------------------------------------------------- |
|
2587 | 2587 | # Things related to extracting values/expressions from kernel and user_ns |
|
2588 | 2588 | #------------------------------------------------------------------------- |
|
2589 | 2589 | |
|
2590 | 2590 | def _user_obj_error(self): |
|
2591 | 2591 | """return simple exception dict |
|
2592 | 2592 | |
|
2593 | 2593 | for use in user_expressions |
|
2594 | 2594 | """ |
|
2595 | 2595 | |
|
2596 | 2596 | etype, evalue, tb = self._get_exc_info() |
|
2597 | 2597 | stb = self.InteractiveTB.get_exception_only(etype, evalue) |
|
2598 | 2598 | |
|
2599 | 2599 | exc_info = { |
|
2600 | 2600 | u'status' : 'error', |
|
2601 | 2601 | u'traceback' : stb, |
|
2602 | 2602 | u'ename' : etype.__name__, |
|
2603 | 2603 | u'evalue' : py3compat.safe_unicode(evalue), |
|
2604 | 2604 | } |
|
2605 | 2605 | |
|
2606 | 2606 | return exc_info |
|
2607 | 2607 | |
|
2608 | 2608 | def _format_user_obj(self, obj): |
|
2609 | 2609 | """format a user object to display dict |
|
2610 | 2610 | |
|
2611 | 2611 | for use in user_expressions |
|
2612 | 2612 | """ |
|
2613 | 2613 | |
|
2614 | 2614 | data, md = self.display_formatter.format(obj) |
|
2615 | 2615 | value = { |
|
2616 | 2616 | 'status' : 'ok', |
|
2617 | 2617 | 'data' : data, |
|
2618 | 2618 | 'metadata' : md, |
|
2619 | 2619 | } |
|
2620 | 2620 | return value |
|
2621 | 2621 | |
|
2622 | 2622 | def user_expressions(self, expressions): |
|
2623 | 2623 | """Evaluate a dict of expressions in the user's namespace. |
|
2624 | 2624 | |
|
2625 | 2625 | Parameters |
|
2626 | 2626 | ---------- |
|
2627 | 2627 | expressions : dict |
|
2628 | 2628 | A dict with string keys and string values. The expression values |
|
2629 | 2629 | should be valid Python expressions, each of which will be evaluated |
|
2630 | 2630 | in the user namespace. |
|
2631 | 2631 | |
|
2632 | 2632 | Returns |
|
2633 | 2633 | ------- |
|
2634 | 2634 | A dict, keyed like the input expressions dict, with the rich mime-typed |
|
2635 | 2635 | display_data of each value. |
|
2636 | 2636 | """ |
|
2637 | 2637 | out = {} |
|
2638 | 2638 | user_ns = self.user_ns |
|
2639 | 2639 | global_ns = self.user_global_ns |
|
2640 | 2640 | |
|
2641 | 2641 | for key, expr in expressions.items(): |
|
2642 | 2642 | try: |
|
2643 | 2643 | value = self._format_user_obj(eval(expr, global_ns, user_ns)) |
|
2644 | 2644 | except: |
|
2645 | 2645 | value = self._user_obj_error() |
|
2646 | 2646 | out[key] = value |
|
2647 | 2647 | return out |
|
2648 | 2648 | |
|
2649 | 2649 | #------------------------------------------------------------------------- |
|
2650 | 2650 | # Things related to the running of code |
|
2651 | 2651 | #------------------------------------------------------------------------- |
|
2652 | 2652 | |
|
2653 | 2653 | def ex(self, cmd): |
|
2654 | 2654 | """Execute a normal python statement in user namespace.""" |
|
2655 | 2655 | with self.builtin_trap: |
|
2656 | 2656 | exec(cmd, self.user_global_ns, self.user_ns) |
|
2657 | 2657 | |
|
2658 | 2658 | def ev(self, expr): |
|
2659 | 2659 | """Evaluate python expression expr in user namespace. |
|
2660 | 2660 | |
|
2661 | 2661 | Returns the result of evaluation |
|
2662 | 2662 | """ |
|
2663 | 2663 | with self.builtin_trap: |
|
2664 | 2664 | return eval(expr, self.user_global_ns, self.user_ns) |
|
2665 | 2665 | |
|
2666 | 2666 | def safe_execfile(self, fname, *where, exit_ignore=False, raise_exceptions=False, shell_futures=False): |
|
2667 | 2667 | """A safe version of the builtin execfile(). |
|
2668 | 2668 | |
|
2669 | 2669 | This version will never throw an exception, but instead print |
|
2670 | 2670 | helpful error messages to the screen. This only works on pure |
|
2671 | 2671 | Python files with the .py extension. |
|
2672 | 2672 | |
|
2673 | 2673 | Parameters |
|
2674 | 2674 | ---------- |
|
2675 | 2675 | fname : string |
|
2676 | 2676 | The name of the file to be executed. |
|
2677 | 2677 | where : tuple |
|
2678 | 2678 | One or two namespaces, passed to execfile() as (globals,locals). |
|
2679 | 2679 | If only one is given, it is passed as both. |
|
2680 | 2680 | exit_ignore : bool (False) |
|
2681 | 2681 | If True, then silence SystemExit for non-zero status (it is always |
|
2682 | 2682 | silenced for zero status, as it is so common). |
|
2683 | 2683 | raise_exceptions : bool (False) |
|
2684 | 2684 | If True raise exceptions everywhere. Meant for testing. |
|
2685 | 2685 | shell_futures : bool (False) |
|
2686 | 2686 | If True, the code will share future statements with the interactive |
|
2687 | 2687 | shell. It will both be affected by previous __future__ imports, and |
|
2688 | 2688 | any __future__ imports in the code will affect the shell. If False, |
|
2689 | 2689 | __future__ imports are not shared in either direction. |
|
2690 | 2690 | |
|
2691 | 2691 | """ |
|
2692 | 2692 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2693 | 2693 | |
|
2694 | 2694 | # Make sure we can open the file |
|
2695 | 2695 | try: |
|
2696 | 2696 | with open(fname): |
|
2697 | 2697 | pass |
|
2698 | 2698 | except: |
|
2699 | 2699 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2700 | 2700 | return |
|
2701 | 2701 | |
|
2702 | 2702 | # Find things also in current directory. This is needed to mimic the |
|
2703 | 2703 | # behavior of running a script from the system command line, where |
|
2704 | 2704 | # Python inserts the script's directory into sys.path |
|
2705 | 2705 | dname = os.path.dirname(fname) |
|
2706 | 2706 | |
|
2707 | 2707 | with prepended_to_syspath(dname), self.builtin_trap: |
|
2708 | 2708 | try: |
|
2709 | 2709 | glob, loc = (where + (None, ))[:2] |
|
2710 | 2710 | py3compat.execfile( |
|
2711 | 2711 | fname, glob, loc, |
|
2712 | 2712 | self.compile if shell_futures else None) |
|
2713 | 2713 | except SystemExit as status: |
|
2714 | 2714 | # If the call was made with 0 or None exit status (sys.exit(0) |
|
2715 | 2715 | # or sys.exit() ), don't bother showing a traceback, as both of |
|
2716 | 2716 | # these are considered normal by the OS: |
|
2717 | 2717 | # > python -c'import sys;sys.exit(0)'; echo $? |
|
2718 | 2718 | # 0 |
|
2719 | 2719 | # > python -c'import sys;sys.exit()'; echo $? |
|
2720 | 2720 | # 0 |
|
2721 | 2721 | # For other exit status, we show the exception unless |
|
2722 | 2722 | # explicitly silenced, but only in short form. |
|
2723 | 2723 | if status.code: |
|
2724 | 2724 | if raise_exceptions: |
|
2725 | 2725 | raise |
|
2726 | 2726 | if not exit_ignore: |
|
2727 | 2727 | self.showtraceback(exception_only=True) |
|
2728 | 2728 | except: |
|
2729 | 2729 | if raise_exceptions: |
|
2730 | 2730 | raise |
|
2731 | 2731 | # tb offset is 2 because we wrap execfile |
|
2732 | 2732 | self.showtraceback(tb_offset=2) |
|
2733 | 2733 | |
|
2734 | 2734 | def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False): |
|
2735 | 2735 | """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax. |
|
2736 | 2736 | |
|
2737 | 2737 | Parameters |
|
2738 | 2738 | ---------- |
|
2739 | 2739 | fname : str |
|
2740 | 2740 | The name of the file to execute. The filename must have a |
|
2741 | 2741 | .ipy or .ipynb extension. |
|
2742 | 2742 | shell_futures : bool (False) |
|
2743 | 2743 | If True, the code will share future statements with the interactive |
|
2744 | 2744 | shell. It will both be affected by previous __future__ imports, and |
|
2745 | 2745 | any __future__ imports in the code will affect the shell. If False, |
|
2746 | 2746 | __future__ imports are not shared in either direction. |
|
2747 | 2747 | raise_exceptions : bool (False) |
|
2748 | 2748 | If True raise exceptions everywhere. Meant for testing. |
|
2749 | 2749 | """ |
|
2750 | 2750 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2751 | 2751 | |
|
2752 | 2752 | # Make sure we can open the file |
|
2753 | 2753 | try: |
|
2754 | 2754 | with open(fname): |
|
2755 | 2755 | pass |
|
2756 | 2756 | except: |
|
2757 | 2757 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2758 | 2758 | return |
|
2759 | 2759 | |
|
2760 | 2760 | # Find things also in current directory. This is needed to mimic the |
|
2761 | 2761 | # behavior of running a script from the system command line, where |
|
2762 | 2762 | # Python inserts the script's directory into sys.path |
|
2763 | 2763 | dname = os.path.dirname(fname) |
|
2764 | 2764 | |
|
2765 | 2765 | def get_cells(): |
|
2766 | 2766 | """generator for sequence of code blocks to run""" |
|
2767 | 2767 | if fname.endswith('.ipynb'): |
|
2768 | 2768 | from nbformat import read |
|
2769 | 2769 | nb = read(fname, as_version=4) |
|
2770 | 2770 | if not nb.cells: |
|
2771 | 2771 | return |
|
2772 | 2772 | for cell in nb.cells: |
|
2773 | 2773 | if cell.cell_type == 'code': |
|
2774 | 2774 | yield cell.source |
|
2775 | 2775 | else: |
|
2776 | 2776 | with open(fname) as f: |
|
2777 | 2777 | yield f.read() |
|
2778 | 2778 | |
|
2779 | 2779 | with prepended_to_syspath(dname): |
|
2780 | 2780 | try: |
|
2781 | 2781 | for cell in get_cells(): |
|
2782 | 2782 | result = self.run_cell(cell, silent=True, shell_futures=shell_futures) |
|
2783 | 2783 | if raise_exceptions: |
|
2784 | 2784 | result.raise_error() |
|
2785 | 2785 | elif not result.success: |
|
2786 | 2786 | break |
|
2787 | 2787 | except: |
|
2788 | 2788 | if raise_exceptions: |
|
2789 | 2789 | raise |
|
2790 | 2790 | self.showtraceback() |
|
2791 | 2791 | warn('Unknown failure executing file: <%s>' % fname) |
|
2792 | 2792 | |
|
2793 | 2793 | def safe_run_module(self, mod_name, where): |
|
2794 | 2794 | """A safe version of runpy.run_module(). |
|
2795 | 2795 | |
|
2796 | 2796 | This version will never throw an exception, but instead print |
|
2797 | 2797 | helpful error messages to the screen. |
|
2798 | 2798 | |
|
2799 | 2799 | `SystemExit` exceptions with status code 0 or None are ignored. |
|
2800 | 2800 | |
|
2801 | 2801 | Parameters |
|
2802 | 2802 | ---------- |
|
2803 | 2803 | mod_name : string |
|
2804 | 2804 | The name of the module to be executed. |
|
2805 | 2805 | where : dict |
|
2806 | 2806 | The globals namespace. |
|
2807 | 2807 | """ |
|
2808 | 2808 | try: |
|
2809 | 2809 | try: |
|
2810 | 2810 | where.update( |
|
2811 | 2811 | runpy.run_module(str(mod_name), run_name="__main__", |
|
2812 | 2812 | alter_sys=True) |
|
2813 | 2813 | ) |
|
2814 | 2814 | except SystemExit as status: |
|
2815 | 2815 | if status.code: |
|
2816 | 2816 | raise |
|
2817 | 2817 | except: |
|
2818 | 2818 | self.showtraceback() |
|
2819 | 2819 | warn('Unknown failure executing module: <%s>' % mod_name) |
|
2820 | 2820 | |
|
2821 | 2821 | def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True): |
|
2822 | 2822 | """Run a complete IPython cell. |
|
2823 | 2823 | |
|
2824 | 2824 | Parameters |
|
2825 | 2825 | ---------- |
|
2826 | 2826 | raw_cell : str |
|
2827 | 2827 | The code (including IPython code such as %magic functions) to run. |
|
2828 | 2828 | store_history : bool |
|
2829 | 2829 | If True, the raw and translated cell will be stored in IPython's |
|
2830 | 2830 | history. For user code calling back into IPython's machinery, this |
|
2831 | 2831 | should be set to False. |
|
2832 | 2832 | silent : bool |
|
2833 | 2833 | If True, avoid side-effects, such as implicit displayhooks and |
|
2834 | 2834 | and logging. silent=True forces store_history=False. |
|
2835 | 2835 | shell_futures : bool |
|
2836 | 2836 | If True, the code will share future statements with the interactive |
|
2837 | 2837 | shell. It will both be affected by previous __future__ imports, and |
|
2838 | 2838 | any __future__ imports in the code will affect the shell. If False, |
|
2839 | 2839 | __future__ imports are not shared in either direction. |
|
2840 | 2840 | |
|
2841 | 2841 | Returns |
|
2842 | 2842 | ------- |
|
2843 | 2843 | result : :class:`ExecutionResult` |
|
2844 | 2844 | """ |
|
2845 | 2845 | result = None |
|
2846 | 2846 | try: |
|
2847 | 2847 | result = self._run_cell( |
|
2848 | 2848 | raw_cell, store_history, silent, shell_futures) |
|
2849 | 2849 | finally: |
|
2850 | 2850 | self.events.trigger('post_execute') |
|
2851 | 2851 | if not silent: |
|
2852 | 2852 | self.events.trigger('post_run_cell', result) |
|
2853 | 2853 | return result |
|
2854 | 2854 | |
|
2855 | 2855 | def _run_cell(self, raw_cell:str, store_history:bool, silent:bool, shell_futures:bool): |
|
2856 | 2856 | """Internal method to run a complete IPython cell.""" |
|
2857 | 2857 | coro = self.run_cell_async( |
|
2858 | 2858 | raw_cell, |
|
2859 | 2859 | store_history=store_history, |
|
2860 | 2860 | silent=silent, |
|
2861 | 2861 | shell_futures=shell_futures, |
|
2862 | 2862 | ) |
|
2863 | 2863 | |
|
2864 | 2864 | # run_cell_async is async, but may not actually need an eventloop. |
|
2865 | 2865 | # when this is the case, we want to run it using the pseudo_sync_runner |
|
2866 | 2866 | # so that code can invoke eventloops (for example via the %run , and |
|
2867 | 2867 | # `%paste` magic. |
|
2868 | 2868 | if self.should_run_async(raw_cell): |
|
2869 | 2869 | runner = self.loop_runner |
|
2870 | 2870 | else: |
|
2871 | 2871 | runner = _pseudo_sync_runner |
|
2872 | 2872 | |
|
2873 | 2873 | try: |
|
2874 | 2874 | return runner(coro) |
|
2875 | 2875 | except BaseException as e: |
|
2876 | 2876 | info = ExecutionInfo(raw_cell, store_history, silent, shell_futures) |
|
2877 | 2877 | result = ExecutionResult(info) |
|
2878 | 2878 | result.error_in_exec = e |
|
2879 | 2879 | self.showtraceback(running_compiled_code=True) |
|
2880 | 2880 | return result |
|
2881 | 2881 | return |
|
2882 | 2882 | |
|
2883 | 2883 | def should_run_async(self, raw_cell: str) -> bool: |
|
2884 | 2884 | """Return whether a cell should be run asynchronously via a coroutine runner |
|
2885 | 2885 | |
|
2886 | 2886 | Parameters |
|
2887 | 2887 | ---------- |
|
2888 | 2888 | raw_cell: str |
|
2889 | 2889 | The code to be executed |
|
2890 | 2890 | |
|
2891 | 2891 | Returns |
|
2892 | 2892 | ------- |
|
2893 | 2893 | result: bool |
|
2894 | 2894 | Whether the code needs to be run with a coroutine runner or not |
|
2895 | 2895 | |
|
2896 | 2896 | .. versionadded: 7.0 |
|
2897 | 2897 | """ |
|
2898 | 2898 | if not self.autoawait: |
|
2899 | 2899 | return False |
|
2900 | 2900 | try: |
|
2901 | 2901 | cell = self.transform_cell(raw_cell) |
|
2902 | 2902 | except Exception: |
|
2903 | 2903 | # any exception during transform will be raised |
|
2904 | 2904 | # prior to execution |
|
2905 | 2905 | return False |
|
2906 | 2906 | return _should_be_async(cell) |
|
2907 | 2907 | |
|
2908 | 2908 | async def run_cell_async(self, raw_cell: str, store_history=False, silent=False, shell_futures=True) -> ExecutionResult: |
|
2909 | 2909 | """Run a complete IPython cell asynchronously. |
|
2910 | 2910 | |
|
2911 | 2911 | Parameters |
|
2912 | 2912 | ---------- |
|
2913 | 2913 | raw_cell : str |
|
2914 | 2914 | The code (including IPython code such as %magic functions) to run. |
|
2915 | 2915 | store_history : bool |
|
2916 | 2916 | If True, the raw and translated cell will be stored in IPython's |
|
2917 | 2917 | history. For user code calling back into IPython's machinery, this |
|
2918 | 2918 | should be set to False. |
|
2919 | 2919 | silent : bool |
|
2920 | 2920 | If True, avoid side-effects, such as implicit displayhooks and |
|
2921 | 2921 | and logging. silent=True forces store_history=False. |
|
2922 | 2922 | shell_futures : bool |
|
2923 | 2923 | If True, the code will share future statements with the interactive |
|
2924 | 2924 | shell. It will both be affected by previous __future__ imports, and |
|
2925 | 2925 | any __future__ imports in the code will affect the shell. If False, |
|
2926 | 2926 | __future__ imports are not shared in either direction. |
|
2927 | 2927 | |
|
2928 | 2928 | Returns |
|
2929 | 2929 | ------- |
|
2930 | 2930 | result : :class:`ExecutionResult` |
|
2931 | 2931 | |
|
2932 | 2932 | .. versionadded: 7.0 |
|
2933 | 2933 | """ |
|
2934 | 2934 | info = ExecutionInfo( |
|
2935 | 2935 | raw_cell, store_history, silent, shell_futures) |
|
2936 | 2936 | result = ExecutionResult(info) |
|
2937 | 2937 | |
|
2938 | 2938 | if (not raw_cell) or raw_cell.isspace(): |
|
2939 | 2939 | self.last_execution_succeeded = True |
|
2940 | 2940 | self.last_execution_result = result |
|
2941 | 2941 | return result |
|
2942 | 2942 | |
|
2943 | 2943 | if silent: |
|
2944 | 2944 | store_history = False |
|
2945 | 2945 | |
|
2946 | 2946 | if store_history: |
|
2947 | 2947 | result.execution_count = self.execution_count |
|
2948 | 2948 | |
|
2949 | 2949 | def error_before_exec(value): |
|
2950 | 2950 | if store_history: |
|
2951 | 2951 | self.execution_count += 1 |
|
2952 | 2952 | result.error_before_exec = value |
|
2953 | 2953 | self.last_execution_succeeded = False |
|
2954 | 2954 | self.last_execution_result = result |
|
2955 | 2955 | return result |
|
2956 | 2956 | |
|
2957 | 2957 | self.events.trigger('pre_execute') |
|
2958 | 2958 | if not silent: |
|
2959 | 2959 | self.events.trigger('pre_run_cell', info) |
|
2960 | 2960 | |
|
2961 | 2961 | # If any of our input transformation (input_transformer_manager or |
|
2962 | 2962 | # prefilter_manager) raises an exception, we store it in this variable |
|
2963 | 2963 | # so that we can display the error after logging the input and storing |
|
2964 | 2964 | # it in the history. |
|
2965 | 2965 | try: |
|
2966 | 2966 | cell = self.transform_cell(raw_cell) |
|
2967 | 2967 | except Exception: |
|
2968 | 2968 | preprocessing_exc_tuple = sys.exc_info() |
|
2969 | 2969 | cell = raw_cell # cell has to exist so it can be stored/logged |
|
2970 | 2970 | else: |
|
2971 | 2971 | preprocessing_exc_tuple = None |
|
2972 | 2972 | |
|
2973 | 2973 | # Store raw and processed history |
|
2974 | 2974 | if store_history: |
|
2975 | 2975 | self.history_manager.store_inputs(self.execution_count, |
|
2976 | 2976 | cell, raw_cell) |
|
2977 | 2977 | if not silent: |
|
2978 | 2978 | self.logger.log(cell, raw_cell) |
|
2979 | 2979 | |
|
2980 | 2980 | # Display the exception if input processing failed. |
|
2981 | 2981 | if preprocessing_exc_tuple is not None: |
|
2982 | 2982 | self.showtraceback(preprocessing_exc_tuple) |
|
2983 | 2983 | if store_history: |
|
2984 | 2984 | self.execution_count += 1 |
|
2985 | 2985 | return error_before_exec(preprocessing_exc_tuple[1]) |
|
2986 | 2986 | |
|
2987 | 2987 | # Our own compiler remembers the __future__ environment. If we want to |
|
2988 | 2988 | # run code with a separate __future__ environment, use the default |
|
2989 | 2989 | # compiler |
|
2990 | 2990 | compiler = self.compile if shell_futures else CachingCompiler() |
|
2991 | 2991 | |
|
2992 | 2992 | _run_async = False |
|
2993 | 2993 | |
|
2994 | 2994 | with self.builtin_trap: |
|
2995 | 2995 | cell_name = self.compile.cache(cell, self.execution_count) |
|
2996 | 2996 | |
|
2997 | 2997 | with self.display_trap: |
|
2998 | 2998 | # Compile to bytecode |
|
2999 | 2999 | try: |
|
3000 | 3000 | if sys.version_info < (3,8) and self.autoawait: |
|
3001 | 3001 | if _should_be_async(cell): |
|
3002 | 3002 | # the code AST below will not be user code: we wrap it |
|
3003 | 3003 | # in an `async def`. This will likely make some AST |
|
3004 | 3004 | # transformer below miss some transform opportunity and |
|
3005 | 3005 | # introduce a small coupling to run_code (in which we |
|
3006 | 3006 | # bake some assumptions of what _ast_asyncify returns. |
|
3007 | 3007 | # they are ways around (like grafting part of the ast |
|
3008 | 3008 | # later: |
|
3009 | 3009 | # - Here, return code_ast.body[0].body[1:-1], as well |
|
3010 | 3010 | # as last expression in return statement which is |
|
3011 | 3011 | # the user code part. |
|
3012 | 3012 | # - Let it go through the AST transformers, and graft |
|
3013 | 3013 | # - it back after the AST transform |
|
3014 | 3014 | # But that seem unreasonable, at least while we |
|
3015 | 3015 | # do not need it. |
|
3016 | 3016 | code_ast = _ast_asyncify(cell, 'async-def-wrapper') |
|
3017 | 3017 | _run_async = True |
|
3018 | 3018 | else: |
|
3019 | 3019 | code_ast = compiler.ast_parse(cell, filename=cell_name) |
|
3020 | 3020 | else: |
|
3021 | 3021 | code_ast = compiler.ast_parse(cell, filename=cell_name) |
|
3022 | 3022 | except self.custom_exceptions as e: |
|
3023 | 3023 | etype, value, tb = sys.exc_info() |
|
3024 | 3024 | self.CustomTB(etype, value, tb) |
|
3025 | 3025 | return error_before_exec(e) |
|
3026 | 3026 | except IndentationError as e: |
|
3027 | 3027 | self.showindentationerror() |
|
3028 | 3028 | return error_before_exec(e) |
|
3029 | 3029 | except (OverflowError, SyntaxError, ValueError, TypeError, |
|
3030 | 3030 | MemoryError) as e: |
|
3031 | 3031 | self.showsyntaxerror() |
|
3032 | 3032 | return error_before_exec(e) |
|
3033 | 3033 | |
|
3034 | 3034 | # Apply AST transformations |
|
3035 | 3035 | try: |
|
3036 | 3036 | code_ast = self.transform_ast(code_ast) |
|
3037 | 3037 | except InputRejected as e: |
|
3038 | 3038 | self.showtraceback() |
|
3039 | 3039 | return error_before_exec(e) |
|
3040 | 3040 | |
|
3041 | 3041 | # Give the displayhook a reference to our ExecutionResult so it |
|
3042 | 3042 | # can fill in the output value. |
|
3043 | 3043 | self.displayhook.exec_result = result |
|
3044 | 3044 | |
|
3045 | 3045 | # Execute the user code |
|
3046 | 3046 | interactivity = "none" if silent else self.ast_node_interactivity |
|
3047 | 3047 | if _run_async: |
|
3048 | 3048 | interactivity = 'async' |
|
3049 | 3049 | |
|
3050 | 3050 | has_raised = await self.run_ast_nodes(code_ast.body, cell_name, |
|
3051 | 3051 | interactivity=interactivity, compiler=compiler, result=result) |
|
3052 | 3052 | |
|
3053 | 3053 | self.last_execution_succeeded = not has_raised |
|
3054 | 3054 | self.last_execution_result = result |
|
3055 | 3055 | |
|
3056 | 3056 | # Reset this so later displayed values do not modify the |
|
3057 | 3057 | # ExecutionResult |
|
3058 | 3058 | self.displayhook.exec_result = None |
|
3059 | 3059 | |
|
3060 | 3060 | if store_history: |
|
3061 | 3061 | # Write output to the database. Does nothing unless |
|
3062 | 3062 | # history output logging is enabled. |
|
3063 | 3063 | self.history_manager.store_output(self.execution_count) |
|
3064 | 3064 | # Each cell is a *single* input, regardless of how many lines it has |
|
3065 | 3065 | self.execution_count += 1 |
|
3066 | 3066 | |
|
3067 | 3067 | return result |
|
3068 | 3068 | |
|
3069 | 3069 | def transform_cell(self, raw_cell): |
|
3070 | 3070 | """Transform an input cell before parsing it. |
|
3071 | 3071 | |
|
3072 | 3072 | Static transformations, implemented in IPython.core.inputtransformer2, |
|
3073 | 3073 | deal with things like ``%magic`` and ``!system`` commands. |
|
3074 | 3074 | These run on all input. |
|
3075 | 3075 | Dynamic transformations, for things like unescaped magics and the exit |
|
3076 | 3076 | autocall, depend on the state of the interpreter. |
|
3077 | 3077 | These only apply to single line inputs. |
|
3078 | 3078 | |
|
3079 | 3079 | These string-based transformations are followed by AST transformations; |
|
3080 | 3080 | see :meth:`transform_ast`. |
|
3081 | 3081 | """ |
|
3082 | 3082 | # Static input transformations |
|
3083 | 3083 | cell = self.input_transformer_manager.transform_cell(raw_cell) |
|
3084 | 3084 | |
|
3085 | 3085 | if len(cell.splitlines()) == 1: |
|
3086 | 3086 | # Dynamic transformations - only applied for single line commands |
|
3087 | 3087 | with self.builtin_trap: |
|
3088 | 3088 | # use prefilter_lines to handle trailing newlines |
|
3089 | 3089 | # restore trailing newline for ast.parse |
|
3090 | 3090 | cell = self.prefilter_manager.prefilter_lines(cell) + '\n' |
|
3091 | 3091 | |
|
3092 | 3092 | lines = cell.splitlines(keepends=True) |
|
3093 | 3093 | for transform in self.input_transformers_post: |
|
3094 | 3094 | lines = transform(lines) |
|
3095 | 3095 | cell = ''.join(lines) |
|
3096 | 3096 | |
|
3097 | 3097 | return cell |
|
3098 | 3098 | |
|
3099 | 3099 | def transform_ast(self, node): |
|
3100 | 3100 | """Apply the AST transformations from self.ast_transformers |
|
3101 | 3101 | |
|
3102 | 3102 | Parameters |
|
3103 | 3103 | ---------- |
|
3104 | 3104 | node : ast.Node |
|
3105 | 3105 | The root node to be transformed. Typically called with the ast.Module |
|
3106 | 3106 | produced by parsing user input. |
|
3107 | 3107 | |
|
3108 | 3108 | Returns |
|
3109 | 3109 | ------- |
|
3110 | 3110 | An ast.Node corresponding to the node it was called with. Note that it |
|
3111 | 3111 | may also modify the passed object, so don't rely on references to the |
|
3112 | 3112 | original AST. |
|
3113 | 3113 | """ |
|
3114 | 3114 | for transformer in self.ast_transformers: |
|
3115 | 3115 | try: |
|
3116 | 3116 | node = transformer.visit(node) |
|
3117 | 3117 | except InputRejected: |
|
3118 | 3118 | # User-supplied AST transformers can reject an input by raising |
|
3119 | 3119 | # an InputRejected. Short-circuit in this case so that we |
|
3120 | 3120 | # don't unregister the transform. |
|
3121 | 3121 | raise |
|
3122 | 3122 | except Exception: |
|
3123 | 3123 | warn("AST transformer %r threw an error. It will be unregistered." % transformer) |
|
3124 | 3124 | self.ast_transformers.remove(transformer) |
|
3125 | 3125 | |
|
3126 | 3126 | if self.ast_transformers: |
|
3127 | 3127 | ast.fix_missing_locations(node) |
|
3128 | 3128 | return node |
|
3129 | 3129 | |
|
3130 | 3130 | async def run_ast_nodes(self, nodelist:ListType[AST], cell_name:str, interactivity='last_expr', |
|
3131 | 3131 | compiler=compile, result=None): |
|
3132 | 3132 | """Run a sequence of AST nodes. The execution mode depends on the |
|
3133 | 3133 | interactivity parameter. |
|
3134 | 3134 | |
|
3135 | 3135 | Parameters |
|
3136 | 3136 | ---------- |
|
3137 | 3137 | nodelist : list |
|
3138 | 3138 | A sequence of AST nodes to run. |
|
3139 | 3139 | cell_name : str |
|
3140 | 3140 | Will be passed to the compiler as the filename of the cell. Typically |
|
3141 | 3141 | the value returned by ip.compile.cache(cell). |
|
3142 | 3142 | interactivity : str |
|
3143 | 3143 | 'all', 'last', 'last_expr' , 'last_expr_or_assign' or 'none', |
|
3144 | 3144 | specifying which nodes should be run interactively (displaying output |
|
3145 | 3145 | from expressions). 'last_expr' will run the last node interactively |
|
3146 | 3146 | only if it is an expression (i.e. expressions in loops or other blocks |
|
3147 | 3147 | are not displayed) 'last_expr_or_assign' will run the last expression |
|
3148 | 3148 | or the last assignment. Other values for this parameter will raise a |
|
3149 | 3149 | ValueError. |
|
3150 | 3150 | |
|
3151 | 3151 | Experimental value: 'async' Will try to run top level interactive |
|
3152 | 3152 | async/await code in default runner, this will not respect the |
|
3153 | 3153 | interactivity setting and will only run the last node if it is an |
|
3154 | 3154 | expression. |
|
3155 | 3155 | |
|
3156 | 3156 | compiler : callable |
|
3157 | 3157 | A function with the same interface as the built-in compile(), to turn |
|
3158 | 3158 | the AST nodes into code objects. Default is the built-in compile(). |
|
3159 | 3159 | result : ExecutionResult, optional |
|
3160 | 3160 | An object to store exceptions that occur during execution. |
|
3161 | 3161 | |
|
3162 | 3162 | Returns |
|
3163 | 3163 | ------- |
|
3164 | 3164 | True if an exception occurred while running code, False if it finished |
|
3165 | 3165 | running. |
|
3166 | 3166 | """ |
|
3167 | 3167 | if not nodelist: |
|
3168 | 3168 | return |
|
3169 | 3169 | |
|
3170 | 3170 | if interactivity == 'last_expr_or_assign': |
|
3171 | 3171 | if isinstance(nodelist[-1], _assign_nodes): |
|
3172 | 3172 | asg = nodelist[-1] |
|
3173 | 3173 | if isinstance(asg, ast.Assign) and len(asg.targets) == 1: |
|
3174 | 3174 | target = asg.targets[0] |
|
3175 | 3175 | elif isinstance(asg, _single_targets_nodes): |
|
3176 | 3176 | target = asg.target |
|
3177 | 3177 | else: |
|
3178 | 3178 | target = None |
|
3179 | 3179 | if isinstance(target, ast.Name): |
|
3180 | 3180 | nnode = ast.Expr(ast.Name(target.id, ast.Load())) |
|
3181 | 3181 | ast.fix_missing_locations(nnode) |
|
3182 | 3182 | nodelist.append(nnode) |
|
3183 | 3183 | interactivity = 'last_expr' |
|
3184 | 3184 | |
|
3185 | 3185 | _async = False |
|
3186 | 3186 | if interactivity == 'last_expr': |
|
3187 | 3187 | if isinstance(nodelist[-1], ast.Expr): |
|
3188 | 3188 | interactivity = "last" |
|
3189 | 3189 | else: |
|
3190 | 3190 | interactivity = "none" |
|
3191 | 3191 | |
|
3192 | 3192 | if interactivity == 'none': |
|
3193 | 3193 | to_run_exec, to_run_interactive = nodelist, [] |
|
3194 | 3194 | elif interactivity == 'last': |
|
3195 | 3195 | to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:] |
|
3196 | 3196 | elif interactivity == 'all': |
|
3197 | 3197 | to_run_exec, to_run_interactive = [], nodelist |
|
3198 | 3198 | elif interactivity == 'async': |
|
3199 | 3199 | to_run_exec, to_run_interactive = [], nodelist |
|
3200 | 3200 | _async = True |
|
3201 | 3201 | else: |
|
3202 | 3202 | raise ValueError("Interactivity was %r" % interactivity) |
|
3203 | 3203 | |
|
3204 | 3204 | try: |
|
3205 | 3205 | if _async and sys.version_info > (3,8): |
|
3206 | 3206 | raise ValueError("This branch should never happen on Python 3.8 and above, " |
|
3207 | 3207 | "please try to upgrade IPython and open a bug report with your case.") |
|
3208 | 3208 | if _async: |
|
3209 | 3209 | # If interactivity is async the semantics of run_code are |
|
3210 | 3210 | # completely different Skip usual machinery. |
|
3211 | 3211 | mod = Module(nodelist, []) |
|
3212 | 3212 | async_wrapper_code = compiler(mod, cell_name, 'exec') |
|
3213 | 3213 | exec(async_wrapper_code, self.user_global_ns, self.user_ns) |
|
3214 | 3214 | async_code = removed_co_newlocals(self.user_ns.pop('async-def-wrapper')).__code__ |
|
3215 | 3215 | if (await self.run_code(async_code, result, async_=True)): |
|
3216 | 3216 | return True |
|
3217 | 3217 | else: |
|
3218 | 3218 | if sys.version_info > (3, 8): |
|
3219 | 3219 | def compare(code): |
|
3220 | 3220 | is_async = (inspect.CO_COROUTINE & code.co_flags == inspect.CO_COROUTINE) |
|
3221 | 3221 | return is_async |
|
3222 | 3222 | else: |
|
3223 | 3223 | def compare(code): |
|
3224 | 3224 | return _async |
|
3225 | 3225 | |
|
3226 | 3226 | # refactor that to just change the mod constructor. |
|
3227 | 3227 | to_run = [] |
|
3228 | 3228 | for node in to_run_exec: |
|
3229 | 3229 | to_run.append((node, 'exec')) |
|
3230 | 3230 | |
|
3231 | 3231 | for node in to_run_interactive: |
|
3232 | 3232 | to_run.append((node, 'single')) |
|
3233 | 3233 | |
|
3234 | 3234 | for node,mode in to_run: |
|
3235 | 3235 | if mode == 'exec': |
|
3236 | 3236 | mod = Module([node], []) |
|
3237 | 3237 | elif mode == 'single': |
|
3238 | 3238 | mod = ast.Interactive([node]) |
|
3239 | 3239 | with compiler.extra_flags(getattr(ast, 'PyCF_ALLOW_TOP_LEVEL_AWAIT', 0x0) if self.autoawait else 0x0): |
|
3240 | 3240 | code = compiler(mod, cell_name, mode) |
|
3241 | 3241 | asy = compare(code) |
|
3242 | 3242 | if (await self.run_code(code, result, async_=asy)): |
|
3243 | 3243 | return True |
|
3244 | 3244 | |
|
3245 | 3245 | # Flush softspace |
|
3246 | 3246 | if softspace(sys.stdout, 0): |
|
3247 | 3247 | print() |
|
3248 | 3248 | |
|
3249 | 3249 | except: |
|
3250 | 3250 | # It's possible to have exceptions raised here, typically by |
|
3251 | 3251 | # compilation of odd code (such as a naked 'return' outside a |
|
3252 | 3252 | # function) that did parse but isn't valid. Typically the exception |
|
3253 | 3253 | # is a SyntaxError, but it's safest just to catch anything and show |
|
3254 | 3254 | # the user a traceback. |
|
3255 | 3255 | |
|
3256 | 3256 | # We do only one try/except outside the loop to minimize the impact |
|
3257 | 3257 | # on runtime, and also because if any node in the node list is |
|
3258 | 3258 | # broken, we should stop execution completely. |
|
3259 | 3259 | if result: |
|
3260 | 3260 | result.error_before_exec = sys.exc_info()[1] |
|
3261 | 3261 | self.showtraceback() |
|
3262 | 3262 | return True |
|
3263 | 3263 | |
|
3264 | 3264 | return False |
|
3265 | 3265 | |
|
3266 | 3266 | def _async_exec(self, code_obj: types.CodeType, user_ns: dict): |
|
3267 | 3267 | """ |
|
3268 | 3268 | Evaluate an asynchronous code object using a code runner |
|
3269 | 3269 | |
|
3270 | 3270 | Fake asynchronous execution of code_object in a namespace via a proxy namespace. |
|
3271 | 3271 | |
|
3272 | 3272 | Returns coroutine object, which can be executed via async loop runner |
|
3273 | 3273 | |
|
3274 | 3274 | WARNING: The semantics of `async_exec` are quite different from `exec`, |
|
3275 | 3275 | in particular you can only pass a single namespace. It also return a |
|
3276 | 3276 | handle to the value of the last things returned by code_object. |
|
3277 | 3277 | """ |
|
3278 | 3278 | |
|
3279 | 3279 | return eval(code_obj, user_ns) |
|
3280 | 3280 | |
|
3281 | 3281 | async def run_code(self, code_obj, result=None, *, async_=False): |
|
3282 | 3282 | """Execute a code object. |
|
3283 | 3283 | |
|
3284 | 3284 | When an exception occurs, self.showtraceback() is called to display a |
|
3285 | 3285 | traceback. |
|
3286 | 3286 | |
|
3287 | 3287 | Parameters |
|
3288 | 3288 | ---------- |
|
3289 | 3289 | code_obj : code object |
|
3290 | 3290 | A compiled code object, to be executed |
|
3291 | 3291 | result : ExecutionResult, optional |
|
3292 | 3292 | An object to store exceptions that occur during execution. |
|
3293 | 3293 | async_ : Bool (Experimental) |
|
3294 | 3294 | Attempt to run top-level asynchronous code in a default loop. |
|
3295 | 3295 | |
|
3296 | 3296 | Returns |
|
3297 | 3297 | ------- |
|
3298 | 3298 | False : successful execution. |
|
3299 | 3299 | True : an error occurred. |
|
3300 | 3300 | """ |
|
3301 | 3301 | # Set our own excepthook in case the user code tries to call it |
|
3302 | 3302 | # directly, so that the IPython crash handler doesn't get triggered |
|
3303 | 3303 | old_excepthook, sys.excepthook = sys.excepthook, self.excepthook |
|
3304 | 3304 | |
|
3305 | 3305 | # we save the original sys.excepthook in the instance, in case config |
|
3306 | 3306 | # code (such as magics) needs access to it. |
|
3307 | 3307 | self.sys_excepthook = old_excepthook |
|
3308 | 3308 | outflag = True # happens in more places, so it's easier as default |
|
3309 | 3309 | try: |
|
3310 | 3310 | try: |
|
3311 | 3311 | self.hooks.pre_run_code_hook() |
|
3312 | 3312 | if async_ and sys.version_info < (3,8): |
|
3313 | 3313 | last_expr = (await self._async_exec(code_obj, self.user_ns)) |
|
3314 | 3314 | code = compile('last_expr', 'fake', "single") |
|
3315 | 3315 | exec(code, {'last_expr': last_expr}) |
|
3316 | 3316 | elif async_ : |
|
3317 | 3317 | await eval(code_obj, self.user_global_ns, self.user_ns) |
|
3318 | 3318 | else: |
|
3319 | 3319 | exec(code_obj, self.user_global_ns, self.user_ns) |
|
3320 | 3320 | finally: |
|
3321 | 3321 | # Reset our crash handler in place |
|
3322 | 3322 | sys.excepthook = old_excepthook |
|
3323 | 3323 | except SystemExit as e: |
|
3324 | 3324 | if result is not None: |
|
3325 | 3325 | result.error_in_exec = e |
|
3326 | 3326 | self.showtraceback(exception_only=True) |
|
3327 | 3327 | warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1) |
|
3328 | 3328 | except self.custom_exceptions: |
|
3329 | 3329 | etype, value, tb = sys.exc_info() |
|
3330 | 3330 | if result is not None: |
|
3331 | 3331 | result.error_in_exec = value |
|
3332 | 3332 | self.CustomTB(etype, value, tb) |
|
3333 | 3333 | except: |
|
3334 | 3334 | if result is not None: |
|
3335 | 3335 | result.error_in_exec = sys.exc_info()[1] |
|
3336 | 3336 | self.showtraceback(running_compiled_code=True) |
|
3337 | 3337 | else: |
|
3338 | 3338 | outflag = False |
|
3339 | 3339 | return outflag |
|
3340 | 3340 | |
|
3341 | 3341 | # For backwards compatibility |
|
3342 | 3342 | runcode = run_code |
|
3343 | 3343 | |
|
3344 | 3344 | def check_complete(self, code: str) -> Tuple[str, str]: |
|
3345 | 3345 | """Return whether a block of code is ready to execute, or should be continued |
|
3346 | 3346 | |
|
3347 | 3347 | Parameters |
|
3348 | 3348 | ---------- |
|
3349 | 3349 | source : string |
|
3350 | 3350 | Python input code, which can be multiline. |
|
3351 | 3351 | |
|
3352 | 3352 | Returns |
|
3353 | 3353 | ------- |
|
3354 | 3354 | status : str |
|
3355 | 3355 | One of 'complete', 'incomplete', or 'invalid' if source is not a |
|
3356 | 3356 | prefix of valid code. |
|
3357 | 3357 | indent : str |
|
3358 | 3358 | When status is 'incomplete', this is some whitespace to insert on |
|
3359 | 3359 | the next line of the prompt. |
|
3360 | 3360 | """ |
|
3361 | 3361 | status, nspaces = self.input_transformer_manager.check_complete(code) |
|
3362 | 3362 | return status, ' ' * (nspaces or 0) |
|
3363 | 3363 | |
|
3364 | 3364 | #------------------------------------------------------------------------- |
|
3365 | 3365 | # Things related to GUI support and pylab |
|
3366 | 3366 | #------------------------------------------------------------------------- |
|
3367 | 3367 | |
|
3368 | 3368 | active_eventloop = None |
|
3369 | 3369 | |
|
3370 | 3370 | def enable_gui(self, gui=None): |
|
3371 | 3371 | raise NotImplementedError('Implement enable_gui in a subclass') |
|
3372 | 3372 | |
|
3373 | 3373 | def enable_matplotlib(self, gui=None): |
|
3374 | 3374 | """Enable interactive matplotlib and inline figure support. |
|
3375 | 3375 | |
|
3376 | 3376 | This takes the following steps: |
|
3377 | 3377 | |
|
3378 | 3378 | 1. select the appropriate eventloop and matplotlib backend |
|
3379 | 3379 | 2. set up matplotlib for interactive use with that backend |
|
3380 | 3380 | 3. configure formatters for inline figure display |
|
3381 | 3381 | 4. enable the selected gui eventloop |
|
3382 | 3382 | |
|
3383 | 3383 | Parameters |
|
3384 | 3384 | ---------- |
|
3385 | 3385 | gui : optional, string |
|
3386 | 3386 | If given, dictates the choice of matplotlib GUI backend to use |
|
3387 | 3387 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', |
|
3388 | 3388 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by |
|
3389 | 3389 | matplotlib (as dictated by the matplotlib build-time options plus the |
|
3390 | 3390 | user's matplotlibrc configuration file). Note that not all backends |
|
3391 | 3391 | make sense in all contexts, for example a terminal ipython can't |
|
3392 | 3392 | display figures inline. |
|
3393 | 3393 | """ |
|
3394 | 3394 | from IPython.core import pylabtools as pt |
|
3395 | 3395 | gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select) |
|
3396 | 3396 | |
|
3397 | 3397 | if gui != 'inline': |
|
3398 | 3398 | # If we have our first gui selection, store it |
|
3399 | 3399 | if self.pylab_gui_select is None: |
|
3400 | 3400 | self.pylab_gui_select = gui |
|
3401 | 3401 | # Otherwise if they are different |
|
3402 | 3402 | elif gui != self.pylab_gui_select: |
|
3403 | 3403 | print('Warning: Cannot change to a different GUI toolkit: %s.' |
|
3404 | 3404 | ' Using %s instead.' % (gui, self.pylab_gui_select)) |
|
3405 | 3405 | gui, backend = pt.find_gui_and_backend(self.pylab_gui_select) |
|
3406 | 3406 | |
|
3407 | 3407 | pt.activate_matplotlib(backend) |
|
3408 | 3408 | pt.configure_inline_support(self, backend) |
|
3409 | 3409 | |
|
3410 | 3410 | # Now we must activate the gui pylab wants to use, and fix %run to take |
|
3411 | 3411 | # plot updates into account |
|
3412 | 3412 | self.enable_gui(gui) |
|
3413 | 3413 | self.magics_manager.registry['ExecutionMagics'].default_runner = \ |
|
3414 | 3414 | pt.mpl_runner(self.safe_execfile) |
|
3415 | 3415 | |
|
3416 | 3416 | return gui, backend |
|
3417 | 3417 | |
|
3418 | 3418 | def enable_pylab(self, gui=None, import_all=True, welcome_message=False): |
|
3419 | 3419 | """Activate pylab support at runtime. |
|
3420 | 3420 | |
|
3421 | 3421 | This turns on support for matplotlib, preloads into the interactive |
|
3422 | 3422 | namespace all of numpy and pylab, and configures IPython to correctly |
|
3423 | 3423 | interact with the GUI event loop. The GUI backend to be used can be |
|
3424 | 3424 | optionally selected with the optional ``gui`` argument. |
|
3425 | 3425 | |
|
3426 | 3426 | This method only adds preloading the namespace to InteractiveShell.enable_matplotlib. |
|
3427 | 3427 | |
|
3428 | 3428 | Parameters |
|
3429 | 3429 | ---------- |
|
3430 | 3430 | gui : optional, string |
|
3431 | 3431 | If given, dictates the choice of matplotlib GUI backend to use |
|
3432 | 3432 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', |
|
3433 | 3433 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by |
|
3434 | 3434 | matplotlib (as dictated by the matplotlib build-time options plus the |
|
3435 | 3435 | user's matplotlibrc configuration file). Note that not all backends |
|
3436 | 3436 | make sense in all contexts, for example a terminal ipython can't |
|
3437 | 3437 | display figures inline. |
|
3438 | 3438 | import_all : optional, bool, default: True |
|
3439 | 3439 | Whether to do `from numpy import *` and `from pylab import *` |
|
3440 | 3440 | in addition to module imports. |
|
3441 | 3441 | welcome_message : deprecated |
|
3442 | 3442 | This argument is ignored, no welcome message will be displayed. |
|
3443 | 3443 | """ |
|
3444 | 3444 | from IPython.core.pylabtools import import_pylab |
|
3445 | 3445 | |
|
3446 | 3446 | gui, backend = self.enable_matplotlib(gui) |
|
3447 | 3447 | |
|
3448 | 3448 | # We want to prevent the loading of pylab to pollute the user's |
|
3449 | 3449 | # namespace as shown by the %who* magics, so we execute the activation |
|
3450 | 3450 | # code in an empty namespace, and we update *both* user_ns and |
|
3451 | 3451 | # user_ns_hidden with this information. |
|
3452 | 3452 | ns = {} |
|
3453 | 3453 | import_pylab(ns, import_all) |
|
3454 | 3454 | # warn about clobbered names |
|
3455 | 3455 | ignored = {"__builtins__"} |
|
3456 | 3456 | both = set(ns).intersection(self.user_ns).difference(ignored) |
|
3457 | 3457 | clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ] |
|
3458 | 3458 | self.user_ns.update(ns) |
|
3459 | 3459 | self.user_ns_hidden.update(ns) |
|
3460 | 3460 | return gui, backend, clobbered |
|
3461 | 3461 | |
|
3462 | 3462 | #------------------------------------------------------------------------- |
|
3463 | 3463 | # Utilities |
|
3464 | 3464 | #------------------------------------------------------------------------- |
|
3465 | 3465 | |
|
3466 | 3466 | def var_expand(self, cmd, depth=0, formatter=DollarFormatter()): |
|
3467 | 3467 | """Expand python variables in a string. |
|
3468 | 3468 | |
|
3469 | 3469 | The depth argument indicates how many frames above the caller should |
|
3470 | 3470 | be walked to look for the local namespace where to expand variables. |
|
3471 | 3471 | |
|
3472 | 3472 | The global namespace for expansion is always the user's interactive |
|
3473 | 3473 | namespace. |
|
3474 | 3474 | """ |
|
3475 | 3475 | ns = self.user_ns.copy() |
|
3476 | 3476 | try: |
|
3477 | 3477 | frame = sys._getframe(depth+1) |
|
3478 | 3478 | except ValueError: |
|
3479 | 3479 | # This is thrown if there aren't that many frames on the stack, |
|
3480 | 3480 | # e.g. if a script called run_line_magic() directly. |
|
3481 | 3481 | pass |
|
3482 | 3482 | else: |
|
3483 | 3483 | ns.update(frame.f_locals) |
|
3484 | 3484 | |
|
3485 | 3485 | try: |
|
3486 | 3486 | # We have to use .vformat() here, because 'self' is a valid and common |
|
3487 | 3487 | # name, and expanding **ns for .format() would make it collide with |
|
3488 | 3488 | # the 'self' argument of the method. |
|
3489 | 3489 | cmd = formatter.vformat(cmd, args=[], kwargs=ns) |
|
3490 | 3490 | except Exception: |
|
3491 | 3491 | # if formatter couldn't format, just let it go untransformed |
|
3492 | 3492 | pass |
|
3493 | 3493 | return cmd |
|
3494 | 3494 | |
|
3495 | 3495 | def mktempfile(self, data=None, prefix='ipython_edit_'): |
|
3496 | 3496 | """Make a new tempfile and return its filename. |
|
3497 | 3497 | |
|
3498 | 3498 | This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp), |
|
3499 | 3499 | but it registers the created filename internally so ipython cleans it up |
|
3500 | 3500 | at exit time. |
|
3501 | 3501 | |
|
3502 | 3502 | Optional inputs: |
|
3503 | 3503 | |
|
3504 | 3504 | - data(None): if data is given, it gets written out to the temp file |
|
3505 | 3505 | immediately, and the file is closed again.""" |
|
3506 | 3506 | |
|
3507 | 3507 | dirname = tempfile.mkdtemp(prefix=prefix) |
|
3508 | 3508 | self.tempdirs.append(dirname) |
|
3509 | 3509 | |
|
3510 | 3510 | handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname) |
|
3511 | 3511 | os.close(handle) # On Windows, there can only be one open handle on a file |
|
3512 | 3512 | self.tempfiles.append(filename) |
|
3513 | 3513 | |
|
3514 | 3514 | if data: |
|
3515 | 3515 | with open(filename, 'w') as tmp_file: |
|
3516 | 3516 | tmp_file.write(data) |
|
3517 | 3517 | return filename |
|
3518 | 3518 | |
|
3519 | 3519 | @undoc |
|
3520 | 3520 | def write(self,data): |
|
3521 | 3521 | """DEPRECATED: Write a string to the default output""" |
|
3522 | 3522 | warn('InteractiveShell.write() is deprecated, use sys.stdout instead', |
|
3523 | 3523 | DeprecationWarning, stacklevel=2) |
|
3524 | 3524 | sys.stdout.write(data) |
|
3525 | 3525 | |
|
3526 | 3526 | @undoc |
|
3527 | 3527 | def write_err(self,data): |
|
3528 | 3528 | """DEPRECATED: Write a string to the default error output""" |
|
3529 | 3529 | warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead', |
|
3530 | 3530 | DeprecationWarning, stacklevel=2) |
|
3531 | 3531 | sys.stderr.write(data) |
|
3532 | 3532 | |
|
3533 | 3533 | def ask_yes_no(self, prompt, default=None, interrupt=None): |
|
3534 | 3534 | if self.quiet: |
|
3535 | 3535 | return True |
|
3536 | 3536 | return ask_yes_no(prompt,default,interrupt) |
|
3537 | 3537 | |
|
3538 | 3538 | def show_usage(self): |
|
3539 | 3539 | """Show a usage message""" |
|
3540 | 3540 | page.page(IPython.core.usage.interactive_usage) |
|
3541 | 3541 | |
|
3542 | 3542 | def extract_input_lines(self, range_str, raw=False): |
|
3543 | 3543 | """Return as a string a set of input history slices. |
|
3544 | 3544 | |
|
3545 | 3545 | Parameters |
|
3546 | 3546 | ---------- |
|
3547 | 3547 | range_str : string |
|
3548 | 3548 | The set of slices is given as a string, like "~5/6-~4/2 4:8 9", |
|
3549 | 3549 | since this function is for use by magic functions which get their |
|
3550 | 3550 | arguments as strings. The number before the / is the session |
|
3551 | 3551 | number: ~n goes n back from the current session. |
|
3552 | 3552 | |
|
3553 | 3553 | raw : bool, optional |
|
3554 | 3554 | By default, the processed input is used. If this is true, the raw |
|
3555 | 3555 | input history is used instead. |
|
3556 | 3556 | |
|
3557 | 3557 | Notes |
|
3558 | 3558 | ----- |
|
3559 | 3559 | |
|
3560 | 3560 | Slices can be described with two notations: |
|
3561 | 3561 | |
|
3562 | 3562 | * ``N:M`` -> standard python form, means including items N...(M-1). |
|
3563 | 3563 | * ``N-M`` -> include items N..M (closed endpoint). |
|
3564 | 3564 | """ |
|
3565 | 3565 | lines = self.history_manager.get_range_by_str(range_str, raw=raw) |
|
3566 | 3566 | return "\n".join(x for _, _, x in lines) |
|
3567 | 3567 | |
|
3568 | 3568 | def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False): |
|
3569 | 3569 | """Get a code string from history, file, url, or a string or macro. |
|
3570 | 3570 | |
|
3571 | 3571 | This is mainly used by magic functions. |
|
3572 | 3572 | |
|
3573 | 3573 | Parameters |
|
3574 | 3574 | ---------- |
|
3575 | 3575 | |
|
3576 | 3576 | target : str |
|
3577 | 3577 | |
|
3578 | 3578 | A string specifying code to retrieve. This will be tried respectively |
|
3579 | 3579 | as: ranges of input history (see %history for syntax), url, |
|
3580 | 3580 | corresponding .py file, filename, or an expression evaluating to a |
|
3581 | 3581 | string or Macro in the user namespace. |
|
3582 | 3582 | |
|
3583 | 3583 | raw : bool |
|
3584 | 3584 | If true (default), retrieve raw history. Has no effect on the other |
|
3585 | 3585 | retrieval mechanisms. |
|
3586 | 3586 | |
|
3587 | 3587 | py_only : bool (default False) |
|
3588 | 3588 | Only try to fetch python code, do not try alternative methods to decode file |
|
3589 | 3589 | if unicode fails. |
|
3590 | 3590 | |
|
3591 | 3591 | Returns |
|
3592 | 3592 | ------- |
|
3593 | 3593 | A string of code. |
|
3594 | 3594 | |
|
3595 | 3595 | ValueError is raised if nothing is found, and TypeError if it evaluates |
|
3596 | 3596 | to an object of another type. In each case, .args[0] is a printable |
|
3597 | 3597 | message. |
|
3598 | 3598 | """ |
|
3599 | 3599 | code = self.extract_input_lines(target, raw=raw) # Grab history |
|
3600 | 3600 | if code: |
|
3601 | 3601 | return code |
|
3602 | 3602 | try: |
|
3603 | 3603 | if target.startswith(('http://', 'https://')): |
|
3604 | 3604 | return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie) |
|
3605 | 3605 | except UnicodeDecodeError: |
|
3606 | 3606 | if not py_only : |
|
3607 | 3607 | # Deferred import |
|
3608 | 3608 | from urllib.request import urlopen |
|
3609 | 3609 | response = urlopen(target) |
|
3610 | 3610 | return response.read().decode('latin1') |
|
3611 | 3611 | raise ValueError(("'%s' seem to be unreadable.") % target) |
|
3612 | 3612 | |
|
3613 | 3613 | potential_target = [target] |
|
3614 | 3614 | try : |
|
3615 | 3615 | potential_target.insert(0,get_py_filename(target)) |
|
3616 | 3616 | except IOError: |
|
3617 | 3617 | pass |
|
3618 | 3618 | |
|
3619 | 3619 | for tgt in potential_target : |
|
3620 | 3620 | if os.path.isfile(tgt): # Read file |
|
3621 | 3621 | try : |
|
3622 | 3622 | return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie) |
|
3623 | 3623 | except UnicodeDecodeError : |
|
3624 | 3624 | if not py_only : |
|
3625 | 3625 | with io_open(tgt,'r', encoding='latin1') as f : |
|
3626 | 3626 | return f.read() |
|
3627 | 3627 | raise ValueError(("'%s' seem to be unreadable.") % target) |
|
3628 | 3628 | elif os.path.isdir(os.path.expanduser(tgt)): |
|
3629 | 3629 | raise ValueError("'%s' is a directory, not a regular file." % target) |
|
3630 | 3630 | |
|
3631 | 3631 | if search_ns: |
|
3632 | 3632 | # Inspect namespace to load object source |
|
3633 | 3633 | object_info = self.object_inspect(target, detail_level=1) |
|
3634 | 3634 | if object_info['found'] and object_info['source']: |
|
3635 | 3635 | return object_info['source'] |
|
3636 | 3636 | |
|
3637 | 3637 | try: # User namespace |
|
3638 | 3638 | codeobj = eval(target, self.user_ns) |
|
3639 | 3639 | except Exception: |
|
3640 | 3640 | raise ValueError(("'%s' was not found in history, as a file, url, " |
|
3641 | 3641 | "nor in the user namespace.") % target) |
|
3642 | 3642 | |
|
3643 | 3643 | if isinstance(codeobj, str): |
|
3644 | 3644 | return codeobj |
|
3645 | 3645 | elif isinstance(codeobj, Macro): |
|
3646 | 3646 | return codeobj.value |
|
3647 | 3647 | |
|
3648 | 3648 | raise TypeError("%s is neither a string nor a macro." % target, |
|
3649 | 3649 | codeobj) |
|
3650 | 3650 | |
|
3651 | 3651 | #------------------------------------------------------------------------- |
|
3652 | 3652 | # Things related to IPython exiting |
|
3653 | 3653 | #------------------------------------------------------------------------- |
|
3654 | 3654 | def atexit_operations(self): |
|
3655 | 3655 | """This will be executed at the time of exit. |
|
3656 | 3656 | |
|
3657 | 3657 | Cleanup operations and saving of persistent data that is done |
|
3658 | 3658 | unconditionally by IPython should be performed here. |
|
3659 | 3659 | |
|
3660 | 3660 | For things that may depend on startup flags or platform specifics (such |
|
3661 | 3661 | as having readline or not), register a separate atexit function in the |
|
3662 | 3662 | code that has the appropriate information, rather than trying to |
|
3663 | 3663 | clutter |
|
3664 | 3664 | """ |
|
3665 | 3665 | # Close the history session (this stores the end time and line count) |
|
3666 | 3666 | # this must be *before* the tempfile cleanup, in case of temporary |
|
3667 | 3667 | # history db |
|
3668 | 3668 | self.history_manager.end_session() |
|
3669 | 3669 | |
|
3670 | 3670 | # Cleanup all tempfiles and folders left around |
|
3671 | 3671 | for tfile in self.tempfiles: |
|
3672 | 3672 | try: |
|
3673 | 3673 | os.unlink(tfile) |
|
3674 | 3674 | except OSError: |
|
3675 | 3675 | pass |
|
3676 | 3676 | |
|
3677 | 3677 | for tdir in self.tempdirs: |
|
3678 | 3678 | try: |
|
3679 | 3679 | os.rmdir(tdir) |
|
3680 | 3680 | except OSError: |
|
3681 | 3681 | pass |
|
3682 | 3682 | |
|
3683 | 3683 | # Clear all user namespaces to release all references cleanly. |
|
3684 | 3684 | self.reset(new_session=False) |
|
3685 | 3685 | |
|
3686 | 3686 | # Run user hooks |
|
3687 | 3687 | self.hooks.shutdown_hook() |
|
3688 | 3688 | |
|
3689 | 3689 | def cleanup(self): |
|
3690 | 3690 | self.restore_sys_module_state() |
|
3691 | 3691 | |
|
3692 | 3692 | |
|
3693 | 3693 | # Overridden in terminal subclass to change prompts |
|
3694 | 3694 | def switch_doctest_mode(self, mode): |
|
3695 | 3695 | pass |
|
3696 | 3696 | |
|
3697 | 3697 | |
|
3698 | 3698 | class InteractiveShellABC(metaclass=abc.ABCMeta): |
|
3699 | 3699 | """An abstract base class for InteractiveShell.""" |
|
3700 | 3700 | |
|
3701 | 3701 | InteractiveShellABC.register(InteractiveShell) |
@@ -1,1501 +1,1503 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Implementation of execution-related magic functions.""" |
|
3 | 3 | |
|
4 | 4 | # Copyright (c) IPython Development Team. |
|
5 | 5 | # Distributed under the terms of the Modified BSD License. |
|
6 | 6 | |
|
7 | 7 | |
|
8 | 8 | import ast |
|
9 | 9 | import bdb |
|
10 | 10 | import builtins as builtin_mod |
|
11 | 11 | import gc |
|
12 | 12 | import itertools |
|
13 | 13 | import os |
|
14 | 14 | import shlex |
|
15 | 15 | import sys |
|
16 | 16 | import time |
|
17 | 17 | import timeit |
|
18 | 18 | import math |
|
19 | 19 | import re |
|
20 | 20 | from pdb import Restart |
|
21 | 21 | |
|
22 | 22 | # cProfile was added in Python2.5 |
|
23 | 23 | try: |
|
24 | 24 | import cProfile as profile |
|
25 | 25 | import pstats |
|
26 | 26 | except ImportError: |
|
27 | 27 | # profile isn't bundled by default in Debian for license reasons |
|
28 | 28 | try: |
|
29 | 29 | import profile, pstats |
|
30 | 30 | except ImportError: |
|
31 | 31 | profile = pstats = None |
|
32 | 32 | |
|
33 | 33 | from IPython.core import oinspect |
|
34 | 34 | from IPython.core import magic_arguments |
|
35 | 35 | from IPython.core import page |
|
36 | 36 | from IPython.core.error import UsageError |
|
37 | 37 | from IPython.core.macro import Macro |
|
38 | 38 | from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic, |
|
39 | 39 | line_cell_magic, on_off, needs_local_scope, |
|
40 | 40 | no_var_expand) |
|
41 | 41 | from IPython.testing.skipdoctest import skip_doctest |
|
42 | 42 | from IPython.utils.contexts import preserve_keys |
|
43 | 43 | from IPython.utils.capture import capture_output |
|
44 | 44 | from IPython.utils.ipstruct import Struct |
|
45 | 45 | from IPython.utils.module_paths import find_mod |
|
46 | 46 | from IPython.utils.path import get_py_filename, shellglob |
|
47 | 47 | from IPython.utils.timing import clock, clock2 |
|
48 | 48 | from warnings import warn |
|
49 | 49 | from logging import error |
|
50 | 50 | from io import StringIO |
|
51 | 51 | |
|
52 | 52 | if sys.version_info > (3,8): |
|
53 | 53 | from ast import Module |
|
54 | 54 | else : |
|
55 | 55 | # mock the new API, ignore second argument |
|
56 | 56 | # see https://github.com/ipython/ipython/issues/11590 |
|
57 | 57 | from ast import Module as OriginalModule |
|
58 | 58 | Module = lambda nodelist, type_ignores: OriginalModule(nodelist) |
|
59 | 59 | |
|
60 | 60 | |
|
61 | 61 | #----------------------------------------------------------------------------- |
|
62 | 62 | # Magic implementation classes |
|
63 | 63 | #----------------------------------------------------------------------------- |
|
64 | 64 | |
|
65 | 65 | |
|
66 | 66 | class TimeitResult(object): |
|
67 | 67 | """ |
|
68 | 68 | Object returned by the timeit magic with info about the run. |
|
69 | 69 | |
|
70 | 70 | Contains the following attributes : |
|
71 | 71 | |
|
72 | 72 | loops: (int) number of loops done per measurement |
|
73 | 73 | repeat: (int) number of times the measurement has been repeated |
|
74 | 74 | best: (float) best execution time / number |
|
75 | 75 | all_runs: (list of float) execution time of each run (in s) |
|
76 | 76 | compile_time: (float) time of statement compilation (s) |
|
77 | 77 | |
|
78 | 78 | """ |
|
79 | 79 | def __init__(self, loops, repeat, best, worst, all_runs, compile_time, precision): |
|
80 | 80 | self.loops = loops |
|
81 | 81 | self.repeat = repeat |
|
82 | 82 | self.best = best |
|
83 | 83 | self.worst = worst |
|
84 | 84 | self.all_runs = all_runs |
|
85 | 85 | self.compile_time = compile_time |
|
86 | 86 | self._precision = precision |
|
87 | 87 | self.timings = [ dt / self.loops for dt in all_runs] |
|
88 | 88 | |
|
89 | 89 | @property |
|
90 | 90 | def average(self): |
|
91 | 91 | return math.fsum(self.timings) / len(self.timings) |
|
92 | 92 | |
|
93 | 93 | @property |
|
94 | 94 | def stdev(self): |
|
95 | 95 | mean = self.average |
|
96 | 96 | return (math.fsum([(x - mean) ** 2 for x in self.timings]) / len(self.timings)) ** 0.5 |
|
97 | 97 | |
|
98 | 98 | def __str__(self): |
|
99 | 99 | pm = '+-' |
|
100 | 100 | if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding: |
|
101 | 101 | try: |
|
102 | 102 | u'\xb1'.encode(sys.stdout.encoding) |
|
103 | 103 | pm = u'\xb1' |
|
104 | 104 | except: |
|
105 | 105 | pass |
|
106 | 106 | return ( |
|
107 | 107 | u"{mean} {pm} {std} per loop (mean {pm} std. dev. of {runs} run{run_plural}, {loops} loop{loop_plural} each)" |
|
108 | 108 | .format( |
|
109 | 109 | pm = pm, |
|
110 | 110 | runs = self.repeat, |
|
111 | 111 | loops = self.loops, |
|
112 | 112 | loop_plural = "" if self.loops == 1 else "s", |
|
113 | 113 | run_plural = "" if self.repeat == 1 else "s", |
|
114 | 114 | mean = _format_time(self.average, self._precision), |
|
115 | 115 | std = _format_time(self.stdev, self._precision)) |
|
116 | 116 | ) |
|
117 | 117 | |
|
118 | 118 | def _repr_pretty_(self, p , cycle): |
|
119 | 119 | unic = self.__str__() |
|
120 | 120 | p.text(u'<TimeitResult : '+unic+u'>') |
|
121 | 121 | |
|
122 | 122 | |
|
123 | 123 | class TimeitTemplateFiller(ast.NodeTransformer): |
|
124 | 124 | """Fill in the AST template for timing execution. |
|
125 | 125 | |
|
126 | 126 | This is quite closely tied to the template definition, which is in |
|
127 | 127 | :meth:`ExecutionMagics.timeit`. |
|
128 | 128 | """ |
|
129 | 129 | def __init__(self, ast_setup, ast_stmt): |
|
130 | 130 | self.ast_setup = ast_setup |
|
131 | 131 | self.ast_stmt = ast_stmt |
|
132 | 132 | |
|
133 | 133 | def visit_FunctionDef(self, node): |
|
134 | 134 | "Fill in the setup statement" |
|
135 | 135 | self.generic_visit(node) |
|
136 | 136 | if node.name == "inner": |
|
137 | 137 | node.body[:1] = self.ast_setup.body |
|
138 | 138 | |
|
139 | 139 | return node |
|
140 | 140 | |
|
141 | 141 | def visit_For(self, node): |
|
142 | 142 | "Fill in the statement to be timed" |
|
143 | 143 | if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt': |
|
144 | 144 | node.body = self.ast_stmt.body |
|
145 | 145 | return node |
|
146 | 146 | |
|
147 | 147 | |
|
148 | 148 | class Timer(timeit.Timer): |
|
149 | 149 | """Timer class that explicitly uses self.inner |
|
150 | 150 | |
|
151 | 151 | which is an undocumented implementation detail of CPython, |
|
152 | 152 | not shared by PyPy. |
|
153 | 153 | """ |
|
154 | 154 | # Timer.timeit copied from CPython 3.4.2 |
|
155 | 155 | def timeit(self, number=timeit.default_number): |
|
156 | 156 | """Time 'number' executions of the main statement. |
|
157 | 157 | |
|
158 | 158 | To be precise, this executes the setup statement once, and |
|
159 | 159 | then returns the time it takes to execute the main statement |
|
160 | 160 | a number of times, as a float measured in seconds. The |
|
161 | 161 | argument is the number of times through the loop, defaulting |
|
162 | 162 | to one million. The main statement, the setup statement and |
|
163 | 163 | the timer function to be used are passed to the constructor. |
|
164 | 164 | """ |
|
165 | 165 | it = itertools.repeat(None, number) |
|
166 | 166 | gcold = gc.isenabled() |
|
167 | 167 | gc.disable() |
|
168 | 168 | try: |
|
169 | 169 | timing = self.inner(it, self.timer) |
|
170 | 170 | finally: |
|
171 | 171 | if gcold: |
|
172 | 172 | gc.enable() |
|
173 | 173 | return timing |
|
174 | 174 | |
|
175 | 175 | |
|
176 | 176 | @magics_class |
|
177 | 177 | class ExecutionMagics(Magics): |
|
178 | 178 | """Magics related to code execution, debugging, profiling, etc. |
|
179 | 179 | |
|
180 | 180 | """ |
|
181 | 181 | |
|
182 | 182 | def __init__(self, shell): |
|
183 | 183 | super(ExecutionMagics, self).__init__(shell) |
|
184 | 184 | if profile is None: |
|
185 | 185 | self.prun = self.profile_missing_notice |
|
186 | 186 | # Default execution function used to actually run user code. |
|
187 | 187 | self.default_runner = None |
|
188 | 188 | |
|
189 | 189 | def profile_missing_notice(self, *args, **kwargs): |
|
190 | 190 | error("""\ |
|
191 | 191 | The profile module could not be found. It has been removed from the standard |
|
192 | 192 | python packages because of its non-free license. To use profiling, install the |
|
193 | 193 | python-profiler package from non-free.""") |
|
194 | 194 | |
|
195 | 195 | @skip_doctest |
|
196 | 196 | @no_var_expand |
|
197 | 197 | @line_cell_magic |
|
198 | 198 | def prun(self, parameter_s='', cell=None): |
|
199 | 199 | |
|
200 | 200 | """Run a statement through the python code profiler. |
|
201 | 201 | |
|
202 | 202 | Usage, in line mode: |
|
203 | 203 | %prun [options] statement |
|
204 | 204 | |
|
205 | 205 | Usage, in cell mode: |
|
206 | 206 | %%prun [options] [statement] |
|
207 | 207 | code... |
|
208 | 208 | code... |
|
209 | 209 | |
|
210 | 210 | In cell mode, the additional code lines are appended to the (possibly |
|
211 | 211 | empty) statement in the first line. Cell mode allows you to easily |
|
212 | 212 | profile multiline blocks without having to put them in a separate |
|
213 | 213 | function. |
|
214 | 214 | |
|
215 | 215 | The given statement (which doesn't require quote marks) is run via the |
|
216 | 216 | python profiler in a manner similar to the profile.run() function. |
|
217 | 217 | Namespaces are internally managed to work correctly; profile.run |
|
218 | 218 | cannot be used in IPython because it makes certain assumptions about |
|
219 | 219 | namespaces which do not hold under IPython. |
|
220 | 220 | |
|
221 | 221 | Options: |
|
222 | 222 | |
|
223 | 223 | -l <limit> |
|
224 | 224 | you can place restrictions on what or how much of the |
|
225 | 225 | profile gets printed. The limit value can be: |
|
226 | 226 | |
|
227 | 227 | * A string: only information for function names containing this string |
|
228 | 228 | is printed. |
|
229 | 229 | |
|
230 | 230 | * An integer: only these many lines are printed. |
|
231 | 231 | |
|
232 | 232 | * A float (between 0 and 1): this fraction of the report is printed |
|
233 | 233 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
234 | 234 | |
|
235 | 235 | You can combine several limits with repeated use of the option. For |
|
236 | 236 | example, ``-l __init__ -l 5`` will print only the topmost 5 lines of |
|
237 | 237 | information about class constructors. |
|
238 | 238 | |
|
239 | 239 | -r |
|
240 | 240 | return the pstats.Stats object generated by the profiling. This |
|
241 | 241 | object has all the information about the profile in it, and you can |
|
242 | 242 | later use it for further analysis or in other functions. |
|
243 | 243 | |
|
244 | 244 | -s <key> |
|
245 | 245 | sort profile by given key. You can provide more than one key |
|
246 | 246 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
247 | 247 | default sorting key is 'time'. |
|
248 | 248 | |
|
249 | 249 | The following is copied verbatim from the profile documentation |
|
250 | 250 | referenced below: |
|
251 | 251 | |
|
252 | 252 | When more than one key is provided, additional keys are used as |
|
253 | 253 | secondary criteria when the there is equality in all keys selected |
|
254 | 254 | before them. |
|
255 | 255 | |
|
256 | 256 | Abbreviations can be used for any key names, as long as the |
|
257 | 257 | abbreviation is unambiguous. The following are the keys currently |
|
258 | 258 | defined: |
|
259 | 259 | |
|
260 | 260 | ============ ===================== |
|
261 | 261 | Valid Arg Meaning |
|
262 | 262 | ============ ===================== |
|
263 | 263 | "calls" call count |
|
264 | 264 | "cumulative" cumulative time |
|
265 | 265 | "file" file name |
|
266 | 266 | "module" file name |
|
267 | 267 | "pcalls" primitive call count |
|
268 | 268 | "line" line number |
|
269 | 269 | "name" function name |
|
270 | 270 | "nfl" name/file/line |
|
271 | 271 | "stdname" standard name |
|
272 | 272 | "time" internal time |
|
273 | 273 | ============ ===================== |
|
274 | 274 | |
|
275 | 275 | Note that all sorts on statistics are in descending order (placing |
|
276 | 276 | most time consuming items first), where as name, file, and line number |
|
277 | 277 | searches are in ascending order (i.e., alphabetical). The subtle |
|
278 | 278 | distinction between "nfl" and "stdname" is that the standard name is a |
|
279 | 279 | sort of the name as printed, which means that the embedded line |
|
280 | 280 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
281 | 281 | would (if the file names were the same) appear in the string order |
|
282 | 282 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
283 | 283 | line numbers. In fact, sort_stats("nfl") is the same as |
|
284 | 284 | sort_stats("name", "file", "line"). |
|
285 | 285 | |
|
286 | 286 | -T <filename> |
|
287 | 287 | save profile results as shown on screen to a text |
|
288 | 288 | file. The profile is still shown on screen. |
|
289 | 289 | |
|
290 | 290 | -D <filename> |
|
291 | 291 | save (via dump_stats) profile statistics to given |
|
292 | 292 | filename. This data is in a format understood by the pstats module, and |
|
293 | 293 | is generated by a call to the dump_stats() method of profile |
|
294 | 294 | objects. The profile is still shown on screen. |
|
295 | 295 | |
|
296 | 296 | -q |
|
297 | 297 | suppress output to the pager. Best used with -T and/or -D above. |
|
298 | 298 | |
|
299 | 299 | If you want to run complete programs under the profiler's control, use |
|
300 | 300 | ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts |
|
301 | 301 | contains profiler specific options as described here. |
|
302 | 302 | |
|
303 | 303 | You can read the complete documentation for the profile module with:: |
|
304 | 304 | |
|
305 | 305 | In [1]: import profile; profile.help() |
|
306 | 306 | |
|
307 | 307 | .. versionchanged:: 7.3 |
|
308 | 308 | User variables are no longer expanded, |
|
309 | 309 | the magic line is always left unmodified. |
|
310 | 310 | |
|
311 | 311 | """ |
|
312 | 312 | opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q', |
|
313 | 313 | list_all=True, posix=False) |
|
314 | 314 | if cell is not None: |
|
315 | 315 | arg_str += '\n' + cell |
|
316 | 316 | arg_str = self.shell.transform_cell(arg_str) |
|
317 | 317 | return self._run_with_profiler(arg_str, opts, self.shell.user_ns) |
|
318 | 318 | |
|
319 | 319 | def _run_with_profiler(self, code, opts, namespace): |
|
320 | 320 | """ |
|
321 | 321 | Run `code` with profiler. Used by ``%prun`` and ``%run -p``. |
|
322 | 322 | |
|
323 | 323 | Parameters |
|
324 | 324 | ---------- |
|
325 | 325 | code : str |
|
326 | 326 | Code to be executed. |
|
327 | 327 | opts : Struct |
|
328 | 328 | Options parsed by `self.parse_options`. |
|
329 | 329 | namespace : dict |
|
330 | 330 | A dictionary for Python namespace (e.g., `self.shell.user_ns`). |
|
331 | 331 | |
|
332 | 332 | """ |
|
333 | 333 | |
|
334 | 334 | # Fill default values for unspecified options: |
|
335 | 335 | opts.merge(Struct(D=[''], l=[], s=['time'], T=[''])) |
|
336 | 336 | |
|
337 | 337 | prof = profile.Profile() |
|
338 | 338 | try: |
|
339 | 339 | prof = prof.runctx(code, namespace, namespace) |
|
340 | 340 | sys_exit = '' |
|
341 | 341 | except SystemExit: |
|
342 | 342 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
343 | 343 | |
|
344 | 344 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
345 | 345 | |
|
346 | 346 | lims = opts.l |
|
347 | 347 | if lims: |
|
348 | 348 | lims = [] # rebuild lims with ints/floats/strings |
|
349 | 349 | for lim in opts.l: |
|
350 | 350 | try: |
|
351 | 351 | lims.append(int(lim)) |
|
352 | 352 | except ValueError: |
|
353 | 353 | try: |
|
354 | 354 | lims.append(float(lim)) |
|
355 | 355 | except ValueError: |
|
356 | 356 | lims.append(lim) |
|
357 | 357 | |
|
358 | 358 | # Trap output. |
|
359 | 359 | stdout_trap = StringIO() |
|
360 | 360 | stats_stream = stats.stream |
|
361 | 361 | try: |
|
362 | 362 | stats.stream = stdout_trap |
|
363 | 363 | stats.print_stats(*lims) |
|
364 | 364 | finally: |
|
365 | 365 | stats.stream = stats_stream |
|
366 | 366 | |
|
367 | 367 | output = stdout_trap.getvalue() |
|
368 | 368 | output = output.rstrip() |
|
369 | 369 | |
|
370 | 370 | if 'q' not in opts: |
|
371 | 371 | page.page(output) |
|
372 | 372 | print(sys_exit, end=' ') |
|
373 | 373 | |
|
374 | 374 | dump_file = opts.D[0] |
|
375 | 375 | text_file = opts.T[0] |
|
376 | 376 | if dump_file: |
|
377 | 377 | prof.dump_stats(dump_file) |
|
378 | 378 | print('\n*** Profile stats marshalled to file',\ |
|
379 | 379 | repr(dump_file)+'.',sys_exit) |
|
380 | 380 | if text_file: |
|
381 | 381 | with open(text_file, 'w') as pfile: |
|
382 | 382 | pfile.write(output) |
|
383 | 383 | print('\n*** Profile printout saved to text file',\ |
|
384 | 384 | repr(text_file)+'.',sys_exit) |
|
385 | 385 | |
|
386 | 386 | if 'r' in opts: |
|
387 | 387 | return stats |
|
388 | 388 | else: |
|
389 | 389 | return None |
|
390 | 390 | |
|
391 | 391 | @line_magic |
|
392 | 392 | def pdb(self, parameter_s=''): |
|
393 | 393 | """Control the automatic calling of the pdb interactive debugger. |
|
394 | 394 | |
|
395 | 395 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
396 | 396 | argument it works as a toggle. |
|
397 | 397 | |
|
398 | 398 | When an exception is triggered, IPython can optionally call the |
|
399 | 399 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
400 | 400 | this feature on and off. |
|
401 | 401 | |
|
402 | 402 | The initial state of this feature is set in your configuration |
|
403 | 403 | file (the option is ``InteractiveShell.pdb``). |
|
404 | 404 | |
|
405 | 405 | If you want to just activate the debugger AFTER an exception has fired, |
|
406 | 406 | without having to type '%pdb on' and rerunning your code, you can use |
|
407 | 407 | the %debug magic.""" |
|
408 | 408 | |
|
409 | 409 | par = parameter_s.strip().lower() |
|
410 | 410 | |
|
411 | 411 | if par: |
|
412 | 412 | try: |
|
413 | 413 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
414 | 414 | except KeyError: |
|
415 | 415 | print ('Incorrect argument. Use on/1, off/0, ' |
|
416 | 416 | 'or nothing for a toggle.') |
|
417 | 417 | return |
|
418 | 418 | else: |
|
419 | 419 | # toggle |
|
420 | 420 | new_pdb = not self.shell.call_pdb |
|
421 | 421 | |
|
422 | 422 | # set on the shell |
|
423 | 423 | self.shell.call_pdb = new_pdb |
|
424 | 424 | print('Automatic pdb calling has been turned',on_off(new_pdb)) |
|
425 | 425 | |
|
426 | 426 | @skip_doctest |
|
427 | 427 | @magic_arguments.magic_arguments() |
|
428 | 428 | @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE', |
|
429 | 429 | help=""" |
|
430 | 430 | Set break point at LINE in FILE. |
|
431 | 431 | """ |
|
432 | 432 | ) |
|
433 | 433 | @magic_arguments.argument('statement', nargs='*', |
|
434 | 434 | help=""" |
|
435 | 435 | Code to run in debugger. |
|
436 | 436 | You can omit this in cell magic mode. |
|
437 | 437 | """ |
|
438 | 438 | ) |
|
439 | 439 | @no_var_expand |
|
440 | 440 | @line_cell_magic |
|
441 | 441 | def debug(self, line='', cell=None): |
|
442 | 442 | """Activate the interactive debugger. |
|
443 | 443 | |
|
444 | 444 | This magic command support two ways of activating debugger. |
|
445 | 445 | One is to activate debugger before executing code. This way, you |
|
446 | 446 | can set a break point, to step through the code from the point. |
|
447 | 447 | You can use this mode by giving statements to execute and optionally |
|
448 | 448 | a breakpoint. |
|
449 | 449 | |
|
450 | 450 | The other one is to activate debugger in post-mortem mode. You can |
|
451 | 451 | activate this mode simply running %debug without any argument. |
|
452 | 452 | If an exception has just occurred, this lets you inspect its stack |
|
453 | 453 | frames interactively. Note that this will always work only on the last |
|
454 | 454 | traceback that occurred, so you must call this quickly after an |
|
455 | 455 | exception that you wish to inspect has fired, because if another one |
|
456 | 456 | occurs, it clobbers the previous one. |
|
457 | 457 | |
|
458 | 458 | If you want IPython to automatically do this on every exception, see |
|
459 | 459 | the %pdb magic for more details. |
|
460 | 460 | |
|
461 | 461 | .. versionchanged:: 7.3 |
|
462 | 462 | When running code, user variables are no longer expanded, |
|
463 | 463 | the magic line is always left unmodified. |
|
464 | 464 | |
|
465 | 465 | """ |
|
466 | 466 | args = magic_arguments.parse_argstring(self.debug, line) |
|
467 | 467 | |
|
468 | 468 | if not (args.breakpoint or args.statement or cell): |
|
469 | 469 | self._debug_post_mortem() |
|
470 | 470 | else: |
|
471 | 471 | code = "\n".join(args.statement) |
|
472 | 472 | if cell: |
|
473 | 473 | code += "\n" + cell |
|
474 | 474 | self._debug_exec(code, args.breakpoint) |
|
475 | 475 | |
|
476 | 476 | def _debug_post_mortem(self): |
|
477 | 477 | self.shell.debugger(force=True) |
|
478 | 478 | |
|
479 | 479 | def _debug_exec(self, code, breakpoint): |
|
480 | 480 | if breakpoint: |
|
481 | 481 | (filename, bp_line) = breakpoint.rsplit(':', 1) |
|
482 | 482 | bp_line = int(bp_line) |
|
483 | 483 | else: |
|
484 | 484 | (filename, bp_line) = (None, None) |
|
485 | 485 | self._run_with_debugger(code, self.shell.user_ns, filename, bp_line) |
|
486 | 486 | |
|
487 | 487 | @line_magic |
|
488 | 488 | def tb(self, s): |
|
489 | 489 | """Print the last traceback. |
|
490 | 490 | |
|
491 | 491 | Optionally, specify an exception reporting mode, tuning the |
|
492 | 492 | verbosity of the traceback. By default the currently-active exception |
|
493 | 493 | mode is used. See %xmode for changing exception reporting modes. |
|
494 | 494 | |
|
495 | 495 | Valid modes: Plain, Context, Verbose, and Minimal. |
|
496 | 496 | """ |
|
497 | 497 | interactive_tb = self.shell.InteractiveTB |
|
498 | 498 | if s: |
|
499 | 499 | # Switch exception reporting mode for this one call. |
|
500 | 500 | # Ensure it is switched back. |
|
501 | 501 | def xmode_switch_err(name): |
|
502 | 502 | warn('Error changing %s exception modes.\n%s' % |
|
503 | 503 | (name,sys.exc_info()[1])) |
|
504 | 504 | |
|
505 | 505 | new_mode = s.strip().capitalize() |
|
506 | 506 | original_mode = interactive_tb.mode |
|
507 | 507 | try: |
|
508 | 508 | try: |
|
509 | 509 | interactive_tb.set_mode(mode=new_mode) |
|
510 | 510 | except Exception: |
|
511 | 511 | xmode_switch_err('user') |
|
512 | 512 | else: |
|
513 | 513 | self.shell.showtraceback() |
|
514 | 514 | finally: |
|
515 | 515 | interactive_tb.set_mode(mode=original_mode) |
|
516 | 516 | else: |
|
517 | 517 | self.shell.showtraceback() |
|
518 | 518 | |
|
519 | 519 | @skip_doctest |
|
520 | 520 | @line_magic |
|
521 | 521 | def run(self, parameter_s='', runner=None, |
|
522 | 522 | file_finder=get_py_filename): |
|
523 | 523 | """Run the named file inside IPython as a program. |
|
524 | 524 | |
|
525 | 525 | Usage:: |
|
526 | 526 | |
|
527 | 527 | %run [-n -i -e -G] |
|
528 | 528 | [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )] |
|
529 | 529 | ( -m mod | file ) [args] |
|
530 | 530 | |
|
531 | 531 | Parameters after the filename are passed as command-line arguments to |
|
532 | 532 | the program (put in sys.argv). Then, control returns to IPython's |
|
533 | 533 | prompt. |
|
534 | 534 | |
|
535 | 535 | This is similar to running at a system prompt ``python file args``, |
|
536 | 536 | but with the advantage of giving you IPython's tracebacks, and of |
|
537 | 537 | loading all variables into your interactive namespace for further use |
|
538 | 538 | (unless -p is used, see below). |
|
539 | 539 | |
|
540 | 540 | The file is executed in a namespace initially consisting only of |
|
541 | 541 | ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus |
|
542 | 542 | sees its environment as if it were being run as a stand-alone program |
|
543 | 543 | (except for sharing global objects such as previously imported |
|
544 | 544 | modules). But after execution, the IPython interactive namespace gets |
|
545 | 545 | updated with all variables defined in the program (except for __name__ |
|
546 | 546 | and sys.argv). This allows for very convenient loading of code for |
|
547 | 547 | interactive work, while giving each program a 'clean sheet' to run in. |
|
548 | 548 | |
|
549 | 549 | Arguments are expanded using shell-like glob match. Patterns |
|
550 | 550 | '*', '?', '[seq]' and '[!seq]' can be used. Additionally, |
|
551 | 551 | tilde '~' will be expanded into user's home directory. Unlike |
|
552 | 552 | real shells, quotation does not suppress expansions. Use |
|
553 | 553 | *two* back slashes (e.g. ``\\\\*``) to suppress expansions. |
|
554 | 554 | To completely disable these expansions, you can use -G flag. |
|
555 | 555 | |
|
556 | 556 | On Windows systems, the use of single quotes `'` when specifying |
|
557 | 557 | a file is not supported. Use double quotes `"`. |
|
558 | 558 | |
|
559 | 559 | Options: |
|
560 | 560 | |
|
561 | 561 | -n |
|
562 | 562 | __name__ is NOT set to '__main__', but to the running file's name |
|
563 | 563 | without extension (as python does under import). This allows running |
|
564 | 564 | scripts and reloading the definitions in them without calling code |
|
565 | 565 | protected by an ``if __name__ == "__main__"`` clause. |
|
566 | 566 | |
|
567 | 567 | -i |
|
568 | 568 | run the file in IPython's namespace instead of an empty one. This |
|
569 | 569 | is useful if you are experimenting with code written in a text editor |
|
570 | 570 | which depends on variables defined interactively. |
|
571 | 571 | |
|
572 | 572 | -e |
|
573 | 573 | ignore sys.exit() calls or SystemExit exceptions in the script |
|
574 | 574 | being run. This is particularly useful if IPython is being used to |
|
575 | 575 | run unittests, which always exit with a sys.exit() call. In such |
|
576 | 576 | cases you are interested in the output of the test results, not in |
|
577 | 577 | seeing a traceback of the unittest module. |
|
578 | 578 | |
|
579 | 579 | -t |
|
580 | 580 | print timing information at the end of the run. IPython will give |
|
581 | 581 | you an estimated CPU time consumption for your script, which under |
|
582 | 582 | Unix uses the resource module to avoid the wraparound problems of |
|
583 | 583 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
584 | 584 | is also given (for Windows platforms this is reported as 0.0). |
|
585 | 585 | |
|
586 | 586 | If -t is given, an additional ``-N<N>`` option can be given, where <N> |
|
587 | 587 | must be an integer indicating how many times you want the script to |
|
588 | 588 | run. The final timing report will include total and per run results. |
|
589 | 589 | |
|
590 | 590 | For example (testing the script uniq_stable.py):: |
|
591 | 591 | |
|
592 | 592 | In [1]: run -t uniq_stable |
|
593 | 593 | |
|
594 | 594 | IPython CPU timings (estimated): |
|
595 | 595 | User : 0.19597 s. |
|
596 | 596 | System: 0.0 s. |
|
597 | 597 | |
|
598 | 598 | In [2]: run -t -N5 uniq_stable |
|
599 | 599 | |
|
600 | 600 | IPython CPU timings (estimated): |
|
601 | 601 | Total runs performed: 5 |
|
602 | 602 | Times : Total Per run |
|
603 | 603 | User : 0.910862 s, 0.1821724 s. |
|
604 | 604 | System: 0.0 s, 0.0 s. |
|
605 | 605 | |
|
606 | 606 | -d |
|
607 | 607 | run your program under the control of pdb, the Python debugger. |
|
608 | 608 | This allows you to execute your program step by step, watch variables, |
|
609 | 609 | etc. Internally, what IPython does is similar to calling:: |
|
610 | 610 | |
|
611 | 611 | pdb.run('execfile("YOURFILENAME")') |
|
612 | 612 | |
|
613 | 613 | with a breakpoint set on line 1 of your file. You can change the line |
|
614 | 614 | number for this automatic breakpoint to be <N> by using the -bN option |
|
615 | 615 | (where N must be an integer). For example:: |
|
616 | 616 | |
|
617 | 617 | %run -d -b40 myscript |
|
618 | 618 | |
|
619 | 619 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
620 | 620 | the first breakpoint must be set on a line which actually does |
|
621 | 621 | something (not a comment or docstring) for it to stop execution. |
|
622 | 622 | |
|
623 | 623 | Or you can specify a breakpoint in a different file:: |
|
624 | 624 | |
|
625 | 625 | %run -d -b myotherfile.py:20 myscript |
|
626 | 626 | |
|
627 | 627 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
628 | 628 | first enter 'c' (without quotes) to start execution up to the first |
|
629 | 629 | breakpoint. |
|
630 | 630 | |
|
631 | 631 | Entering 'help' gives information about the use of the debugger. You |
|
632 | 632 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
633 | 633 | at a prompt. |
|
634 | 634 | |
|
635 | 635 | -p |
|
636 | 636 | run program under the control of the Python profiler module (which |
|
637 | 637 | prints a detailed report of execution times, function calls, etc). |
|
638 | 638 | |
|
639 | 639 | You can pass other options after -p which affect the behavior of the |
|
640 | 640 | profiler itself. See the docs for %prun for details. |
|
641 | 641 | |
|
642 | 642 | In this mode, the program's variables do NOT propagate back to the |
|
643 | 643 | IPython interactive namespace (because they remain in the namespace |
|
644 | 644 | where the profiler executes them). |
|
645 | 645 | |
|
646 | 646 | Internally this triggers a call to %prun, see its documentation for |
|
647 | 647 | details on the options available specifically for profiling. |
|
648 | 648 | |
|
649 | 649 | There is one special usage for which the text above doesn't apply: |
|
650 | 650 | if the filename ends with .ipy[nb], the file is run as ipython script, |
|
651 | 651 | just as if the commands were written on IPython prompt. |
|
652 | 652 | |
|
653 | 653 | -m |
|
654 | 654 | specify module name to load instead of script path. Similar to |
|
655 | 655 | the -m option for the python interpreter. Use this option last if you |
|
656 | 656 | want to combine with other %run options. Unlike the python interpreter |
|
657 | 657 | only source modules are allowed no .pyc or .pyo files. |
|
658 | 658 | For example:: |
|
659 | 659 | |
|
660 | 660 | %run -m example |
|
661 | 661 | |
|
662 | 662 | will run the example module. |
|
663 | 663 | |
|
664 | 664 | -G |
|
665 | 665 | disable shell-like glob expansion of arguments. |
|
666 | 666 | |
|
667 | 667 | """ |
|
668 | 668 | |
|
669 | 669 | # Logic to handle issue #3664 |
|
670 | 670 | # Add '--' after '-m <module_name>' to ignore additional args passed to a module. |
|
671 | 671 | if '-m' in parameter_s and '--' not in parameter_s: |
|
672 | 672 | argv = shlex.split(parameter_s, posix=(os.name == 'posix')) |
|
673 | 673 | for idx, arg in enumerate(argv): |
|
674 | 674 | if arg and arg.startswith('-') and arg != '-': |
|
675 | 675 | if arg == '-m': |
|
676 | 676 | argv.insert(idx + 2, '--') |
|
677 | 677 | break |
|
678 | 678 | else: |
|
679 | 679 | # Positional arg, break |
|
680 | 680 | break |
|
681 | 681 | parameter_s = ' '.join(shlex.quote(arg) for arg in argv) |
|
682 | 682 | |
|
683 | 683 | # get arguments and set sys.argv for program to be run. |
|
684 | 684 | opts, arg_lst = self.parse_options(parameter_s, |
|
685 | 685 | 'nidtN:b:pD:l:rs:T:em:G', |
|
686 | 686 | mode='list', list_all=1) |
|
687 | 687 | if "m" in opts: |
|
688 | 688 | modulename = opts["m"][0] |
|
689 | 689 | modpath = find_mod(modulename) |
|
690 | 690 | if modpath is None: |
|
691 | 691 | warn('%r is not a valid modulename on sys.path'%modulename) |
|
692 | 692 | return |
|
693 | 693 | arg_lst = [modpath] + arg_lst |
|
694 | 694 | try: |
|
695 | 695 | fpath = None # initialize to make sure fpath is in scope later |
|
696 | 696 | fpath = arg_lst[0] |
|
697 | 697 | filename = file_finder(fpath) |
|
698 | 698 | except IndexError: |
|
699 | 699 | warn('you must provide at least a filename.') |
|
700 | 700 | print('\n%run:\n', oinspect.getdoc(self.run)) |
|
701 | 701 | return |
|
702 | 702 | except IOError as e: |
|
703 | 703 | try: |
|
704 | 704 | msg = str(e) |
|
705 | 705 | except UnicodeError: |
|
706 | 706 | msg = e.message |
|
707 | 707 | if os.name == 'nt' and re.match(r"^'.*'$",fpath): |
|
708 | 708 | warn('For Windows, use double quotes to wrap a filename: %run "mypath\\myfile.py"') |
|
709 | 709 | error(msg) |
|
710 | 710 | return |
|
711 | 711 | |
|
712 | 712 | if filename.lower().endswith(('.ipy', '.ipynb')): |
|
713 | 713 | with preserve_keys(self.shell.user_ns, '__file__'): |
|
714 | 714 | self.shell.user_ns['__file__'] = filename |
|
715 | 715 | self.shell.safe_execfile_ipy(filename) |
|
716 | 716 | return |
|
717 | 717 | |
|
718 | 718 | # Control the response to exit() calls made by the script being run |
|
719 | 719 | exit_ignore = 'e' in opts |
|
720 | 720 | |
|
721 | 721 | # Make sure that the running script gets a proper sys.argv as if it |
|
722 | 722 | # were run from a system shell. |
|
723 | 723 | save_argv = sys.argv # save it for later restoring |
|
724 | 724 | |
|
725 | 725 | if 'G' in opts: |
|
726 | 726 | args = arg_lst[1:] |
|
727 | 727 | else: |
|
728 | 728 | # tilde and glob expansion |
|
729 | 729 | args = shellglob(map(os.path.expanduser, arg_lst[1:])) |
|
730 | 730 | |
|
731 | 731 | sys.argv = [filename] + args # put in the proper filename |
|
732 | 732 | |
|
733 | 733 | if 'n' in opts: |
|
734 | 734 | name = os.path.splitext(os.path.basename(filename))[0] |
|
735 | 735 | else: |
|
736 | 736 | name = '__main__' |
|
737 | 737 | |
|
738 | 738 | if 'i' in opts: |
|
739 | 739 | # Run in user's interactive namespace |
|
740 | 740 | prog_ns = self.shell.user_ns |
|
741 | 741 | __name__save = self.shell.user_ns['__name__'] |
|
742 | 742 | prog_ns['__name__'] = name |
|
743 | 743 | main_mod = self.shell.user_module |
|
744 | 744 | |
|
745 | 745 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
746 | 746 | # set the __file__ global in the script's namespace |
|
747 | 747 | # TK: Is this necessary in interactive mode? |
|
748 | 748 | prog_ns['__file__'] = filename |
|
749 | 749 | else: |
|
750 | 750 | # Run in a fresh, empty namespace |
|
751 | 751 | |
|
752 | 752 | # The shell MUST hold a reference to prog_ns so after %run |
|
753 | 753 | # exits, the python deletion mechanism doesn't zero it out |
|
754 | 754 | # (leaving dangling references). See interactiveshell for details |
|
755 | 755 | main_mod = self.shell.new_main_mod(filename, name) |
|
756 | 756 | prog_ns = main_mod.__dict__ |
|
757 | 757 | |
|
758 | 758 | # pickle fix. See interactiveshell for an explanation. But we need to |
|
759 | 759 | # make sure that, if we overwrite __main__, we replace it at the end |
|
760 | 760 | main_mod_name = prog_ns['__name__'] |
|
761 | 761 | |
|
762 | 762 | if main_mod_name == '__main__': |
|
763 | 763 | restore_main = sys.modules['__main__'] |
|
764 | 764 | else: |
|
765 | 765 | restore_main = False |
|
766 | 766 | |
|
767 | 767 | # This needs to be undone at the end to prevent holding references to |
|
768 | 768 | # every single object ever created. |
|
769 | 769 | sys.modules[main_mod_name] = main_mod |
|
770 | 770 | |
|
771 | 771 | if 'p' in opts or 'd' in opts: |
|
772 | 772 | if 'm' in opts: |
|
773 | 773 | code = 'run_module(modulename, prog_ns)' |
|
774 | 774 | code_ns = { |
|
775 | 775 | 'run_module': self.shell.safe_run_module, |
|
776 | 776 | 'prog_ns': prog_ns, |
|
777 | 777 | 'modulename': modulename, |
|
778 | 778 | } |
|
779 | 779 | else: |
|
780 | 780 | if 'd' in opts: |
|
781 | 781 | # allow exceptions to raise in debug mode |
|
782 | 782 | code = 'execfile(filename, prog_ns, raise_exceptions=True)' |
|
783 | 783 | else: |
|
784 | 784 | code = 'execfile(filename, prog_ns)' |
|
785 | 785 | code_ns = { |
|
786 | 786 | 'execfile': self.shell.safe_execfile, |
|
787 | 787 | 'prog_ns': prog_ns, |
|
788 | 788 | 'filename': get_py_filename(filename), |
|
789 | 789 | } |
|
790 | 790 | |
|
791 | 791 | try: |
|
792 | 792 | stats = None |
|
793 | 793 | if 'p' in opts: |
|
794 | 794 | stats = self._run_with_profiler(code, opts, code_ns) |
|
795 | 795 | else: |
|
796 | 796 | if 'd' in opts: |
|
797 | 797 | bp_file, bp_line = parse_breakpoint( |
|
798 | 798 | opts.get('b', ['1'])[0], filename) |
|
799 | 799 | self._run_with_debugger( |
|
800 | 800 | code, code_ns, filename, bp_line, bp_file) |
|
801 | 801 | else: |
|
802 | 802 | if 'm' in opts: |
|
803 | 803 | def run(): |
|
804 | 804 | self.shell.safe_run_module(modulename, prog_ns) |
|
805 | 805 | else: |
|
806 | 806 | if runner is None: |
|
807 | 807 | runner = self.default_runner |
|
808 | 808 | if runner is None: |
|
809 | 809 | runner = self.shell.safe_execfile |
|
810 | 810 | |
|
811 | 811 | def run(): |
|
812 | 812 | runner(filename, prog_ns, prog_ns, |
|
813 | 813 | exit_ignore=exit_ignore) |
|
814 | 814 | |
|
815 | 815 | if 't' in opts: |
|
816 | 816 | # timed execution |
|
817 | 817 | try: |
|
818 | 818 | nruns = int(opts['N'][0]) |
|
819 | 819 | if nruns < 1: |
|
820 | 820 | error('Number of runs must be >=1') |
|
821 | 821 | return |
|
822 | 822 | except (KeyError): |
|
823 | 823 | nruns = 1 |
|
824 | 824 | self._run_with_timing(run, nruns) |
|
825 | 825 | else: |
|
826 | 826 | # regular execution |
|
827 | 827 | run() |
|
828 | 828 | |
|
829 | 829 | if 'i' in opts: |
|
830 | 830 | self.shell.user_ns['__name__'] = __name__save |
|
831 | 831 | else: |
|
832 | 832 | # update IPython interactive namespace |
|
833 | 833 | |
|
834 | 834 | # Some forms of read errors on the file may mean the |
|
835 | 835 | # __name__ key was never set; using pop we don't have to |
|
836 | 836 | # worry about a possible KeyError. |
|
837 | 837 | prog_ns.pop('__name__', None) |
|
838 | 838 | |
|
839 | 839 | with preserve_keys(self.shell.user_ns, '__file__'): |
|
840 | 840 | self.shell.user_ns.update(prog_ns) |
|
841 | 841 | finally: |
|
842 | 842 | # It's a bit of a mystery why, but __builtins__ can change from |
|
843 | 843 | # being a module to becoming a dict missing some key data after |
|
844 | 844 | # %run. As best I can see, this is NOT something IPython is doing |
|
845 | 845 | # at all, and similar problems have been reported before: |
|
846 | 846 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html |
|
847 | 847 | # Since this seems to be done by the interpreter itself, the best |
|
848 | 848 | # we can do is to at least restore __builtins__ for the user on |
|
849 | 849 | # exit. |
|
850 | 850 | self.shell.user_ns['__builtins__'] = builtin_mod |
|
851 | 851 | |
|
852 | 852 | # Ensure key global structures are restored |
|
853 | 853 | sys.argv = save_argv |
|
854 | 854 | if restore_main: |
|
855 | 855 | sys.modules['__main__'] = restore_main |
|
856 | if '__mp_main__' in sys.modules: | |
|
857 | sys.modules['__mp_main__'] = restore_main | |
|
856 | 858 | else: |
|
857 | 859 | # Remove from sys.modules the reference to main_mod we'd |
|
858 | 860 | # added. Otherwise it will trap references to objects |
|
859 | 861 | # contained therein. |
|
860 | 862 | del sys.modules[main_mod_name] |
|
861 | 863 | |
|
862 | 864 | return stats |
|
863 | 865 | |
|
864 | 866 | def _run_with_debugger(self, code, code_ns, filename=None, |
|
865 | 867 | bp_line=None, bp_file=None): |
|
866 | 868 | """ |
|
867 | 869 | Run `code` in debugger with a break point. |
|
868 | 870 | |
|
869 | 871 | Parameters |
|
870 | 872 | ---------- |
|
871 | 873 | code : str |
|
872 | 874 | Code to execute. |
|
873 | 875 | code_ns : dict |
|
874 | 876 | A namespace in which `code` is executed. |
|
875 | 877 | filename : str |
|
876 | 878 | `code` is ran as if it is in `filename`. |
|
877 | 879 | bp_line : int, optional |
|
878 | 880 | Line number of the break point. |
|
879 | 881 | bp_file : str, optional |
|
880 | 882 | Path to the file in which break point is specified. |
|
881 | 883 | `filename` is used if not given. |
|
882 | 884 | |
|
883 | 885 | Raises |
|
884 | 886 | ------ |
|
885 | 887 | UsageError |
|
886 | 888 | If the break point given by `bp_line` is not valid. |
|
887 | 889 | |
|
888 | 890 | """ |
|
889 | 891 | deb = self.shell.InteractiveTB.pdb |
|
890 | 892 | if not deb: |
|
891 | 893 | self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls() |
|
892 | 894 | deb = self.shell.InteractiveTB.pdb |
|
893 | 895 | |
|
894 | 896 | # deb.checkline() fails if deb.curframe exists but is None; it can |
|
895 | 897 | # handle it not existing. https://github.com/ipython/ipython/issues/10028 |
|
896 | 898 | if hasattr(deb, 'curframe'): |
|
897 | 899 | del deb.curframe |
|
898 | 900 | |
|
899 | 901 | # reset Breakpoint state, which is moronically kept |
|
900 | 902 | # in a class |
|
901 | 903 | bdb.Breakpoint.next = 1 |
|
902 | 904 | bdb.Breakpoint.bplist = {} |
|
903 | 905 | bdb.Breakpoint.bpbynumber = [None] |
|
904 | 906 | deb.clear_all_breaks() |
|
905 | 907 | if bp_line is not None: |
|
906 | 908 | # Set an initial breakpoint to stop execution |
|
907 | 909 | maxtries = 10 |
|
908 | 910 | bp_file = bp_file or filename |
|
909 | 911 | checkline = deb.checkline(bp_file, bp_line) |
|
910 | 912 | if not checkline: |
|
911 | 913 | for bp in range(bp_line + 1, bp_line + maxtries + 1): |
|
912 | 914 | if deb.checkline(bp_file, bp): |
|
913 | 915 | break |
|
914 | 916 | else: |
|
915 | 917 | msg = ("\nI failed to find a valid line to set " |
|
916 | 918 | "a breakpoint\n" |
|
917 | 919 | "after trying up to line: %s.\n" |
|
918 | 920 | "Please set a valid breakpoint manually " |
|
919 | 921 | "with the -b option." % bp) |
|
920 | 922 | raise UsageError(msg) |
|
921 | 923 | # if we find a good linenumber, set the breakpoint |
|
922 | 924 | deb.do_break('%s:%s' % (bp_file, bp_line)) |
|
923 | 925 | |
|
924 | 926 | if filename: |
|
925 | 927 | # Mimic Pdb._runscript(...) |
|
926 | 928 | deb._wait_for_mainpyfile = True |
|
927 | 929 | deb.mainpyfile = deb.canonic(filename) |
|
928 | 930 | |
|
929 | 931 | # Start file run |
|
930 | 932 | print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt) |
|
931 | 933 | try: |
|
932 | 934 | if filename: |
|
933 | 935 | # save filename so it can be used by methods on the deb object |
|
934 | 936 | deb._exec_filename = filename |
|
935 | 937 | while True: |
|
936 | 938 | try: |
|
937 | 939 | trace = sys.gettrace() |
|
938 | 940 | deb.run(code, code_ns) |
|
939 | 941 | except Restart: |
|
940 | 942 | print("Restarting") |
|
941 | 943 | if filename: |
|
942 | 944 | deb._wait_for_mainpyfile = True |
|
943 | 945 | deb.mainpyfile = deb.canonic(filename) |
|
944 | 946 | continue |
|
945 | 947 | else: |
|
946 | 948 | break |
|
947 | 949 | finally: |
|
948 | 950 | sys.settrace(trace) |
|
949 | 951 | |
|
950 | 952 | |
|
951 | 953 | except: |
|
952 | 954 | etype, value, tb = sys.exc_info() |
|
953 | 955 | # Skip three frames in the traceback: the %run one, |
|
954 | 956 | # one inside bdb.py, and the command-line typed by the |
|
955 | 957 | # user (run by exec in pdb itself). |
|
956 | 958 | self.shell.InteractiveTB(etype, value, tb, tb_offset=3) |
|
957 | 959 | |
|
958 | 960 | @staticmethod |
|
959 | 961 | def _run_with_timing(run, nruns): |
|
960 | 962 | """ |
|
961 | 963 | Run function `run` and print timing information. |
|
962 | 964 | |
|
963 | 965 | Parameters |
|
964 | 966 | ---------- |
|
965 | 967 | run : callable |
|
966 | 968 | Any callable object which takes no argument. |
|
967 | 969 | nruns : int |
|
968 | 970 | Number of times to execute `run`. |
|
969 | 971 | |
|
970 | 972 | """ |
|
971 | 973 | twall0 = time.perf_counter() |
|
972 | 974 | if nruns == 1: |
|
973 | 975 | t0 = clock2() |
|
974 | 976 | run() |
|
975 | 977 | t1 = clock2() |
|
976 | 978 | t_usr = t1[0] - t0[0] |
|
977 | 979 | t_sys = t1[1] - t0[1] |
|
978 | 980 | print("\nIPython CPU timings (estimated):") |
|
979 | 981 | print(" User : %10.2f s." % t_usr) |
|
980 | 982 | print(" System : %10.2f s." % t_sys) |
|
981 | 983 | else: |
|
982 | 984 | runs = range(nruns) |
|
983 | 985 | t0 = clock2() |
|
984 | 986 | for nr in runs: |
|
985 | 987 | run() |
|
986 | 988 | t1 = clock2() |
|
987 | 989 | t_usr = t1[0] - t0[0] |
|
988 | 990 | t_sys = t1[1] - t0[1] |
|
989 | 991 | print("\nIPython CPU timings (estimated):") |
|
990 | 992 | print("Total runs performed:", nruns) |
|
991 | 993 | print(" Times : %10s %10s" % ('Total', 'Per run')) |
|
992 | 994 | print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)) |
|
993 | 995 | print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)) |
|
994 | 996 | twall1 = time.perf_counter() |
|
995 | 997 | print("Wall time: %10.2f s." % (twall1 - twall0)) |
|
996 | 998 | |
|
997 | 999 | @skip_doctest |
|
998 | 1000 | @no_var_expand |
|
999 | 1001 | @line_cell_magic |
|
1000 | 1002 | @needs_local_scope |
|
1001 | 1003 | def timeit(self, line='', cell=None, local_ns=None): |
|
1002 | 1004 | """Time execution of a Python statement or expression |
|
1003 | 1005 | |
|
1004 | 1006 | Usage, in line mode: |
|
1005 | 1007 | %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement |
|
1006 | 1008 | or in cell mode: |
|
1007 | 1009 | %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code |
|
1008 | 1010 | code |
|
1009 | 1011 | code... |
|
1010 | 1012 | |
|
1011 | 1013 | Time execution of a Python statement or expression using the timeit |
|
1012 | 1014 | module. This function can be used both as a line and cell magic: |
|
1013 | 1015 | |
|
1014 | 1016 | - In line mode you can time a single-line statement (though multiple |
|
1015 | 1017 | ones can be chained with using semicolons). |
|
1016 | 1018 | |
|
1017 | 1019 | - In cell mode, the statement in the first line is used as setup code |
|
1018 | 1020 | (executed but not timed) and the body of the cell is timed. The cell |
|
1019 | 1021 | body has access to any variables created in the setup code. |
|
1020 | 1022 | |
|
1021 | 1023 | Options: |
|
1022 | 1024 | -n<N>: execute the given statement <N> times in a loop. If <N> is not |
|
1023 | 1025 | provided, <N> is determined so as to get sufficient accuracy. |
|
1024 | 1026 | |
|
1025 | 1027 | -r<R>: number of repeats <R>, each consisting of <N> loops, and take the |
|
1026 | 1028 | best result. |
|
1027 | 1029 | Default: 7 |
|
1028 | 1030 | |
|
1029 | 1031 | -t: use time.time to measure the time, which is the default on Unix. |
|
1030 | 1032 | This function measures wall time. |
|
1031 | 1033 | |
|
1032 | 1034 | -c: use time.clock to measure the time, which is the default on |
|
1033 | 1035 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1034 | 1036 | instead and returns the CPU user time. |
|
1035 | 1037 | |
|
1036 | 1038 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1037 | 1039 | Default: 3 |
|
1038 | 1040 | |
|
1039 | 1041 | -q: Quiet, do not print result. |
|
1040 | 1042 | |
|
1041 | 1043 | -o: return a TimeitResult that can be stored in a variable to inspect |
|
1042 | 1044 | the result in more details. |
|
1043 | 1045 | |
|
1044 | 1046 | .. versionchanged:: 7.3 |
|
1045 | 1047 | User variables are no longer expanded, |
|
1046 | 1048 | the magic line is always left unmodified. |
|
1047 | 1049 | |
|
1048 | 1050 | Examples |
|
1049 | 1051 | -------- |
|
1050 | 1052 | :: |
|
1051 | 1053 | |
|
1052 | 1054 | In [1]: %timeit pass |
|
1053 | 1055 | 8.26 ns ± 0.12 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each) |
|
1054 | 1056 | |
|
1055 | 1057 | In [2]: u = None |
|
1056 | 1058 | |
|
1057 | 1059 | In [3]: %timeit u is None |
|
1058 | 1060 | 29.9 ns ± 0.643 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) |
|
1059 | 1061 | |
|
1060 | 1062 | In [4]: %timeit -r 4 u == None |
|
1061 | 1063 | |
|
1062 | 1064 | In [5]: import time |
|
1063 | 1065 | |
|
1064 | 1066 | In [6]: %timeit -n1 time.sleep(2) |
|
1065 | 1067 | |
|
1066 | 1068 | |
|
1067 | 1069 | The times reported by %timeit will be slightly higher than those |
|
1068 | 1070 | reported by the timeit.py script when variables are accessed. This is |
|
1069 | 1071 | due to the fact that %timeit executes the statement in the namespace |
|
1070 | 1072 | of the shell, compared with timeit.py, which uses a single setup |
|
1071 | 1073 | statement to import function or create variables. Generally, the bias |
|
1072 | 1074 | does not matter as long as results from timeit.py are not mixed with |
|
1073 | 1075 | those from %timeit.""" |
|
1074 | 1076 | |
|
1075 | 1077 | opts, stmt = self.parse_options(line,'n:r:tcp:qo', |
|
1076 | 1078 | posix=False, strict=False) |
|
1077 | 1079 | if stmt == "" and cell is None: |
|
1078 | 1080 | return |
|
1079 | 1081 | |
|
1080 | 1082 | timefunc = timeit.default_timer |
|
1081 | 1083 | number = int(getattr(opts, "n", 0)) |
|
1082 | 1084 | default_repeat = 7 if timeit.default_repeat < 7 else timeit.default_repeat |
|
1083 | 1085 | repeat = int(getattr(opts, "r", default_repeat)) |
|
1084 | 1086 | precision = int(getattr(opts, "p", 3)) |
|
1085 | 1087 | quiet = 'q' in opts |
|
1086 | 1088 | return_result = 'o' in opts |
|
1087 | 1089 | if hasattr(opts, "t"): |
|
1088 | 1090 | timefunc = time.time |
|
1089 | 1091 | if hasattr(opts, "c"): |
|
1090 | 1092 | timefunc = clock |
|
1091 | 1093 | |
|
1092 | 1094 | timer = Timer(timer=timefunc) |
|
1093 | 1095 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1094 | 1096 | # but is there a better way to achieve that the code stmt has access |
|
1095 | 1097 | # to the shell namespace? |
|
1096 | 1098 | transform = self.shell.transform_cell |
|
1097 | 1099 | |
|
1098 | 1100 | if cell is None: |
|
1099 | 1101 | # called as line magic |
|
1100 | 1102 | ast_setup = self.shell.compile.ast_parse("pass") |
|
1101 | 1103 | ast_stmt = self.shell.compile.ast_parse(transform(stmt)) |
|
1102 | 1104 | else: |
|
1103 | 1105 | ast_setup = self.shell.compile.ast_parse(transform(stmt)) |
|
1104 | 1106 | ast_stmt = self.shell.compile.ast_parse(transform(cell)) |
|
1105 | 1107 | |
|
1106 | 1108 | ast_setup = self.shell.transform_ast(ast_setup) |
|
1107 | 1109 | ast_stmt = self.shell.transform_ast(ast_stmt) |
|
1108 | 1110 | |
|
1109 | 1111 | # Check that these compile to valid Python code *outside* the timer func |
|
1110 | 1112 | # Invalid code may become valid when put inside the function & loop, |
|
1111 | 1113 | # which messes up error messages. |
|
1112 | 1114 | # https://github.com/ipython/ipython/issues/10636 |
|
1113 | 1115 | self.shell.compile(ast_setup, "<magic-timeit-setup>", "exec") |
|
1114 | 1116 | self.shell.compile(ast_stmt, "<magic-timeit-stmt>", "exec") |
|
1115 | 1117 | |
|
1116 | 1118 | # This codestring is taken from timeit.template - we fill it in as an |
|
1117 | 1119 | # AST, so that we can apply our AST transformations to the user code |
|
1118 | 1120 | # without affecting the timing code. |
|
1119 | 1121 | timeit_ast_template = ast.parse('def inner(_it, _timer):\n' |
|
1120 | 1122 | ' setup\n' |
|
1121 | 1123 | ' _t0 = _timer()\n' |
|
1122 | 1124 | ' for _i in _it:\n' |
|
1123 | 1125 | ' stmt\n' |
|
1124 | 1126 | ' _t1 = _timer()\n' |
|
1125 | 1127 | ' return _t1 - _t0\n') |
|
1126 | 1128 | |
|
1127 | 1129 | timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template) |
|
1128 | 1130 | timeit_ast = ast.fix_missing_locations(timeit_ast) |
|
1129 | 1131 | |
|
1130 | 1132 | # Track compilation time so it can be reported if too long |
|
1131 | 1133 | # Minimum time above which compilation time will be reported |
|
1132 | 1134 | tc_min = 0.1 |
|
1133 | 1135 | |
|
1134 | 1136 | t0 = clock() |
|
1135 | 1137 | code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec") |
|
1136 | 1138 | tc = clock()-t0 |
|
1137 | 1139 | |
|
1138 | 1140 | ns = {} |
|
1139 | 1141 | glob = self.shell.user_ns |
|
1140 | 1142 | # handles global vars with same name as local vars. We store them in conflict_globs. |
|
1141 | 1143 | conflict_globs = {} |
|
1142 | 1144 | if local_ns and cell is None: |
|
1143 | 1145 | for var_name, var_val in glob.items(): |
|
1144 | 1146 | if var_name in local_ns: |
|
1145 | 1147 | conflict_globs[var_name] = var_val |
|
1146 | 1148 | glob.update(local_ns) |
|
1147 | 1149 | |
|
1148 | 1150 | exec(code, glob, ns) |
|
1149 | 1151 | timer.inner = ns["inner"] |
|
1150 | 1152 | |
|
1151 | 1153 | # This is used to check if there is a huge difference between the |
|
1152 | 1154 | # best and worst timings. |
|
1153 | 1155 | # Issue: https://github.com/ipython/ipython/issues/6471 |
|
1154 | 1156 | if number == 0: |
|
1155 | 1157 | # determine number so that 0.2 <= total time < 2.0 |
|
1156 | 1158 | for index in range(0, 10): |
|
1157 | 1159 | number = 10 ** index |
|
1158 | 1160 | time_number = timer.timeit(number) |
|
1159 | 1161 | if time_number >= 0.2: |
|
1160 | 1162 | break |
|
1161 | 1163 | |
|
1162 | 1164 | all_runs = timer.repeat(repeat, number) |
|
1163 | 1165 | best = min(all_runs) / number |
|
1164 | 1166 | worst = max(all_runs) / number |
|
1165 | 1167 | timeit_result = TimeitResult(number, repeat, best, worst, all_runs, tc, precision) |
|
1166 | 1168 | |
|
1167 | 1169 | # Restore global vars from conflict_globs |
|
1168 | 1170 | if conflict_globs: |
|
1169 | 1171 | glob.update(conflict_globs) |
|
1170 | 1172 | |
|
1171 | 1173 | if not quiet : |
|
1172 | 1174 | # Check best timing is greater than zero to avoid a |
|
1173 | 1175 | # ZeroDivisionError. |
|
1174 | 1176 | # In cases where the slowest timing is lesser than a microsecond |
|
1175 | 1177 | # we assume that it does not really matter if the fastest |
|
1176 | 1178 | # timing is 4 times faster than the slowest timing or not. |
|
1177 | 1179 | if worst > 4 * best and best > 0 and worst > 1e-6: |
|
1178 | 1180 | print("The slowest run took %0.2f times longer than the " |
|
1179 | 1181 | "fastest. This could mean that an intermediate result " |
|
1180 | 1182 | "is being cached." % (worst / best)) |
|
1181 | 1183 | |
|
1182 | 1184 | print( timeit_result ) |
|
1183 | 1185 | |
|
1184 | 1186 | if tc > tc_min: |
|
1185 | 1187 | print("Compiler time: %.2f s" % tc) |
|
1186 | 1188 | if return_result: |
|
1187 | 1189 | return timeit_result |
|
1188 | 1190 | |
|
1189 | 1191 | @skip_doctest |
|
1190 | 1192 | @no_var_expand |
|
1191 | 1193 | @needs_local_scope |
|
1192 | 1194 | @line_cell_magic |
|
1193 | 1195 | def time(self,line='', cell=None, local_ns=None): |
|
1194 | 1196 | """Time execution of a Python statement or expression. |
|
1195 | 1197 | |
|
1196 | 1198 | The CPU and wall clock times are printed, and the value of the |
|
1197 | 1199 | expression (if any) is returned. Note that under Win32, system time |
|
1198 | 1200 | is always reported as 0, since it can not be measured. |
|
1199 | 1201 | |
|
1200 | 1202 | This function can be used both as a line and cell magic: |
|
1201 | 1203 | |
|
1202 | 1204 | - In line mode you can time a single-line statement (though multiple |
|
1203 | 1205 | ones can be chained with using semicolons). |
|
1204 | 1206 | |
|
1205 | 1207 | - In cell mode, you can time the cell body (a directly |
|
1206 | 1208 | following statement raises an error). |
|
1207 | 1209 | |
|
1208 | 1210 | This function provides very basic timing functionality. Use the timeit |
|
1209 | 1211 | magic for more control over the measurement. |
|
1210 | 1212 | |
|
1211 | 1213 | .. versionchanged:: 7.3 |
|
1212 | 1214 | User variables are no longer expanded, |
|
1213 | 1215 | the magic line is always left unmodified. |
|
1214 | 1216 | |
|
1215 | 1217 | Examples |
|
1216 | 1218 | -------- |
|
1217 | 1219 | :: |
|
1218 | 1220 | |
|
1219 | 1221 | In [1]: %time 2**128 |
|
1220 | 1222 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1221 | 1223 | Wall time: 0.00 |
|
1222 | 1224 | Out[1]: 340282366920938463463374607431768211456L |
|
1223 | 1225 | |
|
1224 | 1226 | In [2]: n = 1000000 |
|
1225 | 1227 | |
|
1226 | 1228 | In [3]: %time sum(range(n)) |
|
1227 | 1229 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1228 | 1230 | Wall time: 1.37 |
|
1229 | 1231 | Out[3]: 499999500000L |
|
1230 | 1232 | |
|
1231 | 1233 | In [4]: %time print 'hello world' |
|
1232 | 1234 | hello world |
|
1233 | 1235 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1234 | 1236 | Wall time: 0.00 |
|
1235 | 1237 | |
|
1236 | 1238 | Note that the time needed by Python to compile the given expression |
|
1237 | 1239 | will be reported if it is more than 0.1s. In this example, the |
|
1238 | 1240 | actual exponentiation is done by Python at compilation time, so while |
|
1239 | 1241 | the expression can take a noticeable amount of time to compute, that |
|
1240 | 1242 | time is purely due to the compilation: |
|
1241 | 1243 | |
|
1242 | 1244 | In [5]: %time 3**9999; |
|
1243 | 1245 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1244 | 1246 | Wall time: 0.00 s |
|
1245 | 1247 | |
|
1246 | 1248 | In [6]: %time 3**999999; |
|
1247 | 1249 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1248 | 1250 | Wall time: 0.00 s |
|
1249 | 1251 | Compiler : 0.78 s |
|
1250 | 1252 | """ |
|
1251 | 1253 | |
|
1252 | 1254 | # fail immediately if the given expression can't be compiled |
|
1253 | 1255 | |
|
1254 | 1256 | if line and cell: |
|
1255 | 1257 | raise UsageError("Can't use statement directly after '%%time'!") |
|
1256 | 1258 | |
|
1257 | 1259 | if cell: |
|
1258 | 1260 | expr = self.shell.transform_cell(cell) |
|
1259 | 1261 | else: |
|
1260 | 1262 | expr = self.shell.transform_cell(line) |
|
1261 | 1263 | |
|
1262 | 1264 | # Minimum time above which parse time will be reported |
|
1263 | 1265 | tp_min = 0.1 |
|
1264 | 1266 | |
|
1265 | 1267 | t0 = clock() |
|
1266 | 1268 | expr_ast = self.shell.compile.ast_parse(expr) |
|
1267 | 1269 | tp = clock()-t0 |
|
1268 | 1270 | |
|
1269 | 1271 | # Apply AST transformations |
|
1270 | 1272 | expr_ast = self.shell.transform_ast(expr_ast) |
|
1271 | 1273 | |
|
1272 | 1274 | # Minimum time above which compilation time will be reported |
|
1273 | 1275 | tc_min = 0.1 |
|
1274 | 1276 | |
|
1275 | 1277 | expr_val=None |
|
1276 | 1278 | if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr): |
|
1277 | 1279 | mode = 'eval' |
|
1278 | 1280 | source = '<timed eval>' |
|
1279 | 1281 | expr_ast = ast.Expression(expr_ast.body[0].value) |
|
1280 | 1282 | else: |
|
1281 | 1283 | mode = 'exec' |
|
1282 | 1284 | source = '<timed exec>' |
|
1283 | 1285 | # multi-line %%time case |
|
1284 | 1286 | if len(expr_ast.body) > 1 and isinstance(expr_ast.body[-1], ast.Expr): |
|
1285 | 1287 | expr_val= expr_ast.body[-1] |
|
1286 | 1288 | expr_ast = expr_ast.body[:-1] |
|
1287 | 1289 | expr_ast = Module(expr_ast, []) |
|
1288 | 1290 | expr_val = ast.Expression(expr_val.value) |
|
1289 | 1291 | |
|
1290 | 1292 | t0 = clock() |
|
1291 | 1293 | code = self.shell.compile(expr_ast, source, mode) |
|
1292 | 1294 | tc = clock()-t0 |
|
1293 | 1295 | |
|
1294 | 1296 | # skew measurement as little as possible |
|
1295 | 1297 | glob = self.shell.user_ns |
|
1296 | 1298 | wtime = time.time |
|
1297 | 1299 | # time execution |
|
1298 | 1300 | wall_st = wtime() |
|
1299 | 1301 | if mode=='eval': |
|
1300 | 1302 | st = clock2() |
|
1301 | 1303 | try: |
|
1302 | 1304 | out = eval(code, glob, local_ns) |
|
1303 | 1305 | except: |
|
1304 | 1306 | self.shell.showtraceback() |
|
1305 | 1307 | return |
|
1306 | 1308 | end = clock2() |
|
1307 | 1309 | else: |
|
1308 | 1310 | st = clock2() |
|
1309 | 1311 | try: |
|
1310 | 1312 | exec(code, glob, local_ns) |
|
1311 | 1313 | out=None |
|
1312 | 1314 | # multi-line %%time case |
|
1313 | 1315 | if expr_val is not None: |
|
1314 | 1316 | code_2 = self.shell.compile(expr_val, source, 'eval') |
|
1315 | 1317 | out = eval(code_2, glob, local_ns) |
|
1316 | 1318 | except: |
|
1317 | 1319 | self.shell.showtraceback() |
|
1318 | 1320 | return |
|
1319 | 1321 | end = clock2() |
|
1320 | 1322 | |
|
1321 | 1323 | wall_end = wtime() |
|
1322 | 1324 | # Compute actual times and report |
|
1323 | 1325 | wall_time = wall_end-wall_st |
|
1324 | 1326 | cpu_user = end[0]-st[0] |
|
1325 | 1327 | cpu_sys = end[1]-st[1] |
|
1326 | 1328 | cpu_tot = cpu_user+cpu_sys |
|
1327 | 1329 | # On windows cpu_sys is always zero, so no new information to the next print |
|
1328 | 1330 | if sys.platform != 'win32': |
|
1329 | 1331 | print("CPU times: user %s, sys: %s, total: %s" % \ |
|
1330 | 1332 | (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot))) |
|
1331 | 1333 | print("Wall time: %s" % _format_time(wall_time)) |
|
1332 | 1334 | if tc > tc_min: |
|
1333 | 1335 | print("Compiler : %s" % _format_time(tc)) |
|
1334 | 1336 | if tp > tp_min: |
|
1335 | 1337 | print("Parser : %s" % _format_time(tp)) |
|
1336 | 1338 | return out |
|
1337 | 1339 | |
|
1338 | 1340 | @skip_doctest |
|
1339 | 1341 | @line_magic |
|
1340 | 1342 | def macro(self, parameter_s=''): |
|
1341 | 1343 | """Define a macro for future re-execution. It accepts ranges of history, |
|
1342 | 1344 | filenames or string objects. |
|
1343 | 1345 | |
|
1344 | 1346 | Usage:\\ |
|
1345 | 1347 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1346 | 1348 | |
|
1347 | 1349 | Options: |
|
1348 | 1350 | |
|
1349 | 1351 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1350 | 1352 | so that magics are loaded in their transformed version to valid |
|
1351 | 1353 | Python. If this option is given, the raw input as typed at the |
|
1352 | 1354 | command line is used instead. |
|
1353 | 1355 | |
|
1354 | 1356 | -q: quiet macro definition. By default, a tag line is printed |
|
1355 | 1357 | to indicate the macro has been created, and then the contents of |
|
1356 | 1358 | the macro are printed. If this option is given, then no printout |
|
1357 | 1359 | is produced once the macro is created. |
|
1358 | 1360 | |
|
1359 | 1361 | This will define a global variable called `name` which is a string |
|
1360 | 1362 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1361 | 1363 | above) from your input history into a single string. This variable |
|
1362 | 1364 | acts like an automatic function which re-executes those lines as if |
|
1363 | 1365 | you had typed them. You just type 'name' at the prompt and the code |
|
1364 | 1366 | executes. |
|
1365 | 1367 | |
|
1366 | 1368 | The syntax for indicating input ranges is described in %history. |
|
1367 | 1369 | |
|
1368 | 1370 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
1369 | 1371 | notation, where N:M means numbers N through M-1. |
|
1370 | 1372 | |
|
1371 | 1373 | For example, if your history contains (print using %hist -n ):: |
|
1372 | 1374 | |
|
1373 | 1375 | 44: x=1 |
|
1374 | 1376 | 45: y=3 |
|
1375 | 1377 | 46: z=x+y |
|
1376 | 1378 | 47: print x |
|
1377 | 1379 | 48: a=5 |
|
1378 | 1380 | 49: print 'x',x,'y',y |
|
1379 | 1381 | |
|
1380 | 1382 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
1381 | 1383 | called my_macro with:: |
|
1382 | 1384 | |
|
1383 | 1385 | In [55]: %macro my_macro 44-47 49 |
|
1384 | 1386 | |
|
1385 | 1387 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
1386 | 1388 | in one pass. |
|
1387 | 1389 | |
|
1388 | 1390 | You don't need to give the line-numbers in order, and any given line |
|
1389 | 1391 | number can appear multiple times. You can assemble macros with any |
|
1390 | 1392 | lines from your input history in any order. |
|
1391 | 1393 | |
|
1392 | 1394 | The macro is a simple object which holds its value in an attribute, |
|
1393 | 1395 | but IPython's display system checks for macros and executes them as |
|
1394 | 1396 | code instead of printing them when you type their name. |
|
1395 | 1397 | |
|
1396 | 1398 | You can view a macro's contents by explicitly printing it with:: |
|
1397 | 1399 | |
|
1398 | 1400 | print macro_name |
|
1399 | 1401 | |
|
1400 | 1402 | """ |
|
1401 | 1403 | opts,args = self.parse_options(parameter_s,'rq',mode='list') |
|
1402 | 1404 | if not args: # List existing macros |
|
1403 | 1405 | return sorted(k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)) |
|
1404 | 1406 | if len(args) == 1: |
|
1405 | 1407 | raise UsageError( |
|
1406 | 1408 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
1407 | 1409 | name, codefrom = args[0], " ".join(args[1:]) |
|
1408 | 1410 | |
|
1409 | 1411 | #print 'rng',ranges # dbg |
|
1410 | 1412 | try: |
|
1411 | 1413 | lines = self.shell.find_user_code(codefrom, 'r' in opts) |
|
1412 | 1414 | except (ValueError, TypeError) as e: |
|
1413 | 1415 | print(e.args[0]) |
|
1414 | 1416 | return |
|
1415 | 1417 | macro = Macro(lines) |
|
1416 | 1418 | self.shell.define_macro(name, macro) |
|
1417 | 1419 | if not ( 'q' in opts) : |
|
1418 | 1420 | print('Macro `%s` created. To execute, type its name (without quotes).' % name) |
|
1419 | 1421 | print('=== Macro contents: ===') |
|
1420 | 1422 | print(macro, end=' ') |
|
1421 | 1423 | |
|
1422 | 1424 | @magic_arguments.magic_arguments() |
|
1423 | 1425 | @magic_arguments.argument('output', type=str, default='', nargs='?', |
|
1424 | 1426 | help="""The name of the variable in which to store output. |
|
1425 | 1427 | This is a utils.io.CapturedIO object with stdout/err attributes |
|
1426 | 1428 | for the text of the captured output. |
|
1427 | 1429 | |
|
1428 | 1430 | CapturedOutput also has a show() method for displaying the output, |
|
1429 | 1431 | and __call__ as well, so you can use that to quickly display the |
|
1430 | 1432 | output. |
|
1431 | 1433 | |
|
1432 | 1434 | If unspecified, captured output is discarded. |
|
1433 | 1435 | """ |
|
1434 | 1436 | ) |
|
1435 | 1437 | @magic_arguments.argument('--no-stderr', action="store_true", |
|
1436 | 1438 | help="""Don't capture stderr.""" |
|
1437 | 1439 | ) |
|
1438 | 1440 | @magic_arguments.argument('--no-stdout', action="store_true", |
|
1439 | 1441 | help="""Don't capture stdout.""" |
|
1440 | 1442 | ) |
|
1441 | 1443 | @magic_arguments.argument('--no-display', action="store_true", |
|
1442 | 1444 | help="""Don't capture IPython's rich display.""" |
|
1443 | 1445 | ) |
|
1444 | 1446 | @cell_magic |
|
1445 | 1447 | def capture(self, line, cell): |
|
1446 | 1448 | """run the cell, capturing stdout, stderr, and IPython's rich display() calls.""" |
|
1447 | 1449 | args = magic_arguments.parse_argstring(self.capture, line) |
|
1448 | 1450 | out = not args.no_stdout |
|
1449 | 1451 | err = not args.no_stderr |
|
1450 | 1452 | disp = not args.no_display |
|
1451 | 1453 | with capture_output(out, err, disp) as io: |
|
1452 | 1454 | self.shell.run_cell(cell) |
|
1453 | 1455 | if args.output: |
|
1454 | 1456 | self.shell.user_ns[args.output] = io |
|
1455 | 1457 | |
|
1456 | 1458 | def parse_breakpoint(text, current_file): |
|
1457 | 1459 | '''Returns (file, line) for file:line and (current_file, line) for line''' |
|
1458 | 1460 | colon = text.find(':') |
|
1459 | 1461 | if colon == -1: |
|
1460 | 1462 | return current_file, int(text) |
|
1461 | 1463 | else: |
|
1462 | 1464 | return text[:colon], int(text[colon+1:]) |
|
1463 | 1465 | |
|
1464 | 1466 | def _format_time(timespan, precision=3): |
|
1465 | 1467 | """Formats the timespan in a human readable form""" |
|
1466 | 1468 | |
|
1467 | 1469 | if timespan >= 60.0: |
|
1468 | 1470 | # we have more than a minute, format that in a human readable form |
|
1469 | 1471 | # Idea from http://snipplr.com/view/5713/ |
|
1470 | 1472 | parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)] |
|
1471 | 1473 | time = [] |
|
1472 | 1474 | leftover = timespan |
|
1473 | 1475 | for suffix, length in parts: |
|
1474 | 1476 | value = int(leftover / length) |
|
1475 | 1477 | if value > 0: |
|
1476 | 1478 | leftover = leftover % length |
|
1477 | 1479 | time.append(u'%s%s' % (str(value), suffix)) |
|
1478 | 1480 | if leftover < 1: |
|
1479 | 1481 | break |
|
1480 | 1482 | return " ".join(time) |
|
1481 | 1483 | |
|
1482 | 1484 | |
|
1483 | 1485 | # Unfortunately the unicode 'micro' symbol can cause problems in |
|
1484 | 1486 | # certain terminals. |
|
1485 | 1487 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 |
|
1486 | 1488 | # Try to prevent crashes by being more secure than it needs to |
|
1487 | 1489 | # E.g. eclipse is able to print a µ, but has no sys.stdout.encoding set. |
|
1488 | 1490 | units = [u"s", u"ms",u'us',"ns"] # the save value |
|
1489 | 1491 | if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding: |
|
1490 | 1492 | try: |
|
1491 | 1493 | u'\xb5'.encode(sys.stdout.encoding) |
|
1492 | 1494 | units = [u"s", u"ms",u'\xb5s',"ns"] |
|
1493 | 1495 | except: |
|
1494 | 1496 | pass |
|
1495 | 1497 | scaling = [1, 1e3, 1e6, 1e9] |
|
1496 | 1498 | |
|
1497 | 1499 | if timespan > 0.0: |
|
1498 | 1500 | order = min(-int(math.floor(math.log10(timespan)) // 3), 3) |
|
1499 | 1501 | else: |
|
1500 | 1502 | order = 3 |
|
1501 | 1503 | return u"%.*g %s" % (precision, timespan * scaling[order], units[order]) |
@@ -1,1072 +1,1058 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Tools for inspecting Python objects. |
|
3 | 3 | |
|
4 | 4 | Uses syntax highlighting for presenting the various information elements. |
|
5 | 5 | |
|
6 | 6 | Similar in spirit to the inspect module, but all calls take a name argument to |
|
7 | 7 | reference the name under which an object is being read. |
|
8 | 8 | """ |
|
9 | 9 | |
|
10 | 10 | # Copyright (c) IPython Development Team. |
|
11 | 11 | # Distributed under the terms of the Modified BSD License. |
|
12 | 12 | |
|
13 | 13 | __all__ = ['Inspector','InspectColors'] |
|
14 | 14 | |
|
15 | 15 | # stdlib modules |
|
16 | 16 | import ast |
|
17 | 17 | import inspect |
|
18 | 18 | from inspect import signature |
|
19 | 19 | import linecache |
|
20 | 20 | import warnings |
|
21 | 21 | import os |
|
22 | 22 | from textwrap import dedent |
|
23 | 23 | import types |
|
24 | 24 | import io as stdlib_io |
|
25 | 25 | from itertools import zip_longest |
|
26 | 26 | |
|
27 | 27 | # IPython's own |
|
28 | 28 | from IPython.core import page |
|
29 | 29 | from IPython.lib.pretty import pretty |
|
30 | 30 | from IPython.testing.skipdoctest import skip_doctest |
|
31 | 31 | from IPython.utils import PyColorize |
|
32 | 32 | from IPython.utils import openpy |
|
33 | 33 | from IPython.utils import py3compat |
|
34 | 34 | from IPython.utils.dir2 import safe_hasattr |
|
35 | 35 | from IPython.utils.path import compress_user |
|
36 | 36 | from IPython.utils.text import indent |
|
37 | 37 | from IPython.utils.wildcard import list_namespace |
|
38 | 38 | from IPython.utils.wildcard import typestr2type |
|
39 | 39 | from IPython.utils.coloransi import TermColors, ColorScheme, ColorSchemeTable |
|
40 | 40 | from IPython.utils.py3compat import cast_unicode |
|
41 | 41 | from IPython.utils.colorable import Colorable |
|
42 | 42 | from IPython.utils.decorators import undoc |
|
43 | 43 | |
|
44 | 44 | from pygments import highlight |
|
45 | 45 | from pygments.lexers import PythonLexer |
|
46 | 46 | from pygments.formatters import HtmlFormatter |
|
47 | 47 | |
|
48 | 48 | def pylight(code): |
|
49 | 49 | return highlight(code, PythonLexer(), HtmlFormatter(noclasses=True)) |
|
50 | 50 | |
|
51 | 51 | # builtin docstrings to ignore |
|
52 | 52 | _func_call_docstring = types.FunctionType.__call__.__doc__ |
|
53 | 53 | _object_init_docstring = object.__init__.__doc__ |
|
54 | 54 | _builtin_type_docstrings = { |
|
55 | 55 | inspect.getdoc(t) for t in (types.ModuleType, types.MethodType, |
|
56 | 56 | types.FunctionType, property) |
|
57 | 57 | } |
|
58 | 58 | |
|
59 | 59 | _builtin_func_type = type(all) |
|
60 | 60 | _builtin_meth_type = type(str.upper) # Bound methods have the same type as builtin functions |
|
61 | 61 | #**************************************************************************** |
|
62 | 62 | # Builtin color schemes |
|
63 | 63 | |
|
64 | 64 | Colors = TermColors # just a shorthand |
|
65 | 65 | |
|
66 | 66 | InspectColors = PyColorize.ANSICodeColors |
|
67 | 67 | |
|
68 | 68 | #**************************************************************************** |
|
69 | 69 | # Auxiliary functions and objects |
|
70 | 70 | |
|
71 | 71 | # See the messaging spec for the definition of all these fields. This list |
|
72 | 72 | # effectively defines the order of display |
|
73 | 73 | info_fields = ['type_name', 'base_class', 'string_form', 'namespace', |
|
74 | 74 | 'length', 'file', 'definition', 'docstring', 'source', |
|
75 | 75 | 'init_definition', 'class_docstring', 'init_docstring', |
|
76 | 76 | 'call_def', 'call_docstring', |
|
77 | 77 | # These won't be printed but will be used to determine how to |
|
78 | 78 | # format the object |
|
79 |
'ismagic', 'isalias', 'isclass', ' |
|
|
79 | 'ismagic', 'isalias', 'isclass', 'found', 'name' | |
|
80 | 80 | ] |
|
81 | 81 | |
|
82 | 82 | |
|
83 | 83 | def object_info(**kw): |
|
84 | 84 | """Make an object info dict with all fields present.""" |
|
85 | 85 | infodict = dict(zip_longest(info_fields, [None])) |
|
86 | 86 | infodict.update(kw) |
|
87 | 87 | return infodict |
|
88 | 88 | |
|
89 | 89 | |
|
90 | 90 | def get_encoding(obj): |
|
91 | 91 | """Get encoding for python source file defining obj |
|
92 | 92 | |
|
93 | 93 | Returns None if obj is not defined in a sourcefile. |
|
94 | 94 | """ |
|
95 | 95 | ofile = find_file(obj) |
|
96 | 96 | # run contents of file through pager starting at line where the object |
|
97 | 97 | # is defined, as long as the file isn't binary and is actually on the |
|
98 | 98 | # filesystem. |
|
99 | 99 | if ofile is None: |
|
100 | 100 | return None |
|
101 | 101 | elif ofile.endswith(('.so', '.dll', '.pyd')): |
|
102 | 102 | return None |
|
103 | 103 | elif not os.path.isfile(ofile): |
|
104 | 104 | return None |
|
105 | 105 | else: |
|
106 | 106 | # Print only text files, not extension binaries. Note that |
|
107 | 107 | # getsourcelines returns lineno with 1-offset and page() uses |
|
108 | 108 | # 0-offset, so we must adjust. |
|
109 | 109 | with stdlib_io.open(ofile, 'rb') as buffer: # Tweaked to use io.open for Python 2 |
|
110 | 110 | encoding, lines = openpy.detect_encoding(buffer.readline) |
|
111 | 111 | return encoding |
|
112 | 112 | |
|
113 | 113 | def getdoc(obj): |
|
114 | 114 | """Stable wrapper around inspect.getdoc. |
|
115 | 115 | |
|
116 | 116 | This can't crash because of attribute problems. |
|
117 | 117 | |
|
118 | 118 | It also attempts to call a getdoc() method on the given object. This |
|
119 | 119 | allows objects which provide their docstrings via non-standard mechanisms |
|
120 | 120 | (like Pyro proxies) to still be inspected by ipython's ? system. |
|
121 | 121 | """ |
|
122 | 122 | # Allow objects to offer customized documentation via a getdoc method: |
|
123 | 123 | try: |
|
124 | 124 | ds = obj.getdoc() |
|
125 | 125 | except Exception: |
|
126 | 126 | pass |
|
127 | 127 | else: |
|
128 | 128 | if isinstance(ds, str): |
|
129 | 129 | return inspect.cleandoc(ds) |
|
130 | 130 | docstr = inspect.getdoc(obj) |
|
131 | 131 | encoding = get_encoding(obj) |
|
132 | 132 | return py3compat.cast_unicode(docstr, encoding=encoding) |
|
133 | 133 | |
|
134 | 134 | |
|
135 | 135 | def getsource(obj, oname=''): |
|
136 | 136 | """Wrapper around inspect.getsource. |
|
137 | 137 | |
|
138 | 138 | This can be modified by other projects to provide customized source |
|
139 | 139 | extraction. |
|
140 | 140 | |
|
141 | 141 | Parameters |
|
142 | 142 | ---------- |
|
143 | 143 | obj : object |
|
144 | 144 | an object whose source code we will attempt to extract |
|
145 | 145 | oname : str |
|
146 | 146 | (optional) a name under which the object is known |
|
147 | 147 | |
|
148 | 148 | Returns |
|
149 | 149 | ------- |
|
150 | 150 | src : unicode or None |
|
151 | 151 | |
|
152 | 152 | """ |
|
153 | 153 | |
|
154 | 154 | if isinstance(obj, property): |
|
155 | 155 | sources = [] |
|
156 | 156 | for attrname in ['fget', 'fset', 'fdel']: |
|
157 | 157 | fn = getattr(obj, attrname) |
|
158 | 158 | if fn is not None: |
|
159 | 159 | encoding = get_encoding(fn) |
|
160 | 160 | oname_prefix = ('%s.' % oname) if oname else '' |
|
161 | 161 | sources.append(cast_unicode( |
|
162 | 162 | ''.join(('# ', oname_prefix, attrname)), |
|
163 | 163 | encoding=encoding)) |
|
164 | 164 | if inspect.isfunction(fn): |
|
165 | 165 | sources.append(dedent(getsource(fn))) |
|
166 | 166 | else: |
|
167 | 167 | # Default str/repr only prints function name, |
|
168 | 168 | # pretty.pretty prints module name too. |
|
169 | 169 | sources.append(cast_unicode( |
|
170 | 170 | '%s%s = %s\n' % ( |
|
171 | 171 | oname_prefix, attrname, pretty(fn)), |
|
172 | 172 | encoding=encoding)) |
|
173 | 173 | if sources: |
|
174 | 174 | return '\n'.join(sources) |
|
175 | 175 | else: |
|
176 | 176 | return None |
|
177 | 177 | |
|
178 | 178 | else: |
|
179 | 179 | # Get source for non-property objects. |
|
180 | 180 | |
|
181 | 181 | obj = _get_wrapped(obj) |
|
182 | 182 | |
|
183 | 183 | try: |
|
184 | 184 | src = inspect.getsource(obj) |
|
185 | 185 | except TypeError: |
|
186 | 186 | # The object itself provided no meaningful source, try looking for |
|
187 | 187 | # its class definition instead. |
|
188 | 188 | if hasattr(obj, '__class__'): |
|
189 | 189 | try: |
|
190 | 190 | src = inspect.getsource(obj.__class__) |
|
191 | 191 | except TypeError: |
|
192 | 192 | return None |
|
193 | 193 | |
|
194 | 194 | encoding = get_encoding(obj) |
|
195 | 195 | return cast_unicode(src, encoding=encoding) |
|
196 | 196 | |
|
197 | 197 | |
|
198 | 198 | def is_simple_callable(obj): |
|
199 | 199 | """True if obj is a function ()""" |
|
200 | 200 | return (inspect.isfunction(obj) or inspect.ismethod(obj) or \ |
|
201 | 201 | isinstance(obj, _builtin_func_type) or isinstance(obj, _builtin_meth_type)) |
|
202 | 202 | |
|
203 | ||
|
203 | @undoc | |
|
204 | 204 | def getargspec(obj): |
|
205 | 205 | """Wrapper around :func:`inspect.getfullargspec` on Python 3, and |
|
206 | 206 | :func:inspect.getargspec` on Python 2. |
|
207 | 207 | |
|
208 | 208 | In addition to functions and methods, this can also handle objects with a |
|
209 | 209 | ``__call__`` attribute. |
|
210 | ||
|
211 | DEPRECATED: Deprecated since 7.10. Do not use, will be removed. | |
|
210 | 212 | """ |
|
213 | ||
|
214 | warnings.warn('`getargspec` function is deprecated as of IPython 7.10' | |
|
215 | 'and will be removed in future versions.', DeprecationWarning, stacklevel=2) | |
|
216 | ||
|
211 | 217 | if safe_hasattr(obj, '__call__') and not is_simple_callable(obj): |
|
212 | 218 | obj = obj.__call__ |
|
213 | 219 | |
|
214 | 220 | return inspect.getfullargspec(obj) |
|
215 | 221 | |
|
216 | ||
|
222 | @undoc | |
|
217 | 223 | def format_argspec(argspec): |
|
218 | 224 | """Format argspect, convenience wrapper around inspect's. |
|
219 | 225 | |
|
220 | 226 | This takes a dict instead of ordered arguments and calls |
|
221 | 227 | inspect.format_argspec with the arguments in the necessary order. |
|
228 | ||
|
229 | DEPRECATED: Do not use; will be removed in future versions. | |
|
222 | 230 | """ |
|
231 | ||
|
232 | warnings.warn('`format_argspec` function is deprecated as of IPython 7.10' | |
|
233 | 'and will be removed in future versions.', DeprecationWarning, stacklevel=2) | |
|
234 | ||
|
235 | ||
|
223 | 236 | return inspect.formatargspec(argspec['args'], argspec['varargs'], |
|
224 | 237 | argspec['varkw'], argspec['defaults']) |
|
225 | 238 | |
|
226 | 239 | @undoc |
|
227 | 240 | def call_tip(oinfo, format_call=True): |
|
228 | 241 | """DEPRECATED. Extract call tip data from an oinfo dict. |
|
229 | 242 | """ |
|
230 | 243 | warnings.warn('`call_tip` function is deprecated as of IPython 6.0' |
|
231 | 244 | 'and will be removed in future versions.', DeprecationWarning, stacklevel=2) |
|
232 | 245 | # Get call definition |
|
233 | 246 | argspec = oinfo.get('argspec') |
|
234 | 247 | if argspec is None: |
|
235 | 248 | call_line = None |
|
236 | 249 | else: |
|
237 | 250 | # Callable objects will have 'self' as their first argument, prune |
|
238 | 251 | # it out if it's there for clarity (since users do *not* pass an |
|
239 | 252 | # extra first argument explicitly). |
|
240 | 253 | try: |
|
241 | 254 | has_self = argspec['args'][0] == 'self' |
|
242 | 255 | except (KeyError, IndexError): |
|
243 | 256 | pass |
|
244 | 257 | else: |
|
245 | 258 | if has_self: |
|
246 | 259 | argspec['args'] = argspec['args'][1:] |
|
247 | 260 | |
|
248 | 261 | call_line = oinfo['name']+format_argspec(argspec) |
|
249 | 262 | |
|
250 | 263 | # Now get docstring. |
|
251 | 264 | # The priority is: call docstring, constructor docstring, main one. |
|
252 | 265 | doc = oinfo.get('call_docstring') |
|
253 | 266 | if doc is None: |
|
254 | 267 | doc = oinfo.get('init_docstring') |
|
255 | 268 | if doc is None: |
|
256 | 269 | doc = oinfo.get('docstring','') |
|
257 | 270 | |
|
258 | 271 | return call_line, doc |
|
259 | 272 | |
|
260 | 273 | |
|
261 | 274 | def _get_wrapped(obj): |
|
262 | 275 | """Get the original object if wrapped in one or more @decorators |
|
263 | 276 | |
|
264 | 277 | Some objects automatically construct similar objects on any unrecognised |
|
265 | 278 | attribute access (e.g. unittest.mock.call). To protect against infinite loops, |
|
266 | 279 | this will arbitrarily cut off after 100 levels of obj.__wrapped__ |
|
267 | 280 | attribute access. --TK, Jan 2016 |
|
268 | 281 | """ |
|
269 | 282 | orig_obj = obj |
|
270 | 283 | i = 0 |
|
271 | 284 | while safe_hasattr(obj, '__wrapped__'): |
|
272 | 285 | obj = obj.__wrapped__ |
|
273 | 286 | i += 1 |
|
274 | 287 | if i > 100: |
|
275 | 288 | # __wrapped__ is probably a lie, so return the thing we started with |
|
276 | 289 | return orig_obj |
|
277 | 290 | return obj |
|
278 | 291 | |
|
279 | 292 | def find_file(obj): |
|
280 | 293 | """Find the absolute path to the file where an object was defined. |
|
281 | 294 | |
|
282 | 295 | This is essentially a robust wrapper around `inspect.getabsfile`. |
|
283 | 296 | |
|
284 | 297 | Returns None if no file can be found. |
|
285 | 298 | |
|
286 | 299 | Parameters |
|
287 | 300 | ---------- |
|
288 | 301 | obj : any Python object |
|
289 | 302 | |
|
290 | 303 | Returns |
|
291 | 304 | ------- |
|
292 | 305 | fname : str |
|
293 | 306 | The absolute path to the file where the object was defined. |
|
294 | 307 | """ |
|
295 | 308 | obj = _get_wrapped(obj) |
|
296 | 309 | |
|
297 | 310 | fname = None |
|
298 | 311 | try: |
|
299 | 312 | fname = inspect.getabsfile(obj) |
|
300 | 313 | except TypeError: |
|
301 | 314 | # For an instance, the file that matters is where its class was |
|
302 | 315 | # declared. |
|
303 | 316 | if hasattr(obj, '__class__'): |
|
304 | 317 | try: |
|
305 | 318 | fname = inspect.getabsfile(obj.__class__) |
|
306 | 319 | except TypeError: |
|
307 | 320 | # Can happen for builtins |
|
308 | 321 | pass |
|
309 | 322 | except: |
|
310 | 323 | pass |
|
311 | 324 | return cast_unicode(fname) |
|
312 | 325 | |
|
313 | 326 | |
|
314 | 327 | def find_source_lines(obj): |
|
315 | 328 | """Find the line number in a file where an object was defined. |
|
316 | 329 | |
|
317 | 330 | This is essentially a robust wrapper around `inspect.getsourcelines`. |
|
318 | 331 | |
|
319 | 332 | Returns None if no file can be found. |
|
320 | 333 | |
|
321 | 334 | Parameters |
|
322 | 335 | ---------- |
|
323 | 336 | obj : any Python object |
|
324 | 337 | |
|
325 | 338 | Returns |
|
326 | 339 | ------- |
|
327 | 340 | lineno : int |
|
328 | 341 | The line number where the object definition starts. |
|
329 | 342 | """ |
|
330 | 343 | obj = _get_wrapped(obj) |
|
331 | 344 | |
|
332 | 345 | try: |
|
333 | 346 | try: |
|
334 | 347 | lineno = inspect.getsourcelines(obj)[1] |
|
335 | 348 | except TypeError: |
|
336 | 349 | # For instances, try the class object like getsource() does |
|
337 | 350 | if hasattr(obj, '__class__'): |
|
338 | 351 | lineno = inspect.getsourcelines(obj.__class__)[1] |
|
339 | 352 | else: |
|
340 | 353 | lineno = None |
|
341 | 354 | except: |
|
342 | 355 | return None |
|
343 | 356 | |
|
344 | 357 | return lineno |
|
345 | 358 | |
|
346 | 359 | class Inspector(Colorable): |
|
347 | 360 | |
|
348 | 361 | def __init__(self, color_table=InspectColors, |
|
349 | 362 | code_color_table=PyColorize.ANSICodeColors, |
|
350 | 363 | scheme=None, |
|
351 | 364 | str_detail_level=0, |
|
352 | 365 | parent=None, config=None): |
|
353 | 366 | super(Inspector, self).__init__(parent=parent, config=config) |
|
354 | 367 | self.color_table = color_table |
|
355 | 368 | self.parser = PyColorize.Parser(out='str', parent=self, style=scheme) |
|
356 | 369 | self.format = self.parser.format |
|
357 | 370 | self.str_detail_level = str_detail_level |
|
358 | 371 | self.set_active_scheme(scheme) |
|
359 | 372 | |
|
360 | 373 | def _getdef(self,obj,oname=''): |
|
361 | 374 | """Return the call signature for any callable object. |
|
362 | 375 | |
|
363 | 376 | If any exception is generated, None is returned instead and the |
|
364 | 377 | exception is suppressed.""" |
|
365 | 378 | try: |
|
366 | 379 | hdef = _render_signature(signature(obj), oname) |
|
367 | 380 | return cast_unicode(hdef) |
|
368 | 381 | except: |
|
369 | 382 | return None |
|
370 | 383 | |
|
371 | 384 | def __head(self,h): |
|
372 | 385 | """Return a header string with proper colors.""" |
|
373 | 386 | return '%s%s%s' % (self.color_table.active_colors.header,h, |
|
374 | 387 | self.color_table.active_colors.normal) |
|
375 | 388 | |
|
376 | 389 | def set_active_scheme(self, scheme): |
|
377 | 390 | if scheme is not None: |
|
378 | 391 | self.color_table.set_active_scheme(scheme) |
|
379 | 392 | self.parser.color_table.set_active_scheme(scheme) |
|
380 | 393 | |
|
381 | 394 | def noinfo(self, msg, oname): |
|
382 | 395 | """Generic message when no information is found.""" |
|
383 | 396 | print('No %s found' % msg, end=' ') |
|
384 | 397 | if oname: |
|
385 | 398 | print('for %s' % oname) |
|
386 | 399 | else: |
|
387 | 400 | print() |
|
388 | 401 | |
|
389 | 402 | def pdef(self, obj, oname=''): |
|
390 | 403 | """Print the call signature for any callable object. |
|
391 | 404 | |
|
392 | 405 | If the object is a class, print the constructor information.""" |
|
393 | 406 | |
|
394 | 407 | if not callable(obj): |
|
395 | 408 | print('Object is not callable.') |
|
396 | 409 | return |
|
397 | 410 | |
|
398 | 411 | header = '' |
|
399 | 412 | |
|
400 | 413 | if inspect.isclass(obj): |
|
401 | 414 | header = self.__head('Class constructor information:\n') |
|
402 | 415 | |
|
403 | 416 | |
|
404 | 417 | output = self._getdef(obj,oname) |
|
405 | 418 | if output is None: |
|
406 | 419 | self.noinfo('definition header',oname) |
|
407 | 420 | else: |
|
408 | 421 | print(header,self.format(output), end=' ') |
|
409 | 422 | |
|
410 | 423 | # In Python 3, all classes are new-style, so they all have __init__. |
|
411 | 424 | @skip_doctest |
|
412 | 425 | def pdoc(self, obj, oname='', formatter=None): |
|
413 | 426 | """Print the docstring for any object. |
|
414 | 427 | |
|
415 | 428 | Optional: |
|
416 | 429 | -formatter: a function to run the docstring through for specially |
|
417 | 430 | formatted docstrings. |
|
418 | 431 | |
|
419 | 432 | Examples |
|
420 | 433 | -------- |
|
421 | 434 | |
|
422 | 435 | In [1]: class NoInit: |
|
423 | 436 | ...: pass |
|
424 | 437 | |
|
425 | 438 | In [2]: class NoDoc: |
|
426 | 439 | ...: def __init__(self): |
|
427 | 440 | ...: pass |
|
428 | 441 | |
|
429 | 442 | In [3]: %pdoc NoDoc |
|
430 | 443 | No documentation found for NoDoc |
|
431 | 444 | |
|
432 | 445 | In [4]: %pdoc NoInit |
|
433 | 446 | No documentation found for NoInit |
|
434 | 447 | |
|
435 | 448 | In [5]: obj = NoInit() |
|
436 | 449 | |
|
437 | 450 | In [6]: %pdoc obj |
|
438 | 451 | No documentation found for obj |
|
439 | 452 | |
|
440 | 453 | In [5]: obj2 = NoDoc() |
|
441 | 454 | |
|
442 | 455 | In [6]: %pdoc obj2 |
|
443 | 456 | No documentation found for obj2 |
|
444 | 457 | """ |
|
445 | 458 | |
|
446 | 459 | head = self.__head # For convenience |
|
447 | 460 | lines = [] |
|
448 | 461 | ds = getdoc(obj) |
|
449 | 462 | if formatter: |
|
450 | 463 | ds = formatter(ds).get('plain/text', ds) |
|
451 | 464 | if ds: |
|
452 | 465 | lines.append(head("Class docstring:")) |
|
453 | 466 | lines.append(indent(ds)) |
|
454 | 467 | if inspect.isclass(obj) and hasattr(obj, '__init__'): |
|
455 | 468 | init_ds = getdoc(obj.__init__) |
|
456 | 469 | if init_ds is not None: |
|
457 | 470 | lines.append(head("Init docstring:")) |
|
458 | 471 | lines.append(indent(init_ds)) |
|
459 | 472 | elif hasattr(obj,'__call__'): |
|
460 | 473 | call_ds = getdoc(obj.__call__) |
|
461 | 474 | if call_ds: |
|
462 | 475 | lines.append(head("Call docstring:")) |
|
463 | 476 | lines.append(indent(call_ds)) |
|
464 | 477 | |
|
465 | 478 | if not lines: |
|
466 | 479 | self.noinfo('documentation',oname) |
|
467 | 480 | else: |
|
468 | 481 | page.page('\n'.join(lines)) |
|
469 | 482 | |
|
470 | 483 | def psource(self, obj, oname=''): |
|
471 | 484 | """Print the source code for an object.""" |
|
472 | 485 | |
|
473 | 486 | # Flush the source cache because inspect can return out-of-date source |
|
474 | 487 | linecache.checkcache() |
|
475 | 488 | try: |
|
476 | 489 | src = getsource(obj, oname=oname) |
|
477 | 490 | except Exception: |
|
478 | 491 | src = None |
|
479 | 492 | |
|
480 | 493 | if src is None: |
|
481 | 494 | self.noinfo('source', oname) |
|
482 | 495 | else: |
|
483 | 496 | page.page(self.format(src)) |
|
484 | 497 | |
|
485 | 498 | def pfile(self, obj, oname=''): |
|
486 | 499 | """Show the whole file where an object was defined.""" |
|
487 | 500 | |
|
488 | 501 | lineno = find_source_lines(obj) |
|
489 | 502 | if lineno is None: |
|
490 | 503 | self.noinfo('file', oname) |
|
491 | 504 | return |
|
492 | 505 | |
|
493 | 506 | ofile = find_file(obj) |
|
494 | 507 | # run contents of file through pager starting at line where the object |
|
495 | 508 | # is defined, as long as the file isn't binary and is actually on the |
|
496 | 509 | # filesystem. |
|
497 | 510 | if ofile.endswith(('.so', '.dll', '.pyd')): |
|
498 | 511 | print('File %r is binary, not printing.' % ofile) |
|
499 | 512 | elif not os.path.isfile(ofile): |
|
500 | 513 | print('File %r does not exist, not printing.' % ofile) |
|
501 | 514 | else: |
|
502 | 515 | # Print only text files, not extension binaries. Note that |
|
503 | 516 | # getsourcelines returns lineno with 1-offset and page() uses |
|
504 | 517 | # 0-offset, so we must adjust. |
|
505 | 518 | page.page(self.format(openpy.read_py_file(ofile, skip_encoding_cookie=False)), lineno - 1) |
|
506 | 519 | |
|
507 | 520 | def _format_fields(self, fields, title_width=0): |
|
508 | 521 | """Formats a list of fields for display. |
|
509 | 522 | |
|
510 | 523 | Parameters |
|
511 | 524 | ---------- |
|
512 | 525 | fields : list |
|
513 | 526 | A list of 2-tuples: (field_title, field_content) |
|
514 | 527 | title_width : int |
|
515 | 528 | How many characters to pad titles to. Default to longest title. |
|
516 | 529 | """ |
|
517 | 530 | out = [] |
|
518 | 531 | header = self.__head |
|
519 | 532 | if title_width == 0: |
|
520 | 533 | title_width = max(len(title) + 2 for title, _ in fields) |
|
521 | 534 | for title, content in fields: |
|
522 | 535 | if len(content.splitlines()) > 1: |
|
523 | 536 | title = header(title + ':') + '\n' |
|
524 | 537 | else: |
|
525 | 538 | title = header((title + ':').ljust(title_width)) |
|
526 | 539 | out.append(cast_unicode(title) + cast_unicode(content)) |
|
527 | 540 | return "\n".join(out) |
|
528 | 541 | |
|
529 | 542 | def _mime_format(self, text, formatter=None): |
|
530 | 543 | """Return a mime bundle representation of the input text. |
|
531 | 544 | |
|
532 | 545 | - if `formatter` is None, the returned mime bundle has |
|
533 | 546 | a `text/plain` field, with the input text. |
|
534 | 547 | a `text/html` field with a `<pre>` tag containing the input text. |
|
535 | 548 | |
|
536 | 549 | - if `formatter` is not None, it must be a callable transforming the |
|
537 | 550 | input text into a mime bundle. Default values for `text/plain` and |
|
538 | 551 | `text/html` representations are the ones described above. |
|
539 | 552 | |
|
540 | 553 | Note: |
|
541 | 554 | |
|
542 | 555 | Formatters returning strings are supported but this behavior is deprecated. |
|
543 | 556 | |
|
544 | 557 | """ |
|
545 | 558 | text = cast_unicode(text) |
|
546 | 559 | defaults = { |
|
547 | 560 | 'text/plain': text, |
|
548 | 561 | 'text/html': '<pre>' + text + '</pre>' |
|
549 | 562 | } |
|
550 | 563 | |
|
551 | 564 | if formatter is None: |
|
552 | 565 | return defaults |
|
553 | 566 | else: |
|
554 | 567 | formatted = formatter(text) |
|
555 | 568 | |
|
556 | 569 | if not isinstance(formatted, dict): |
|
557 | 570 | # Handle the deprecated behavior of a formatter returning |
|
558 | 571 | # a string instead of a mime bundle. |
|
559 | 572 | return { |
|
560 | 573 | 'text/plain': formatted, |
|
561 | 574 | 'text/html': '<pre>' + formatted + '</pre>' |
|
562 | 575 | } |
|
563 | 576 | |
|
564 | 577 | else: |
|
565 | 578 | return dict(defaults, **formatted) |
|
566 | 579 | |
|
567 | 580 | |
|
568 | 581 | def format_mime(self, bundle): |
|
569 | 582 | |
|
570 | 583 | text_plain = bundle['text/plain'] |
|
571 | 584 | |
|
572 | 585 | text = '' |
|
573 | 586 | heads, bodies = list(zip(*text_plain)) |
|
574 | 587 | _len = max(len(h) for h in heads) |
|
575 | 588 | |
|
576 | 589 | for head, body in zip(heads, bodies): |
|
577 | 590 | body = body.strip('\n') |
|
578 | 591 | delim = '\n' if '\n' in body else ' ' |
|
579 | 592 | text += self.__head(head+':') + (_len - len(head))*' ' +delim + body +'\n' |
|
580 | 593 | |
|
581 | 594 | bundle['text/plain'] = text |
|
582 | 595 | return bundle |
|
583 | 596 | |
|
584 | 597 | def _get_info(self, obj, oname='', formatter=None, info=None, detail_level=0): |
|
585 | 598 | """Retrieve an info dict and format it. |
|
586 | 599 | |
|
587 | 600 | Parameters |
|
588 | 601 | ========== |
|
589 | 602 | |
|
590 | 603 | obj: any |
|
591 | 604 | Object to inspect and return info from |
|
592 | 605 | oname: str (default: ''): |
|
593 | 606 | Name of the variable pointing to `obj`. |
|
594 | 607 | formatter: callable |
|
595 | 608 | info: |
|
596 | 609 | already computed information |
|
597 | 610 | detail_level: integer |
|
598 | 611 | Granularity of detail level, if set to 1, give more information. |
|
599 | 612 | """ |
|
600 | 613 | |
|
601 | 614 | info = self._info(obj, oname=oname, info=info, detail_level=detail_level) |
|
602 | 615 | |
|
603 | 616 | _mime = { |
|
604 | 617 | 'text/plain': [], |
|
605 | 618 | 'text/html': '', |
|
606 | 619 | } |
|
607 | 620 | |
|
608 | 621 | def append_field(bundle, title, key, formatter=None): |
|
609 | 622 | field = info[key] |
|
610 | 623 | if field is not None: |
|
611 | 624 | formatted_field = self._mime_format(field, formatter) |
|
612 | 625 | bundle['text/plain'].append((title, formatted_field['text/plain'])) |
|
613 | 626 | bundle['text/html'] += '<h1>' + title + '</h1>\n' + formatted_field['text/html'] + '\n' |
|
614 | 627 | |
|
615 | 628 | def code_formatter(text): |
|
616 | 629 | return { |
|
617 | 630 | 'text/plain': self.format(text), |
|
618 | 631 | 'text/html': pylight(text) |
|
619 | 632 | } |
|
620 | 633 | |
|
621 | 634 | if info['isalias']: |
|
622 | 635 | append_field(_mime, 'Repr', 'string_form') |
|
623 | 636 | |
|
624 | 637 | elif info['ismagic']: |
|
625 | 638 | if detail_level > 0: |
|
626 | 639 | append_field(_mime, 'Source', 'source', code_formatter) |
|
627 | 640 | else: |
|
628 | 641 | append_field(_mime, 'Docstring', 'docstring', formatter) |
|
629 | 642 | append_field(_mime, 'File', 'file') |
|
630 | 643 | |
|
631 | 644 | elif info['isclass'] or is_simple_callable(obj): |
|
632 | 645 | # Functions, methods, classes |
|
633 | 646 | append_field(_mime, 'Signature', 'definition', code_formatter) |
|
634 | 647 | append_field(_mime, 'Init signature', 'init_definition', code_formatter) |
|
635 | 648 | append_field(_mime, 'Docstring', 'docstring', formatter) |
|
636 | 649 | if detail_level > 0 and info['source']: |
|
637 | 650 | append_field(_mime, 'Source', 'source', code_formatter) |
|
638 | 651 | else: |
|
639 | 652 | append_field(_mime, 'Init docstring', 'init_docstring', formatter) |
|
640 | 653 | |
|
641 | 654 | append_field(_mime, 'File', 'file') |
|
642 | 655 | append_field(_mime, 'Type', 'type_name') |
|
643 | 656 | append_field(_mime, 'Subclasses', 'subclasses') |
|
644 | 657 | |
|
645 | 658 | else: |
|
646 | 659 | # General Python objects |
|
647 | 660 | append_field(_mime, 'Signature', 'definition', code_formatter) |
|
648 | 661 | append_field(_mime, 'Call signature', 'call_def', code_formatter) |
|
649 | 662 | append_field(_mime, 'Type', 'type_name') |
|
650 | 663 | append_field(_mime, 'String form', 'string_form') |
|
651 | 664 | |
|
652 | 665 | # Namespace |
|
653 | 666 | if info['namespace'] != 'Interactive': |
|
654 | 667 | append_field(_mime, 'Namespace', 'namespace') |
|
655 | 668 | |
|
656 | 669 | append_field(_mime, 'Length', 'length') |
|
657 | 670 | append_field(_mime, 'File', 'file') |
|
658 | 671 | |
|
659 | 672 | # Source or docstring, depending on detail level and whether |
|
660 | 673 | # source found. |
|
661 | 674 | if detail_level > 0 and info['source']: |
|
662 | 675 | append_field(_mime, 'Source', 'source', code_formatter) |
|
663 | 676 | else: |
|
664 | 677 | append_field(_mime, 'Docstring', 'docstring', formatter) |
|
665 | 678 | |
|
666 | 679 | append_field(_mime, 'Class docstring', 'class_docstring', formatter) |
|
667 | 680 | append_field(_mime, 'Init docstring', 'init_docstring', formatter) |
|
668 | 681 | append_field(_mime, 'Call docstring', 'call_docstring', formatter) |
|
669 | 682 | |
|
670 | 683 | |
|
671 | 684 | return self.format_mime(_mime) |
|
672 | 685 | |
|
673 | 686 | def pinfo(self, obj, oname='', formatter=None, info=None, detail_level=0, enable_html_pager=True): |
|
674 | 687 | """Show detailed information about an object. |
|
675 | 688 | |
|
676 | 689 | Optional arguments: |
|
677 | 690 | |
|
678 | 691 | - oname: name of the variable pointing to the object. |
|
679 | 692 | |
|
680 | 693 | - formatter: callable (optional) |
|
681 | 694 | A special formatter for docstrings. |
|
682 | 695 | |
|
683 | 696 | The formatter is a callable that takes a string as an input |
|
684 | 697 | and returns either a formatted string or a mime type bundle |
|
685 | 698 | in the form of a dictionary. |
|
686 | 699 | |
|
687 | 700 | Although the support of custom formatter returning a string |
|
688 | 701 | instead of a mime type bundle is deprecated. |
|
689 | 702 | |
|
690 | 703 | - info: a structure with some information fields which may have been |
|
691 | 704 | precomputed already. |
|
692 | 705 | |
|
693 | 706 | - detail_level: if set to 1, more information is given. |
|
694 | 707 | """ |
|
695 | 708 | info = self._get_info(obj, oname, formatter, info, detail_level) |
|
696 | 709 | if not enable_html_pager: |
|
697 | 710 | del info['text/html'] |
|
698 | 711 | page.page(info) |
|
699 | 712 | |
|
700 | 713 | def info(self, obj, oname='', formatter=None, info=None, detail_level=0): |
|
701 | 714 | """DEPRECATED. Compute a dict with detailed information about an object. |
|
702 | 715 | """ |
|
703 | 716 | if formatter is not None: |
|
704 | 717 | warnings.warn('The `formatter` keyword argument to `Inspector.info`' |
|
705 | 718 | 'is deprecated as of IPython 5.0 and will have no effects.', |
|
706 | 719 | DeprecationWarning, stacklevel=2) |
|
707 | 720 | return self._info(obj, oname=oname, info=info, detail_level=detail_level) |
|
708 | 721 | |
|
709 | 722 | def _info(self, obj, oname='', info=None, detail_level=0) -> dict: |
|
710 | 723 | """Compute a dict with detailed information about an object. |
|
711 | 724 | |
|
712 | 725 | Parameters |
|
713 | 726 | ========== |
|
714 | 727 | |
|
715 | 728 | obj: any |
|
716 | 729 | An object to find information about |
|
717 | 730 | oname: str (default: ''): |
|
718 | 731 | Name of the variable pointing to `obj`. |
|
719 | 732 | info: (default: None) |
|
720 | 733 | A struct (dict like with attr access) with some information fields |
|
721 | 734 | which may have been precomputed already. |
|
722 | 735 | detail_level: int (default:0) |
|
723 | 736 | If set to 1, more information is given. |
|
724 | 737 | |
|
725 | 738 | Returns |
|
726 | 739 | ======= |
|
727 | 740 | |
|
728 | 741 | An object info dict with known fields from `info_fields`. |
|
729 | 742 | """ |
|
730 | 743 | |
|
731 | 744 | if info is None: |
|
732 | 745 | ismagic = False |
|
733 | 746 | isalias = False |
|
734 | 747 | ospace = '' |
|
735 | 748 | else: |
|
736 | 749 | ismagic = info.ismagic |
|
737 | 750 | isalias = info.isalias |
|
738 | 751 | ospace = info.namespace |
|
739 | 752 | |
|
740 | 753 | # Get docstring, special-casing aliases: |
|
741 | 754 | if isalias: |
|
742 | 755 | if not callable(obj): |
|
743 | 756 | try: |
|
744 | 757 | ds = "Alias to the system command:\n %s" % obj[1] |
|
745 | 758 | except: |
|
746 | 759 | ds = "Alias: " + str(obj) |
|
747 | 760 | else: |
|
748 | 761 | ds = "Alias to " + str(obj) |
|
749 | 762 | if obj.__doc__: |
|
750 | 763 | ds += "\nDocstring:\n" + obj.__doc__ |
|
751 | 764 | else: |
|
752 | 765 | ds = getdoc(obj) |
|
753 | 766 | if ds is None: |
|
754 | 767 | ds = '<no docstring>' |
|
755 | 768 | |
|
756 | 769 | # store output in a dict, we initialize it here and fill it as we go |
|
757 | 770 | out = dict(name=oname, found=True, isalias=isalias, ismagic=ismagic, subclasses=None) |
|
758 | 771 | |
|
759 | 772 | string_max = 200 # max size of strings to show (snipped if longer) |
|
760 | 773 | shalf = int((string_max - 5) / 2) |
|
761 | 774 | |
|
762 | 775 | if ismagic: |
|
763 | 776 | out['type_name'] = 'Magic function' |
|
764 | 777 | elif isalias: |
|
765 | 778 | out['type_name'] = 'System alias' |
|
766 | 779 | else: |
|
767 | 780 | out['type_name'] = type(obj).__name__ |
|
768 | 781 | |
|
769 | 782 | try: |
|
770 | 783 | bclass = obj.__class__ |
|
771 | 784 | out['base_class'] = str(bclass) |
|
772 | 785 | except: |
|
773 | 786 | pass |
|
774 | 787 | |
|
775 | 788 | # String form, but snip if too long in ? form (full in ??) |
|
776 | 789 | if detail_level >= self.str_detail_level: |
|
777 | 790 | try: |
|
778 | 791 | ostr = str(obj) |
|
779 | 792 | str_head = 'string_form' |
|
780 | 793 | if not detail_level and len(ostr)>string_max: |
|
781 | 794 | ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:] |
|
782 | 795 | ostr = ("\n" + " " * len(str_head.expandtabs())).\ |
|
783 | 796 | join(q.strip() for q in ostr.split("\n")) |
|
784 | 797 | out[str_head] = ostr |
|
785 | 798 | except: |
|
786 | 799 | pass |
|
787 | 800 | |
|
788 | 801 | if ospace: |
|
789 | 802 | out['namespace'] = ospace |
|
790 | 803 | |
|
791 | 804 | # Length (for strings and lists) |
|
792 | 805 | try: |
|
793 | 806 | out['length'] = str(len(obj)) |
|
794 | 807 | except Exception: |
|
795 | 808 | pass |
|
796 | 809 | |
|
797 | 810 | # Filename where object was defined |
|
798 | 811 | binary_file = False |
|
799 | 812 | fname = find_file(obj) |
|
800 | 813 | if fname is None: |
|
801 | 814 | # if anything goes wrong, we don't want to show source, so it's as |
|
802 | 815 | # if the file was binary |
|
803 | 816 | binary_file = True |
|
804 | 817 | else: |
|
805 | 818 | if fname.endswith(('.so', '.dll', '.pyd')): |
|
806 | 819 | binary_file = True |
|
807 | 820 | elif fname.endswith('<string>'): |
|
808 | 821 | fname = 'Dynamically generated function. No source code available.' |
|
809 | 822 | out['file'] = compress_user(fname) |
|
810 | 823 | |
|
811 | 824 | # Original source code for a callable, class or property. |
|
812 | 825 | if detail_level: |
|
813 | 826 | # Flush the source cache because inspect can return out-of-date |
|
814 | 827 | # source |
|
815 | 828 | linecache.checkcache() |
|
816 | 829 | try: |
|
817 | 830 | if isinstance(obj, property) or not binary_file: |
|
818 | 831 | src = getsource(obj, oname) |
|
819 | 832 | if src is not None: |
|
820 | 833 | src = src.rstrip() |
|
821 | 834 | out['source'] = src |
|
822 | 835 | |
|
823 | 836 | except Exception: |
|
824 | 837 | pass |
|
825 | 838 | |
|
826 | 839 | # Add docstring only if no source is to be shown (avoid repetitions). |
|
827 | 840 | if ds and not self._source_contains_docstring(out.get('source'), ds): |
|
828 | 841 | out['docstring'] = ds |
|
829 | 842 | |
|
830 | 843 | # Constructor docstring for classes |
|
831 | 844 | if inspect.isclass(obj): |
|
832 | 845 | out['isclass'] = True |
|
833 | 846 | |
|
834 | 847 | # get the init signature: |
|
835 | 848 | try: |
|
836 | 849 | init_def = self._getdef(obj, oname) |
|
837 | 850 | except AttributeError: |
|
838 | 851 | init_def = None |
|
839 | 852 | |
|
840 | 853 | # get the __init__ docstring |
|
841 | 854 | try: |
|
842 | 855 | obj_init = obj.__init__ |
|
843 | 856 | except AttributeError: |
|
844 | 857 | init_ds = None |
|
845 | 858 | else: |
|
846 | 859 | if init_def is None: |
|
847 | 860 | # Get signature from init if top-level sig failed. |
|
848 | 861 | # Can happen for built-in types (list, etc.). |
|
849 | 862 | try: |
|
850 | 863 | init_def = self._getdef(obj_init, oname) |
|
851 | 864 | except AttributeError: |
|
852 | 865 | pass |
|
853 | 866 | init_ds = getdoc(obj_init) |
|
854 | 867 | # Skip Python's auto-generated docstrings |
|
855 | 868 | if init_ds == _object_init_docstring: |
|
856 | 869 | init_ds = None |
|
857 | 870 | |
|
858 | 871 | if init_def: |
|
859 | 872 | out['init_definition'] = init_def |
|
860 | 873 | |
|
861 | 874 | if init_ds: |
|
862 | 875 | out['init_docstring'] = init_ds |
|
863 | 876 | |
|
864 | 877 | names = [sub.__name__ for sub in type.__subclasses__(obj)] |
|
865 | 878 | if len(names) < 10: |
|
866 | 879 | all_names = ', '.join(names) |
|
867 | 880 | else: |
|
868 | 881 | all_names = ', '.join(names[:10]+['...']) |
|
869 | 882 | out['subclasses'] = all_names |
|
870 | 883 | # and class docstring for instances: |
|
871 | 884 | else: |
|
872 | 885 | # reconstruct the function definition and print it: |
|
873 | 886 | defln = self._getdef(obj, oname) |
|
874 | 887 | if defln: |
|
875 | 888 | out['definition'] = defln |
|
876 | 889 | |
|
877 | 890 | # First, check whether the instance docstring is identical to the |
|
878 | 891 | # class one, and print it separately if they don't coincide. In |
|
879 | 892 | # most cases they will, but it's nice to print all the info for |
|
880 | 893 | # objects which use instance-customized docstrings. |
|
881 | 894 | if ds: |
|
882 | 895 | try: |
|
883 | 896 | cls = getattr(obj,'__class__') |
|
884 | 897 | except: |
|
885 | 898 | class_ds = None |
|
886 | 899 | else: |
|
887 | 900 | class_ds = getdoc(cls) |
|
888 | 901 | # Skip Python's auto-generated docstrings |
|
889 | 902 | if class_ds in _builtin_type_docstrings: |
|
890 | 903 | class_ds = None |
|
891 | 904 | if class_ds and ds != class_ds: |
|
892 | 905 | out['class_docstring'] = class_ds |
|
893 | 906 | |
|
894 | 907 | # Next, try to show constructor docstrings |
|
895 | 908 | try: |
|
896 | 909 | init_ds = getdoc(obj.__init__) |
|
897 | 910 | # Skip Python's auto-generated docstrings |
|
898 | 911 | if init_ds == _object_init_docstring: |
|
899 | 912 | init_ds = None |
|
900 | 913 | except AttributeError: |
|
901 | 914 | init_ds = None |
|
902 | 915 | if init_ds: |
|
903 | 916 | out['init_docstring'] = init_ds |
|
904 | 917 | |
|
905 | 918 | # Call form docstring for callable instances |
|
906 | 919 | if safe_hasattr(obj, '__call__') and not is_simple_callable(obj): |
|
907 | 920 | call_def = self._getdef(obj.__call__, oname) |
|
908 | 921 | if call_def and (call_def != out.get('definition')): |
|
909 | 922 | # it may never be the case that call def and definition differ, |
|
910 | 923 | # but don't include the same signature twice |
|
911 | 924 | out['call_def'] = call_def |
|
912 | 925 | call_ds = getdoc(obj.__call__) |
|
913 | 926 | # Skip Python's auto-generated docstrings |
|
914 | 927 | if call_ds == _func_call_docstring: |
|
915 | 928 | call_ds = None |
|
916 | 929 | if call_ds: |
|
917 | 930 | out['call_docstring'] = call_ds |
|
918 | 931 | |
|
919 | # Compute the object's argspec as a callable. The key is to decide | |
|
920 | # whether to pull it from the object itself, from its __init__ or | |
|
921 | # from its __call__ method. | |
|
922 | ||
|
923 | if inspect.isclass(obj): | |
|
924 | # Old-style classes need not have an __init__ | |
|
925 | callable_obj = getattr(obj, "__init__", None) | |
|
926 | elif callable(obj): | |
|
927 | callable_obj = obj | |
|
928 | else: | |
|
929 | callable_obj = None | |
|
930 | ||
|
931 | if callable_obj is not None: | |
|
932 | try: | |
|
933 | argspec = getargspec(callable_obj) | |
|
934 | except Exception: | |
|
935 | # For extensions/builtins we can't retrieve the argspec | |
|
936 | pass | |
|
937 | else: | |
|
938 | # named tuples' _asdict() method returns an OrderedDict, but we | |
|
939 | # we want a normal | |
|
940 | out['argspec'] = argspec_dict = dict(argspec._asdict()) | |
|
941 | # We called this varkw before argspec became a named tuple. | |
|
942 | # With getfullargspec it's also called varkw. | |
|
943 | if 'varkw' not in argspec_dict: | |
|
944 | argspec_dict['varkw'] = argspec_dict.pop('keywords') | |
|
945 | ||
|
946 | 932 | return object_info(**out) |
|
947 | 933 | |
|
948 | 934 | @staticmethod |
|
949 | 935 | def _source_contains_docstring(src, doc): |
|
950 | 936 | """ |
|
951 | 937 | Check whether the source *src* contains the docstring *doc*. |
|
952 | 938 | |
|
953 | 939 | This is is helper function to skip displaying the docstring if the |
|
954 | 940 | source already contains it, avoiding repetition of information. |
|
955 | 941 | """ |
|
956 | 942 | try: |
|
957 | 943 | def_node, = ast.parse(dedent(src)).body |
|
958 | 944 | return ast.get_docstring(def_node) == doc |
|
959 | 945 | except Exception: |
|
960 | 946 | # The source can become invalid or even non-existent (because it |
|
961 | 947 | # is re-fetched from the source file) so the above code fail in |
|
962 | 948 | # arbitrary ways. |
|
963 | 949 | return False |
|
964 | 950 | |
|
965 | 951 | def psearch(self,pattern,ns_table,ns_search=[], |
|
966 | 952 | ignore_case=False,show_all=False, *, list_types=False): |
|
967 | 953 | """Search namespaces with wildcards for objects. |
|
968 | 954 | |
|
969 | 955 | Arguments: |
|
970 | 956 | |
|
971 | 957 | - pattern: string containing shell-like wildcards to use in namespace |
|
972 | 958 | searches and optionally a type specification to narrow the search to |
|
973 | 959 | objects of that type. |
|
974 | 960 | |
|
975 | 961 | - ns_table: dict of name->namespaces for search. |
|
976 | 962 | |
|
977 | 963 | Optional arguments: |
|
978 | 964 | |
|
979 | 965 | - ns_search: list of namespace names to include in search. |
|
980 | 966 | |
|
981 | 967 | - ignore_case(False): make the search case-insensitive. |
|
982 | 968 | |
|
983 | 969 | - show_all(False): show all names, including those starting with |
|
984 | 970 | underscores. |
|
985 | 971 | |
|
986 | 972 | - list_types(False): list all available object types for object matching. |
|
987 | 973 | """ |
|
988 | 974 | #print 'ps pattern:<%r>' % pattern # dbg |
|
989 | 975 | |
|
990 | 976 | # defaults |
|
991 | 977 | type_pattern = 'all' |
|
992 | 978 | filter = '' |
|
993 | 979 | |
|
994 | 980 | # list all object types |
|
995 | 981 | if list_types: |
|
996 | 982 | page.page('\n'.join(sorted(typestr2type))) |
|
997 | 983 | return |
|
998 | 984 | |
|
999 | 985 | cmds = pattern.split() |
|
1000 | 986 | len_cmds = len(cmds) |
|
1001 | 987 | if len_cmds == 1: |
|
1002 | 988 | # Only filter pattern given |
|
1003 | 989 | filter = cmds[0] |
|
1004 | 990 | elif len_cmds == 2: |
|
1005 | 991 | # Both filter and type specified |
|
1006 | 992 | filter,type_pattern = cmds |
|
1007 | 993 | else: |
|
1008 | 994 | raise ValueError('invalid argument string for psearch: <%s>' % |
|
1009 | 995 | pattern) |
|
1010 | 996 | |
|
1011 | 997 | # filter search namespaces |
|
1012 | 998 | for name in ns_search: |
|
1013 | 999 | if name not in ns_table: |
|
1014 | 1000 | raise ValueError('invalid namespace <%s>. Valid names: %s' % |
|
1015 | 1001 | (name,ns_table.keys())) |
|
1016 | 1002 | |
|
1017 | 1003 | #print 'type_pattern:',type_pattern # dbg |
|
1018 | 1004 | search_result, namespaces_seen = set(), set() |
|
1019 | 1005 | for ns_name in ns_search: |
|
1020 | 1006 | ns = ns_table[ns_name] |
|
1021 | 1007 | # Normally, locals and globals are the same, so we just check one. |
|
1022 | 1008 | if id(ns) in namespaces_seen: |
|
1023 | 1009 | continue |
|
1024 | 1010 | namespaces_seen.add(id(ns)) |
|
1025 | 1011 | tmp_res = list_namespace(ns, type_pattern, filter, |
|
1026 | 1012 | ignore_case=ignore_case, show_all=show_all) |
|
1027 | 1013 | search_result.update(tmp_res) |
|
1028 | 1014 | |
|
1029 | 1015 | page.page('\n'.join(sorted(search_result))) |
|
1030 | 1016 | |
|
1031 | 1017 | |
|
1032 | 1018 | def _render_signature(obj_signature, obj_name): |
|
1033 | 1019 | """ |
|
1034 | 1020 | This was mostly taken from inspect.Signature.__str__. |
|
1035 | 1021 | Look there for the comments. |
|
1036 | 1022 | The only change is to add linebreaks when this gets too long. |
|
1037 | 1023 | """ |
|
1038 | 1024 | result = [] |
|
1039 | 1025 | pos_only = False |
|
1040 | 1026 | kw_only = True |
|
1041 | 1027 | for param in obj_signature.parameters.values(): |
|
1042 | 1028 | if param.kind == inspect._POSITIONAL_ONLY: |
|
1043 | 1029 | pos_only = True |
|
1044 | 1030 | elif pos_only: |
|
1045 | 1031 | result.append('/') |
|
1046 | 1032 | pos_only = False |
|
1047 | 1033 | |
|
1048 | 1034 | if param.kind == inspect._VAR_POSITIONAL: |
|
1049 | 1035 | kw_only = False |
|
1050 | 1036 | elif param.kind == inspect._KEYWORD_ONLY and kw_only: |
|
1051 | 1037 | result.append('*') |
|
1052 | 1038 | kw_only = False |
|
1053 | 1039 | |
|
1054 | 1040 | result.append(str(param)) |
|
1055 | 1041 | |
|
1056 | 1042 | if pos_only: |
|
1057 | 1043 | result.append('/') |
|
1058 | 1044 | |
|
1059 | 1045 | # add up name, parameters, braces (2), and commas |
|
1060 | 1046 | if len(obj_name) + sum(len(r) + 2 for r in result) > 75: |
|
1061 | 1047 | # This doesn’t fit behind “Signature: ” in an inspect window. |
|
1062 | 1048 | rendered = '{}(\n{})'.format(obj_name, ''.join( |
|
1063 | 1049 | ' {},\n'.format(r) for r in result) |
|
1064 | 1050 | ) |
|
1065 | 1051 | else: |
|
1066 | 1052 | rendered = '{}({})'.format(obj_name, ', '.join(result)) |
|
1067 | 1053 | |
|
1068 | 1054 | if obj_signature.return_annotation is not inspect._empty: |
|
1069 | 1055 | anno = inspect.formatannotation(obj_signature.return_annotation) |
|
1070 | 1056 | rendered += ' -> {}'.format(anno) |
|
1071 | 1057 | |
|
1072 | 1058 | return rendered |
@@ -1,366 +1,372 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """ |
|
3 | 3 | Paging capabilities for IPython.core |
|
4 | 4 | |
|
5 | 5 | Notes |
|
6 | 6 | ----- |
|
7 | 7 | |
|
8 | 8 | For now this uses IPython hooks, so it can't be in IPython.utils. If we can get |
|
9 | 9 | rid of that dependency, we could move it there. |
|
10 | 10 | ----- |
|
11 | 11 | """ |
|
12 | 12 | |
|
13 | 13 | # Copyright (c) IPython Development Team. |
|
14 | 14 | # Distributed under the terms of the Modified BSD License. |
|
15 | 15 | |
|
16 | 16 | |
|
17 | 17 | import os |
|
18 | import io | |
|
18 | 19 | import re |
|
19 | 20 | import sys |
|
20 | 21 | import tempfile |
|
22 | import subprocess | |
|
21 | 23 | |
|
22 | 24 | from io import UnsupportedOperation |
|
23 | 25 | |
|
24 | 26 | from IPython import get_ipython |
|
25 | 27 | from IPython.core.display import display |
|
26 | 28 | from IPython.core.error import TryNext |
|
27 | 29 | from IPython.utils.data import chop |
|
28 | 30 | from IPython.utils.process import system |
|
29 | 31 | from IPython.utils.terminal import get_terminal_size |
|
30 | 32 | from IPython.utils import py3compat |
|
31 | 33 | |
|
32 | 34 | |
|
33 | 35 | def display_page(strng, start=0, screen_lines=25): |
|
34 | 36 | """Just display, no paging. screen_lines is ignored.""" |
|
35 | 37 | if isinstance(strng, dict): |
|
36 | 38 | data = strng |
|
37 | 39 | else: |
|
38 | 40 | if start: |
|
39 | 41 | strng = u'\n'.join(strng.splitlines()[start:]) |
|
40 | 42 | data = { 'text/plain': strng } |
|
41 | 43 | display(data, raw=True) |
|
42 | 44 | |
|
43 | 45 | |
|
44 | 46 | def as_hook(page_func): |
|
45 | 47 | """Wrap a pager func to strip the `self` arg |
|
46 | 48 | |
|
47 | 49 | so it can be called as a hook. |
|
48 | 50 | """ |
|
49 | 51 | return lambda self, *args, **kwargs: page_func(*args, **kwargs) |
|
50 | 52 | |
|
51 | 53 | |
|
52 | 54 | esc_re = re.compile(r"(\x1b[^m]+m)") |
|
53 | 55 | |
|
54 | 56 | def page_dumb(strng, start=0, screen_lines=25): |
|
55 | 57 | """Very dumb 'pager' in Python, for when nothing else works. |
|
56 | 58 | |
|
57 | 59 | Only moves forward, same interface as page(), except for pager_cmd and |
|
58 | 60 | mode. |
|
59 | 61 | """ |
|
60 | 62 | if isinstance(strng, dict): |
|
61 | 63 | strng = strng.get('text/plain', '') |
|
62 | 64 | out_ln = strng.splitlines()[start:] |
|
63 | 65 | screens = chop(out_ln,screen_lines-1) |
|
64 | 66 | if len(screens) == 1: |
|
65 | 67 | print(os.linesep.join(screens[0])) |
|
66 | 68 | else: |
|
67 | 69 | last_escape = "" |
|
68 | 70 | for scr in screens[0:-1]: |
|
69 | 71 | hunk = os.linesep.join(scr) |
|
70 | 72 | print(last_escape + hunk) |
|
71 | 73 | if not page_more(): |
|
72 | 74 | return |
|
73 | 75 | esc_list = esc_re.findall(hunk) |
|
74 | 76 | if len(esc_list) > 0: |
|
75 | 77 | last_escape = esc_list[-1] |
|
76 | 78 | print(last_escape + os.linesep.join(screens[-1])) |
|
77 | 79 | |
|
78 | 80 | def _detect_screen_size(screen_lines_def): |
|
79 | 81 | """Attempt to work out the number of lines on the screen. |
|
80 | 82 | |
|
81 | 83 | This is called by page(). It can raise an error (e.g. when run in the |
|
82 | 84 | test suite), so it's separated out so it can easily be called in a try block. |
|
83 | 85 | """ |
|
84 | 86 | TERM = os.environ.get('TERM',None) |
|
85 | 87 | if not((TERM=='xterm' or TERM=='xterm-color') and sys.platform != 'sunos5'): |
|
86 | 88 | # curses causes problems on many terminals other than xterm, and |
|
87 | 89 | # some termios calls lock up on Sun OS5. |
|
88 | 90 | return screen_lines_def |
|
89 | 91 | |
|
90 | 92 | try: |
|
91 | 93 | import termios |
|
92 | 94 | import curses |
|
93 | 95 | except ImportError: |
|
94 | 96 | return screen_lines_def |
|
95 | 97 | |
|
96 | 98 | # There is a bug in curses, where *sometimes* it fails to properly |
|
97 | 99 | # initialize, and then after the endwin() call is made, the |
|
98 | 100 | # terminal is left in an unusable state. Rather than trying to |
|
99 | 101 | # check every time for this (by requesting and comparing termios |
|
100 | 102 | # flags each time), we just save the initial terminal state and |
|
101 | 103 | # unconditionally reset it every time. It's cheaper than making |
|
102 | 104 | # the checks. |
|
103 | 105 | try: |
|
104 | 106 | term_flags = termios.tcgetattr(sys.stdout) |
|
105 | 107 | except termios.error as err: |
|
106 | 108 | # can fail on Linux 2.6, pager_page will catch the TypeError |
|
107 | 109 | raise TypeError('termios error: {0}'.format(err)) |
|
108 | 110 | |
|
109 | 111 | try: |
|
110 | 112 | scr = curses.initscr() |
|
111 | 113 | except AttributeError: |
|
112 | 114 | # Curses on Solaris may not be complete, so we can't use it there |
|
113 | 115 | return screen_lines_def |
|
114 | 116 | |
|
115 | 117 | screen_lines_real,screen_cols = scr.getmaxyx() |
|
116 | 118 | curses.endwin() |
|
117 | 119 | |
|
118 | 120 | # Restore terminal state in case endwin() didn't. |
|
119 | 121 | termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags) |
|
120 | 122 | # Now we have what we needed: the screen size in rows/columns |
|
121 | 123 | return screen_lines_real |
|
122 | 124 | #print '***Screen size:',screen_lines_real,'lines x',\ |
|
123 | 125 | #screen_cols,'columns.' # dbg |
|
124 | 126 | |
|
125 | 127 | def pager_page(strng, start=0, screen_lines=0, pager_cmd=None): |
|
126 | 128 | """Display a string, piping through a pager after a certain length. |
|
127 | 129 | |
|
128 | 130 | strng can be a mime-bundle dict, supplying multiple representations, |
|
129 | 131 | keyed by mime-type. |
|
130 | 132 | |
|
131 | 133 | The screen_lines parameter specifies the number of *usable* lines of your |
|
132 | 134 | terminal screen (total lines minus lines you need to reserve to show other |
|
133 | 135 | information). |
|
134 | 136 | |
|
135 | 137 | If you set screen_lines to a number <=0, page() will try to auto-determine |
|
136 | 138 | your screen size and will only use up to (screen_size+screen_lines) for |
|
137 | 139 | printing, paging after that. That is, if you want auto-detection but need |
|
138 | 140 | to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for |
|
139 | 141 | auto-detection without any lines reserved simply use screen_lines = 0. |
|
140 | 142 | |
|
141 | 143 | If a string won't fit in the allowed lines, it is sent through the |
|
142 | 144 | specified pager command. If none given, look for PAGER in the environment, |
|
143 | 145 | and ultimately default to less. |
|
144 | 146 | |
|
145 | 147 | If no system pager works, the string is sent through a 'dumb pager' |
|
146 | 148 | written in python, very simplistic. |
|
147 | 149 | """ |
|
148 | 150 | |
|
149 | 151 | # for compatibility with mime-bundle form: |
|
150 | 152 | if isinstance(strng, dict): |
|
151 | 153 | strng = strng['text/plain'] |
|
152 | 154 | |
|
153 | 155 | # Ugly kludge, but calling curses.initscr() flat out crashes in emacs |
|
154 | 156 | TERM = os.environ.get('TERM','dumb') |
|
155 | 157 | if TERM in ['dumb','emacs'] and os.name != 'nt': |
|
156 | 158 | print(strng) |
|
157 | 159 | return |
|
158 | 160 | # chop off the topmost part of the string we don't want to see |
|
159 | 161 | str_lines = strng.splitlines()[start:] |
|
160 | 162 | str_toprint = os.linesep.join(str_lines) |
|
161 | 163 | num_newlines = len(str_lines) |
|
162 | 164 | len_str = len(str_toprint) |
|
163 | 165 | |
|
164 | 166 | # Dumb heuristics to guesstimate number of on-screen lines the string |
|
165 | 167 | # takes. Very basic, but good enough for docstrings in reasonable |
|
166 | 168 | # terminals. If someone later feels like refining it, it's not hard. |
|
167 | 169 | numlines = max(num_newlines,int(len_str/80)+1) |
|
168 | 170 | |
|
169 | 171 | screen_lines_def = get_terminal_size()[1] |
|
170 | 172 | |
|
171 | 173 | # auto-determine screen size |
|
172 | 174 | if screen_lines <= 0: |
|
173 | 175 | try: |
|
174 | 176 | screen_lines += _detect_screen_size(screen_lines_def) |
|
175 | 177 | except (TypeError, UnsupportedOperation): |
|
176 | 178 | print(str_toprint) |
|
177 | 179 | return |
|
178 | 180 | |
|
179 | 181 | #print 'numlines',numlines,'screenlines',screen_lines # dbg |
|
180 | 182 | if numlines <= screen_lines : |
|
181 | 183 | #print '*** normal print' # dbg |
|
182 | 184 | print(str_toprint) |
|
183 | 185 | else: |
|
184 | 186 | # Try to open pager and default to internal one if that fails. |
|
185 | 187 | # All failure modes are tagged as 'retval=1', to match the return |
|
186 | 188 | # value of a failed system command. If any intermediate attempt |
|
187 | 189 | # sets retval to 1, at the end we resort to our own page_dumb() pager. |
|
188 | 190 | pager_cmd = get_pager_cmd(pager_cmd) |
|
189 | 191 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) |
|
190 | 192 | if os.name == 'nt': |
|
191 | 193 | if pager_cmd.startswith('type'): |
|
192 | 194 | # The default WinXP 'type' command is failing on complex strings. |
|
193 | 195 | retval = 1 |
|
194 | 196 | else: |
|
195 | 197 | fd, tmpname = tempfile.mkstemp('.txt') |
|
196 | 198 | try: |
|
197 | 199 | os.close(fd) |
|
198 | 200 | with open(tmpname, 'wt') as tmpfile: |
|
199 | 201 | tmpfile.write(strng) |
|
200 | 202 | cmd = "%s < %s" % (pager_cmd, tmpname) |
|
201 | 203 | # tmpfile needs to be closed for windows |
|
202 | 204 | if os.system(cmd): |
|
203 | 205 | retval = 1 |
|
204 | 206 | else: |
|
205 | 207 | retval = None |
|
206 | 208 | finally: |
|
207 | 209 | os.remove(tmpname) |
|
208 | 210 | else: |
|
209 | 211 | try: |
|
210 | 212 | retval = None |
|
211 | # if I use popen4, things hang. No idea why. | |
|
212 |
|
|
|
213 | pager = os.popen(pager_cmd, 'w') | |
|
213 | # Emulate os.popen, but redirect stderr | |
|
214 | proc = subprocess.Popen(pager_cmd, | |
|
215 | shell=True, | |
|
216 | stdin=subprocess.PIPE, | |
|
217 | stderr=subprocess.DEVNULL | |
|
218 | ) | |
|
219 | pager = os._wrap_close(io.TextIOWrapper(proc.stdin), proc) | |
|
214 | 220 | try: |
|
215 | 221 | pager_encoding = pager.encoding or sys.stdout.encoding |
|
216 | 222 | pager.write(strng) |
|
217 | 223 | finally: |
|
218 | 224 | retval = pager.close() |
|
219 | 225 | except IOError as msg: # broken pipe when user quits |
|
220 | 226 | if msg.args == (32, 'Broken pipe'): |
|
221 | 227 | retval = None |
|
222 | 228 | else: |
|
223 | 229 | retval = 1 |
|
224 | 230 | except OSError: |
|
225 | 231 | # Other strange problems, sometimes seen in Win2k/cygwin |
|
226 | 232 | retval = 1 |
|
227 | 233 | if retval is not None: |
|
228 | 234 | page_dumb(strng,screen_lines=screen_lines) |
|
229 | 235 | |
|
230 | 236 | |
|
231 | 237 | def page(data, start=0, screen_lines=0, pager_cmd=None): |
|
232 | 238 | """Display content in a pager, piping through a pager after a certain length. |
|
233 | 239 | |
|
234 | 240 | data can be a mime-bundle dict, supplying multiple representations, |
|
235 | 241 | keyed by mime-type, or text. |
|
236 | 242 | |
|
237 | 243 | Pager is dispatched via the `show_in_pager` IPython hook. |
|
238 | 244 | If no hook is registered, `pager_page` will be used. |
|
239 | 245 | """ |
|
240 | 246 | # Some routines may auto-compute start offsets incorrectly and pass a |
|
241 | 247 | # negative value. Offset to 0 for robustness. |
|
242 | 248 | start = max(0, start) |
|
243 | 249 | |
|
244 | 250 | # first, try the hook |
|
245 | 251 | ip = get_ipython() |
|
246 | 252 | if ip: |
|
247 | 253 | try: |
|
248 | 254 | ip.hooks.show_in_pager(data, start=start, screen_lines=screen_lines) |
|
249 | 255 | return |
|
250 | 256 | except TryNext: |
|
251 | 257 | pass |
|
252 | 258 | |
|
253 | 259 | # fallback on default pager |
|
254 | 260 | return pager_page(data, start, screen_lines, pager_cmd) |
|
255 | 261 | |
|
256 | 262 | |
|
257 | 263 | def page_file(fname, start=0, pager_cmd=None): |
|
258 | 264 | """Page a file, using an optional pager command and starting line. |
|
259 | 265 | """ |
|
260 | 266 | |
|
261 | 267 | pager_cmd = get_pager_cmd(pager_cmd) |
|
262 | 268 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) |
|
263 | 269 | |
|
264 | 270 | try: |
|
265 | 271 | if os.environ['TERM'] in ['emacs','dumb']: |
|
266 | 272 | raise EnvironmentError |
|
267 | 273 | system(pager_cmd + ' ' + fname) |
|
268 | 274 | except: |
|
269 | 275 | try: |
|
270 | 276 | if start > 0: |
|
271 | 277 | start -= 1 |
|
272 | 278 | page(open(fname).read(),start) |
|
273 | 279 | except: |
|
274 | 280 | print('Unable to show file',repr(fname)) |
|
275 | 281 | |
|
276 | 282 | |
|
277 | 283 | def get_pager_cmd(pager_cmd=None): |
|
278 | 284 | """Return a pager command. |
|
279 | 285 | |
|
280 | 286 | Makes some attempts at finding an OS-correct one. |
|
281 | 287 | """ |
|
282 | 288 | if os.name == 'posix': |
|
283 | 289 | default_pager_cmd = 'less -R' # -R for color control sequences |
|
284 | 290 | elif os.name in ['nt','dos']: |
|
285 | 291 | default_pager_cmd = 'type' |
|
286 | 292 | |
|
287 | 293 | if pager_cmd is None: |
|
288 | 294 | try: |
|
289 | 295 | pager_cmd = os.environ['PAGER'] |
|
290 | 296 | except: |
|
291 | 297 | pager_cmd = default_pager_cmd |
|
292 | 298 | |
|
293 | 299 | if pager_cmd == 'less' and '-r' not in os.environ.get('LESS', '').lower(): |
|
294 | 300 | pager_cmd += ' -R' |
|
295 | 301 | |
|
296 | 302 | return pager_cmd |
|
297 | 303 | |
|
298 | 304 | |
|
299 | 305 | def get_pager_start(pager, start): |
|
300 | 306 | """Return the string for paging files with an offset. |
|
301 | 307 | |
|
302 | 308 | This is the '+N' argument which less and more (under Unix) accept. |
|
303 | 309 | """ |
|
304 | 310 | |
|
305 | 311 | if pager in ['less','more']: |
|
306 | 312 | if start: |
|
307 | 313 | start_string = '+' + str(start) |
|
308 | 314 | else: |
|
309 | 315 | start_string = '' |
|
310 | 316 | else: |
|
311 | 317 | start_string = '' |
|
312 | 318 | return start_string |
|
313 | 319 | |
|
314 | 320 | |
|
315 | 321 | # (X)emacs on win32 doesn't like to be bypassed with msvcrt.getch() |
|
316 | 322 | if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs': |
|
317 | 323 | import msvcrt |
|
318 | 324 | def page_more(): |
|
319 | 325 | """ Smart pausing between pages |
|
320 | 326 | |
|
321 | 327 | @return: True if need print more lines, False if quit |
|
322 | 328 | """ |
|
323 | 329 | sys.stdout.write('---Return to continue, q to quit--- ') |
|
324 | 330 | ans = msvcrt.getwch() |
|
325 | 331 | if ans in ("q", "Q"): |
|
326 | 332 | result = False |
|
327 | 333 | else: |
|
328 | 334 | result = True |
|
329 | 335 | sys.stdout.write("\b"*37 + " "*37 + "\b"*37) |
|
330 | 336 | return result |
|
331 | 337 | else: |
|
332 | 338 | def page_more(): |
|
333 | 339 | ans = py3compat.input('---Return to continue, q to quit--- ') |
|
334 | 340 | if ans.lower().startswith('q'): |
|
335 | 341 | return False |
|
336 | 342 | else: |
|
337 | 343 | return True |
|
338 | 344 | |
|
339 | 345 | |
|
340 | 346 | def snip_print(str,width = 75,print_full = 0,header = ''): |
|
341 | 347 | """Print a string snipping the midsection to fit in width. |
|
342 | 348 | |
|
343 | 349 | print_full: mode control: |
|
344 | 350 | |
|
345 | 351 | - 0: only snip long strings |
|
346 | 352 | - 1: send to page() directly. |
|
347 | 353 | - 2: snip long strings and ask for full length viewing with page() |
|
348 | 354 | |
|
349 | 355 | Return 1 if snipping was necessary, 0 otherwise.""" |
|
350 | 356 | |
|
351 | 357 | if print_full == 1: |
|
352 | 358 | page(header+str) |
|
353 | 359 | return 0 |
|
354 | 360 | |
|
355 | 361 | print(header, end=' ') |
|
356 | 362 | if len(str) < width: |
|
357 | 363 | print(str) |
|
358 | 364 | snip = 0 |
|
359 | 365 | else: |
|
360 | 366 | whalf = int((width -5)/2) |
|
361 | 367 | print(str[:whalf] + ' <...> ' + str[-whalf:]) |
|
362 | 368 | snip = 1 |
|
363 | 369 | if snip and print_full == 2: |
|
364 | 370 | if py3compat.input(header+' Snipped. View (y/n)? [N]').lower() == 'y': |
|
365 | 371 | page(str) |
|
366 | 372 | return snip |
@@ -1,119 +1,119 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Release data for the IPython project.""" |
|
3 | 3 | |
|
4 | 4 | #----------------------------------------------------------------------------- |
|
5 | 5 | # Copyright (c) 2008, IPython Development Team. |
|
6 | 6 | # Copyright (c) 2001, Fernando Perez <fernando.perez@colorado.edu> |
|
7 | 7 | # Copyright (c) 2001, Janko Hauser <jhauser@zscout.de> |
|
8 | 8 | # Copyright (c) 2001, Nathaniel Gray <n8gray@caltech.edu> |
|
9 | 9 | # |
|
10 | 10 | # Distributed under the terms of the Modified BSD License. |
|
11 | 11 | # |
|
12 | 12 | # The full license is in the file COPYING.txt, distributed with this software. |
|
13 | 13 | #----------------------------------------------------------------------------- |
|
14 | 14 | |
|
15 | 15 | # Name of the package for release purposes. This is the name which labels |
|
16 | 16 | # the tarballs and RPMs made by distutils, so it's best to lowercase it. |
|
17 | 17 | name = 'ipython' |
|
18 | 18 | |
|
19 | 19 | # IPython version information. An empty _version_extra corresponds to a full |
|
20 | 20 | # release. 'dev' as a _version_extra string means this is a development |
|
21 | 21 | # version |
|
22 | 22 | _version_major = 7 |
|
23 |
_version_minor = 1 |
|
|
23 | _version_minor = 11 | |
|
24 | 24 | _version_patch = 0 |
|
25 | 25 | _version_extra = '.dev' |
|
26 | 26 | # _version_extra = 'b1' |
|
27 | 27 | # _version_extra = '' # Uncomment this for full releases |
|
28 | 28 | |
|
29 | 29 | # Construct full version string from these. |
|
30 | 30 | _ver = [_version_major, _version_minor, _version_patch] |
|
31 | 31 | |
|
32 | 32 | __version__ = '.'.join(map(str, _ver)) |
|
33 | 33 | if _version_extra: |
|
34 | 34 | __version__ = __version__ + _version_extra |
|
35 | 35 | |
|
36 | 36 | version = __version__ # backwards compatibility name |
|
37 | 37 | version_info = (_version_major, _version_minor, _version_patch, _version_extra) |
|
38 | 38 | |
|
39 | 39 | # Change this when incrementing the kernel protocol version |
|
40 | 40 | kernel_protocol_version_info = (5, 0) |
|
41 | 41 | kernel_protocol_version = "%i.%i" % kernel_protocol_version_info |
|
42 | 42 | |
|
43 | 43 | description = "IPython: Productive Interactive Computing" |
|
44 | 44 | |
|
45 | 45 | long_description = \ |
|
46 | 46 | """ |
|
47 | 47 | IPython provides a rich toolkit to help you make the most out of using Python |
|
48 | 48 | interactively. Its main components are: |
|
49 | 49 | |
|
50 | 50 | * A powerful interactive Python shell |
|
51 | 51 | * A `Jupyter <https://jupyter.org/>`_ kernel to work with Python code in Jupyter |
|
52 | 52 | notebooks and other interactive frontends. |
|
53 | 53 | |
|
54 | 54 | The enhanced interactive Python shells have the following main features: |
|
55 | 55 | |
|
56 | 56 | * Comprehensive object introspection. |
|
57 | 57 | |
|
58 | 58 | * Input history, persistent across sessions. |
|
59 | 59 | |
|
60 | 60 | * Caching of output results during a session with automatically generated |
|
61 | 61 | references. |
|
62 | 62 | |
|
63 | 63 | * Extensible tab completion, with support by default for completion of python |
|
64 | 64 | variables and keywords, filenames and function keywords. |
|
65 | 65 | |
|
66 | 66 | * Extensible system of 'magic' commands for controlling the environment and |
|
67 | 67 | performing many tasks related either to IPython or the operating system. |
|
68 | 68 | |
|
69 | 69 | * A rich configuration system with easy switching between different setups |
|
70 | 70 | (simpler than changing $PYTHONSTARTUP environment variables every time). |
|
71 | 71 | |
|
72 | 72 | * Session logging and reloading. |
|
73 | 73 | |
|
74 | 74 | * Extensible syntax processing for special purpose situations. |
|
75 | 75 | |
|
76 | 76 | * Access to the system shell with user-extensible alias system. |
|
77 | 77 | |
|
78 | 78 | * Easily embeddable in other Python programs and GUIs. |
|
79 | 79 | |
|
80 | 80 | * Integrated access to the pdb debugger and the Python profiler. |
|
81 | 81 | |
|
82 | 82 | The latest development version is always available from IPython's `GitHub |
|
83 | 83 | site <http://github.com/ipython>`_. |
|
84 | 84 | """ |
|
85 | 85 | |
|
86 | 86 | license = 'BSD' |
|
87 | 87 | |
|
88 | 88 | authors = {'Fernando' : ('Fernando Perez','fperez.net@gmail.com'), |
|
89 | 89 | 'Janko' : ('Janko Hauser','jhauser@zscout.de'), |
|
90 | 90 | 'Nathan' : ('Nathaniel Gray','n8gray@caltech.edu'), |
|
91 | 91 | 'Ville' : ('Ville Vainio','vivainio@gmail.com'), |
|
92 | 92 | 'Brian' : ('Brian E Granger', 'ellisonbg@gmail.com'), |
|
93 | 93 | 'Min' : ('Min Ragan-Kelley', 'benjaminrk@gmail.com'), |
|
94 | 94 | 'Thomas' : ('Thomas A. Kluyver', 'takowl@gmail.com'), |
|
95 | 95 | 'Jorgen' : ('Jorgen Stenarson', 'jorgen.stenarson@bostream.nu'), |
|
96 | 96 | 'Matthias' : ('Matthias Bussonnier', 'bussonniermatthias@gmail.com'), |
|
97 | 97 | } |
|
98 | 98 | |
|
99 | 99 | author = 'The IPython Development Team' |
|
100 | 100 | |
|
101 | 101 | author_email = 'ipython-dev@python.org' |
|
102 | 102 | |
|
103 | 103 | url = 'https://ipython.org' |
|
104 | 104 | |
|
105 | 105 | |
|
106 | 106 | platforms = ['Linux','Mac OSX','Windows'] |
|
107 | 107 | |
|
108 | 108 | keywords = ['Interactive','Interpreter','Shell', 'Embedding'] |
|
109 | 109 | |
|
110 | 110 | classifiers = [ |
|
111 | 111 | 'Framework :: IPython', |
|
112 | 112 | 'Intended Audience :: Developers', |
|
113 | 113 | 'Intended Audience :: Science/Research', |
|
114 | 114 | 'License :: OSI Approved :: BSD License', |
|
115 | 115 | 'Programming Language :: Python', |
|
116 | 116 | 'Programming Language :: Python :: 3', |
|
117 | 117 | 'Programming Language :: Python :: 3 :: Only', |
|
118 | 118 | 'Topic :: System :: Shells' |
|
119 | 119 | ] |
@@ -1,67 +1,66 b'' | |||
|
1 | 1 | """These kinds of tests are less than ideal, but at least they run. |
|
2 | 2 | |
|
3 | 3 | This was an old test that was being run interactively in the top-level tests/ |
|
4 | 4 | directory, which we are removing. For now putting this here ensures at least |
|
5 | 5 | we do run the test, though ultimately this functionality should all be tested |
|
6 | 6 | with better-isolated tests that don't rely on the global instance in iptest. |
|
7 | 7 | """ |
|
8 | 8 | from IPython.core.splitinput import LineInfo |
|
9 | 9 | from IPython.core.prefilter import AutocallChecker |
|
10 | from IPython.utils import py3compat | |
|
11 | 10 | |
|
12 | 11 | def doctest_autocall(): |
|
13 | 12 | """ |
|
14 | 13 | In [1]: def f1(a,b,c): |
|
15 | 14 | ...: return a+b+c |
|
16 | 15 | ...: |
|
17 | 16 | |
|
18 | 17 | In [2]: def f2(a): |
|
19 | 18 | ...: return a + a |
|
20 | 19 | ...: |
|
21 | 20 | |
|
22 | 21 | In [3]: def r(x): |
|
23 | 22 | ...: return True |
|
24 | 23 | ...: |
|
25 | 24 | |
|
26 | 25 | In [4]: ;f2 a b c |
|
27 | 26 | Out[4]: 'a b ca b c' |
|
28 | 27 | |
|
29 | 28 | In [5]: assert _ == "a b ca b c" |
|
30 | 29 | |
|
31 | 30 | In [6]: ,f1 a b c |
|
32 | 31 | Out[6]: 'abc' |
|
33 | 32 | |
|
34 | 33 | In [7]: assert _ == 'abc' |
|
35 | 34 | |
|
36 | 35 | In [8]: print(_) |
|
37 | 36 | abc |
|
38 | 37 | |
|
39 | 38 | In [9]: /f1 1,2,3 |
|
40 | 39 | Out[9]: 6 |
|
41 | 40 | |
|
42 | 41 | In [10]: assert _ == 6 |
|
43 | 42 | |
|
44 | 43 | In [11]: /f2 4 |
|
45 | 44 | Out[11]: 8 |
|
46 | 45 | |
|
47 | 46 | In [12]: assert _ == 8 |
|
48 | 47 | |
|
49 | 48 | In [12]: del f1, f2 |
|
50 | 49 | |
|
51 | 50 | In [13]: ,r a |
|
52 | 51 | Out[13]: True |
|
53 | 52 | |
|
54 | 53 | In [14]: assert _ == True |
|
55 | 54 | |
|
56 | 55 | In [15]: r'a' |
|
57 | 56 | Out[15]: 'a' |
|
58 | 57 | |
|
59 | 58 | In [16]: assert _ == 'a' |
|
60 | 59 | """ |
|
61 | 60 | |
|
62 | 61 | |
|
63 | 62 | def test_autocall_should_ignore_raw_strings(): |
|
64 | 63 | line_info = LineInfo("r'a'") |
|
65 | 64 | pm = ip.prefilter_manager |
|
66 | 65 | ac = AutocallChecker(shell=pm.shell, prefilter_manager=pm, config=pm.config) |
|
67 | 66 | assert ac.check(line_info) is None |
@@ -1,95 +1,95 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.utils import py3compat |
|
14 | 14 | |
|
15 | 15 | #----------------------------------------------------------------------------- |
|
16 | 16 | # Globals |
|
17 | 17 | #----------------------------------------------------------------------------- |
|
18 | 18 | |
|
19 | 19 | # Get the public instance of IPython |
|
20 | 20 | |
|
21 | 21 | failures = [] |
|
22 | 22 | num_tests = 0 |
|
23 | 23 | |
|
24 | 24 | #----------------------------------------------------------------------------- |
|
25 | 25 | # Test functions |
|
26 | 26 | #----------------------------------------------------------------------------- |
|
27 | 27 | |
|
28 | 28 | class CallableIndexable(object): |
|
29 | 29 | def __getitem__(self, idx): return True |
|
30 | 30 | def __call__(self, *args, **kws): return True |
|
31 | 31 | |
|
32 | 32 | |
|
33 | 33 | class Autocallable(autocall.IPyAutocall): |
|
34 | 34 | def __call__(self): |
|
35 | 35 | return "called" |
|
36 | 36 | |
|
37 | 37 | |
|
38 | 38 | def run(tests): |
|
39 | 39 | """Loop through a list of (pre, post) inputs, where pre is the string |
|
40 | 40 | handed to ipython, and post is how that string looks after it's been |
|
41 | 41 | transformed (i.e. ipython's notion of _i)""" |
|
42 | 42 | tt.check_pairs(ip.prefilter_manager.prefilter_lines, tests) |
|
43 | 43 | |
|
44 | 44 | |
|
45 | 45 | def test_handlers(): |
|
46 | 46 | call_idx = CallableIndexable() |
|
47 | 47 | ip.user_ns['call_idx'] = call_idx |
|
48 | 48 | |
|
49 | 49 | # For many of the below, we're also checking that leading whitespace |
|
50 | 50 | # turns off the esc char, which it should unless there is a continuation |
|
51 | 51 | # line. |
|
52 | run([(i,py3compat.u_format(o)) for i,o in \ | |
|
52 | run( | |
|
53 | 53 | [('"no change"', '"no change"'), # normal |
|
54 | 54 | (u"lsmagic", "get_ipython().run_line_magic('lsmagic', '')"), # magic |
|
55 | 55 | #("a = b # PYTHON-MODE", '_i'), # emacs -- avoids _in cache |
|
56 |
] |
|
|
56 | ]) | |
|
57 | 57 | |
|
58 | 58 | # Objects which are instances of IPyAutocall are *always* autocalled |
|
59 | 59 | autocallable = Autocallable() |
|
60 | 60 | ip.user_ns['autocallable'] = autocallable |
|
61 | 61 | |
|
62 | 62 | # auto |
|
63 | 63 | ip.magic('autocall 0') |
|
64 | 64 | # Only explicit escapes or instances of IPyAutocallable should get |
|
65 | 65 | # expanded |
|
66 | 66 | run([ |
|
67 | 67 | ('len "abc"', 'len "abc"'), |
|
68 | 68 | ('autocallable', 'autocallable()'), |
|
69 | 69 | # Don't add extra brackets (gh-1117) |
|
70 | 70 | ('autocallable()', 'autocallable()'), |
|
71 | 71 | ]) |
|
72 | 72 | ip.magic('autocall 1') |
|
73 | 73 | run([ |
|
74 | 74 | ('len "abc"', 'len("abc")'), |
|
75 | 75 | ('len "abc";', 'len("abc");'), # ; is special -- moves out of parens |
|
76 | 76 | # Autocall is turned off if first arg is [] and the object |
|
77 | 77 | # is both callable and indexable. Like so: |
|
78 | 78 | ('len [1,2]', 'len([1,2])'), # len doesn't support __getitem__... |
|
79 | 79 | ('call_idx [1]', 'call_idx [1]'), # call_idx *does*.. |
|
80 | 80 | ('call_idx 1', 'call_idx(1)'), |
|
81 | 81 | ('len', 'len'), # only at 2 does it auto-call on single args |
|
82 | 82 | ]) |
|
83 | 83 | ip.magic('autocall 2') |
|
84 | 84 | run([ |
|
85 | 85 | ('len "abc"', 'len("abc")'), |
|
86 | 86 | ('len "abc";', 'len("abc");'), |
|
87 | 87 | ('len [1,2]', 'len([1,2])'), |
|
88 | 88 | ('call_idx [1]', 'call_idx [1]'), |
|
89 | 89 | ('call_idx 1', 'call_idx(1)'), |
|
90 | 90 | # This is what's different: |
|
91 | 91 | ('len', 'len()'), # only at 2 does it auto-call on single args |
|
92 | 92 | ]) |
|
93 | 93 | ip.magic('autocall 1') |
|
94 | 94 | |
|
95 | 95 | nt.assert_equal(failures, []) |
@@ -1,559 +1,588 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """Tests for code execution (%run and related), which is particularly tricky. |
|
3 | 3 | |
|
4 | 4 | Because of how %run manages namespaces, and the fact that we are trying here to |
|
5 | 5 | verify subtle object deletion and reference counting issues, the %run tests |
|
6 | 6 | will be kept in this separate file. This makes it easier to aggregate in one |
|
7 | 7 | place the tricks needed to handle it; most other magics are much easier to test |
|
8 | 8 | and we do so in a common test_magic file. |
|
9 | 9 | |
|
10 | 10 | Note that any test using `run -i` should make sure to do a `reset` afterwards, |
|
11 | 11 | as otherwise it may influence later tests. |
|
12 | 12 | """ |
|
13 | 13 | |
|
14 | 14 | # Copyright (c) IPython Development Team. |
|
15 | 15 | # Distributed under the terms of the Modified BSD License. |
|
16 | 16 | |
|
17 | 17 | |
|
18 | 18 | |
|
19 | 19 | import functools |
|
20 | 20 | import os |
|
21 | 21 | from os.path import join as pjoin |
|
22 | 22 | import random |
|
23 | 23 | import string |
|
24 | 24 | import sys |
|
25 | 25 | import textwrap |
|
26 | 26 | import unittest |
|
27 | 27 | from unittest.mock import patch |
|
28 | 28 | |
|
29 | 29 | import nose.tools as nt |
|
30 | 30 | from nose import SkipTest |
|
31 | 31 | |
|
32 | 32 | from IPython.testing import decorators as dec |
|
33 | 33 | from IPython.testing import tools as tt |
|
34 | 34 | from IPython.utils.io import capture_output |
|
35 | 35 | from IPython.utils.tempdir import TemporaryDirectory |
|
36 | 36 | from IPython.core import debugger |
|
37 | 37 | |
|
38 | 38 | def doctest_refbug(): |
|
39 | 39 | """Very nasty problem with references held by multiple runs of a script. |
|
40 | 40 | See: https://github.com/ipython/ipython/issues/141 |
|
41 | 41 | |
|
42 | 42 | In [1]: _ip.clear_main_mod_cache() |
|
43 | 43 | # random |
|
44 | 44 | |
|
45 | 45 | In [2]: %run refbug |
|
46 | 46 | |
|
47 | 47 | In [3]: call_f() |
|
48 | 48 | lowercased: hello |
|
49 | 49 | |
|
50 | 50 | In [4]: %run refbug |
|
51 | 51 | |
|
52 | 52 | In [5]: call_f() |
|
53 | 53 | lowercased: hello |
|
54 | 54 | lowercased: hello |
|
55 | 55 | """ |
|
56 | 56 | |
|
57 | 57 | |
|
58 | 58 | def doctest_run_builtins(): |
|
59 | 59 | r"""Check that %run doesn't damage __builtins__. |
|
60 | 60 | |
|
61 | 61 | In [1]: import tempfile |
|
62 | 62 | |
|
63 | 63 | In [2]: bid1 = id(__builtins__) |
|
64 | 64 | |
|
65 | 65 | In [3]: fname = tempfile.mkstemp('.py')[1] |
|
66 | 66 | |
|
67 | 67 | In [3]: f = open(fname,'w') |
|
68 | 68 | |
|
69 | 69 | In [4]: dummy= f.write('pass\n') |
|
70 | 70 | |
|
71 | 71 | In [5]: f.flush() |
|
72 | 72 | |
|
73 | 73 | In [6]: t1 = type(__builtins__) |
|
74 | 74 | |
|
75 | 75 | In [7]: %run $fname |
|
76 | 76 | |
|
77 | 77 | In [7]: f.close() |
|
78 | 78 | |
|
79 | 79 | In [8]: bid2 = id(__builtins__) |
|
80 | 80 | |
|
81 | 81 | In [9]: t2 = type(__builtins__) |
|
82 | 82 | |
|
83 | 83 | In [10]: t1 == t2 |
|
84 | 84 | Out[10]: True |
|
85 | 85 | |
|
86 | 86 | In [10]: bid1 == bid2 |
|
87 | 87 | Out[10]: True |
|
88 | 88 | |
|
89 | 89 | In [12]: try: |
|
90 | 90 | ....: os.unlink(fname) |
|
91 | 91 | ....: except: |
|
92 | 92 | ....: pass |
|
93 | 93 | ....: |
|
94 | 94 | """ |
|
95 | 95 | |
|
96 | 96 | |
|
97 | 97 | def doctest_run_option_parser(): |
|
98 | 98 | r"""Test option parser in %run. |
|
99 | 99 | |
|
100 | 100 | In [1]: %run print_argv.py |
|
101 | 101 | [] |
|
102 | 102 | |
|
103 | 103 | In [2]: %run print_argv.py print*.py |
|
104 | 104 | ['print_argv.py'] |
|
105 | 105 | |
|
106 | 106 | In [3]: %run -G print_argv.py print*.py |
|
107 | 107 | ['print*.py'] |
|
108 | 108 | |
|
109 | 109 | """ |
|
110 | 110 | |
|
111 | 111 | |
|
112 | 112 | @dec.skip_win32 |
|
113 | 113 | def doctest_run_option_parser_for_posix(): |
|
114 | 114 | r"""Test option parser in %run (Linux/OSX specific). |
|
115 | 115 | |
|
116 | 116 | You need double quote to escape glob in POSIX systems: |
|
117 | 117 | |
|
118 | 118 | In [1]: %run print_argv.py print\\*.py |
|
119 | 119 | ['print*.py'] |
|
120 | 120 | |
|
121 | 121 | You can't use quote to escape glob in POSIX systems: |
|
122 | 122 | |
|
123 | 123 | In [2]: %run print_argv.py 'print*.py' |
|
124 | 124 | ['print_argv.py'] |
|
125 | 125 | |
|
126 | 126 | """ |
|
127 | 127 | |
|
128 | 128 | |
|
129 | 129 | @dec.skip_if_not_win32 |
|
130 | 130 | def doctest_run_option_parser_for_windows(): |
|
131 | 131 | r"""Test option parser in %run (Windows specific). |
|
132 | 132 | |
|
133 | 133 | In Windows, you can't escape ``*` `by backslash: |
|
134 | 134 | |
|
135 | 135 | In [1]: %run print_argv.py print\\*.py |
|
136 | 136 | ['print\\*.py'] |
|
137 | 137 | |
|
138 | 138 | You can use quote to escape glob: |
|
139 | 139 | |
|
140 | 140 | In [2]: %run print_argv.py 'print*.py' |
|
141 | 141 | ['print*.py'] |
|
142 | 142 | |
|
143 | 143 | """ |
|
144 | 144 | |
|
145 | 145 | |
|
146 | 146 | def doctest_reset_del(): |
|
147 | 147 | """Test that resetting doesn't cause errors in __del__ methods. |
|
148 | 148 | |
|
149 | 149 | In [2]: class A(object): |
|
150 | 150 | ...: def __del__(self): |
|
151 | 151 | ...: print(str("Hi")) |
|
152 | 152 | ...: |
|
153 | 153 | |
|
154 | 154 | In [3]: a = A() |
|
155 | 155 | |
|
156 | 156 | In [4]: get_ipython().reset() |
|
157 | 157 | Hi |
|
158 | 158 | |
|
159 | 159 | In [5]: 1+1 |
|
160 | 160 | Out[5]: 2 |
|
161 | 161 | """ |
|
162 | 162 | |
|
163 | 163 | # For some tests, it will be handy to organize them in a class with a common |
|
164 | 164 | # setup that makes a temp file |
|
165 | 165 | |
|
166 | 166 | class TestMagicRunPass(tt.TempFileMixin): |
|
167 | 167 | |
|
168 | 168 | def setUp(self): |
|
169 | 169 | content = "a = [1,2,3]\nb = 1" |
|
170 | 170 | self.mktmp(content) |
|
171 | 171 | |
|
172 | 172 | def run_tmpfile(self): |
|
173 | 173 | _ip = get_ipython() |
|
174 | 174 | # This fails on Windows if self.tmpfile.name has spaces or "~" in it. |
|
175 | 175 | # See below and ticket https://bugs.launchpad.net/bugs/366353 |
|
176 | 176 | _ip.magic('run %s' % self.fname) |
|
177 | 177 | |
|
178 | 178 | def run_tmpfile_p(self): |
|
179 | 179 | _ip = get_ipython() |
|
180 | 180 | # This fails on Windows if self.tmpfile.name has spaces or "~" in it. |
|
181 | 181 | # See below and ticket https://bugs.launchpad.net/bugs/366353 |
|
182 | 182 | _ip.magic('run -p %s' % self.fname) |
|
183 | 183 | |
|
184 | 184 | def test_builtins_id(self): |
|
185 | 185 | """Check that %run doesn't damage __builtins__ """ |
|
186 | 186 | _ip = get_ipython() |
|
187 | 187 | # Test that the id of __builtins__ is not modified by %run |
|
188 | 188 | bid1 = id(_ip.user_ns['__builtins__']) |
|
189 | 189 | self.run_tmpfile() |
|
190 | 190 | bid2 = id(_ip.user_ns['__builtins__']) |
|
191 | 191 | nt.assert_equal(bid1, bid2) |
|
192 | 192 | |
|
193 | 193 | def test_builtins_type(self): |
|
194 | 194 | """Check that the type of __builtins__ doesn't change with %run. |
|
195 | 195 | |
|
196 | 196 | However, the above could pass if __builtins__ was already modified to |
|
197 | 197 | be a dict (it should be a module) by a previous use of %run. So we |
|
198 | 198 | also check explicitly that it really is a module: |
|
199 | 199 | """ |
|
200 | 200 | _ip = get_ipython() |
|
201 | 201 | self.run_tmpfile() |
|
202 | 202 | nt.assert_equal(type(_ip.user_ns['__builtins__']),type(sys)) |
|
203 | 203 | |
|
204 | 204 | def test_run_profile( self ): |
|
205 | 205 | """Test that the option -p, which invokes the profiler, do not |
|
206 | 206 | crash by invoking execfile""" |
|
207 | 207 | self.run_tmpfile_p() |
|
208 | 208 | |
|
209 | 209 | def test_run_debug_twice(self): |
|
210 | 210 | # https://github.com/ipython/ipython/issues/10028 |
|
211 | 211 | _ip = get_ipython() |
|
212 | 212 | with tt.fake_input(['c']): |
|
213 | 213 | _ip.magic('run -d %s' % self.fname) |
|
214 | 214 | with tt.fake_input(['c']): |
|
215 | 215 | _ip.magic('run -d %s' % self.fname) |
|
216 | 216 | |
|
217 | 217 | def test_run_debug_twice_with_breakpoint(self): |
|
218 | 218 | """Make a valid python temp file.""" |
|
219 | 219 | _ip = get_ipython() |
|
220 | 220 | with tt.fake_input(['b 2', 'c', 'c']): |
|
221 | 221 | _ip.magic('run -d %s' % self.fname) |
|
222 | 222 | |
|
223 | 223 | with tt.fake_input(['c']): |
|
224 | 224 | with tt.AssertNotPrints('KeyError'): |
|
225 | 225 | _ip.magic('run -d %s' % self.fname) |
|
226 | 226 | |
|
227 | 227 | |
|
228 | 228 | class TestMagicRunSimple(tt.TempFileMixin): |
|
229 | 229 | |
|
230 | 230 | def test_simpledef(self): |
|
231 | 231 | """Test that simple class definitions work.""" |
|
232 | 232 | src = ("class foo: pass\n" |
|
233 | 233 | "def f(): return foo()") |
|
234 | 234 | self.mktmp(src) |
|
235 | 235 | _ip.magic('run %s' % self.fname) |
|
236 | 236 | _ip.run_cell('t = isinstance(f(), foo)') |
|
237 | 237 | nt.assert_true(_ip.user_ns['t']) |
|
238 | 238 | |
|
239 | 239 | def test_obj_del(self): |
|
240 | 240 | """Test that object's __del__ methods are called on exit.""" |
|
241 | 241 | if sys.platform == 'win32': |
|
242 | 242 | try: |
|
243 | 243 | import win32api |
|
244 | 244 | except ImportError: |
|
245 | 245 | raise SkipTest("Test requires pywin32") |
|
246 | 246 | src = ("class A(object):\n" |
|
247 | 247 | " def __del__(self):\n" |
|
248 | 248 | " print('object A deleted')\n" |
|
249 | 249 | "a = A()\n") |
|
250 | 250 | self.mktmp(src) |
|
251 | 251 | if dec.module_not_available('sqlite3'): |
|
252 | 252 | err = 'WARNING: IPython History requires SQLite, your history will not be saved\n' |
|
253 | 253 | else: |
|
254 | 254 | err = None |
|
255 | 255 | tt.ipexec_validate(self.fname, 'object A deleted', err) |
|
256 | 256 | |
|
257 | 257 | def test_aggressive_namespace_cleanup(self): |
|
258 | 258 | """Test that namespace cleanup is not too aggressive GH-238 |
|
259 | 259 | |
|
260 | 260 | Returning from another run magic deletes the namespace""" |
|
261 | 261 | # see ticket https://github.com/ipython/ipython/issues/238 |
|
262 | 262 | |
|
263 | 263 | with tt.TempFileMixin() as empty: |
|
264 | 264 | empty.mktmp('') |
|
265 | 265 | # On Windows, the filename will have \users in it, so we need to use the |
|
266 | 266 | # repr so that the \u becomes \\u. |
|
267 | 267 | src = ("ip = get_ipython()\n" |
|
268 | 268 | "for i in range(5):\n" |
|
269 | 269 | " try:\n" |
|
270 | 270 | " ip.magic(%r)\n" |
|
271 | 271 | " except NameError as e:\n" |
|
272 | 272 | " print(i)\n" |
|
273 | 273 | " break\n" % ('run ' + empty.fname)) |
|
274 | 274 | self.mktmp(src) |
|
275 | 275 | _ip.magic('run %s' % self.fname) |
|
276 | 276 | _ip.run_cell('ip == get_ipython()') |
|
277 | 277 | nt.assert_equal(_ip.user_ns['i'], 4) |
|
278 | 278 | |
|
279 | 279 | def test_run_second(self): |
|
280 | 280 | """Test that running a second file doesn't clobber the first, gh-3547 |
|
281 | 281 | """ |
|
282 | 282 | self.mktmp("avar = 1\n" |
|
283 | 283 | "def afunc():\n" |
|
284 | 284 | " return avar\n") |
|
285 | 285 | |
|
286 | 286 | with tt.TempFileMixin() as empty: |
|
287 | 287 | empty.mktmp("") |
|
288 | 288 | |
|
289 | 289 | _ip.magic('run %s' % self.fname) |
|
290 | 290 | _ip.magic('run %s' % empty.fname) |
|
291 | 291 | nt.assert_equal(_ip.user_ns['afunc'](), 1) |
|
292 | 292 | |
|
293 | 293 | @dec.skip_win32 |
|
294 | 294 | def test_tclass(self): |
|
295 | 295 | mydir = os.path.dirname(__file__) |
|
296 | 296 | tc = os.path.join(mydir, 'tclass') |
|
297 | 297 | src = ("%%run '%s' C-first\n" |
|
298 | 298 | "%%run '%s' C-second\n" |
|
299 | 299 | "%%run '%s' C-third\n") % (tc, tc, tc) |
|
300 | 300 | self.mktmp(src, '.ipy') |
|
301 | 301 | out = """\ |
|
302 | 302 | ARGV 1-: ['C-first'] |
|
303 | 303 | ARGV 1-: ['C-second'] |
|
304 | 304 | tclass.py: deleting object: C-first |
|
305 | 305 | ARGV 1-: ['C-third'] |
|
306 | 306 | tclass.py: deleting object: C-second |
|
307 | 307 | tclass.py: deleting object: C-third |
|
308 | 308 | """ |
|
309 | 309 | if dec.module_not_available('sqlite3'): |
|
310 | 310 | err = 'WARNING: IPython History requires SQLite, your history will not be saved\n' |
|
311 | 311 | else: |
|
312 | 312 | err = None |
|
313 | 313 | tt.ipexec_validate(self.fname, out, err) |
|
314 | 314 | |
|
315 | 315 | def test_run_i_after_reset(self): |
|
316 | 316 | """Check that %run -i still works after %reset (gh-693)""" |
|
317 | 317 | src = "yy = zz\n" |
|
318 | 318 | self.mktmp(src) |
|
319 | 319 | _ip.run_cell("zz = 23") |
|
320 | 320 | try: |
|
321 | 321 | _ip.magic('run -i %s' % self.fname) |
|
322 | 322 | nt.assert_equal(_ip.user_ns['yy'], 23) |
|
323 | 323 | finally: |
|
324 | 324 | _ip.magic('reset -f') |
|
325 | 325 | |
|
326 | 326 | _ip.run_cell("zz = 23") |
|
327 | 327 | try: |
|
328 | 328 | _ip.magic('run -i %s' % self.fname) |
|
329 | 329 | nt.assert_equal(_ip.user_ns['yy'], 23) |
|
330 | 330 | finally: |
|
331 | 331 | _ip.magic('reset -f') |
|
332 | 332 | |
|
333 | 333 | def test_unicode(self): |
|
334 | 334 | """Check that files in odd encodings are accepted.""" |
|
335 | 335 | mydir = os.path.dirname(__file__) |
|
336 | 336 | na = os.path.join(mydir, 'nonascii.py') |
|
337 | 337 | _ip.magic('run "%s"' % na) |
|
338 | 338 | nt.assert_equal(_ip.user_ns['u'], u'Ўт№Ф') |
|
339 | 339 | |
|
340 | 340 | def test_run_py_file_attribute(self): |
|
341 | 341 | """Test handling of `__file__` attribute in `%run <file>.py`.""" |
|
342 | 342 | src = "t = __file__\n" |
|
343 | 343 | self.mktmp(src) |
|
344 | 344 | _missing = object() |
|
345 | 345 | file1 = _ip.user_ns.get('__file__', _missing) |
|
346 | 346 | _ip.magic('run %s' % self.fname) |
|
347 | 347 | file2 = _ip.user_ns.get('__file__', _missing) |
|
348 | 348 | |
|
349 | 349 | # Check that __file__ was equal to the filename in the script's |
|
350 | 350 | # namespace. |
|
351 | 351 | nt.assert_equal(_ip.user_ns['t'], self.fname) |
|
352 | 352 | |
|
353 | 353 | # Check that __file__ was not leaked back into user_ns. |
|
354 | 354 | nt.assert_equal(file1, file2) |
|
355 | 355 | |
|
356 | 356 | def test_run_ipy_file_attribute(self): |
|
357 | 357 | """Test handling of `__file__` attribute in `%run <file.ipy>`.""" |
|
358 | 358 | src = "t = __file__\n" |
|
359 | 359 | self.mktmp(src, ext='.ipy') |
|
360 | 360 | _missing = object() |
|
361 | 361 | file1 = _ip.user_ns.get('__file__', _missing) |
|
362 | 362 | _ip.magic('run %s' % self.fname) |
|
363 | 363 | file2 = _ip.user_ns.get('__file__', _missing) |
|
364 | 364 | |
|
365 | 365 | # Check that __file__ was equal to the filename in the script's |
|
366 | 366 | # namespace. |
|
367 | 367 | nt.assert_equal(_ip.user_ns['t'], self.fname) |
|
368 | 368 | |
|
369 | 369 | # Check that __file__ was not leaked back into user_ns. |
|
370 | 370 | nt.assert_equal(file1, file2) |
|
371 | 371 | |
|
372 | 372 | def test_run_formatting(self): |
|
373 | 373 | """ Test that %run -t -N<N> does not raise a TypeError for N > 1.""" |
|
374 | 374 | src = "pass" |
|
375 | 375 | self.mktmp(src) |
|
376 | 376 | _ip.magic('run -t -N 1 %s' % self.fname) |
|
377 | 377 | _ip.magic('run -t -N 10 %s' % self.fname) |
|
378 | 378 | |
|
379 | 379 | def test_ignore_sys_exit(self): |
|
380 | 380 | """Test the -e option to ignore sys.exit()""" |
|
381 | 381 | src = "import sys; sys.exit(1)" |
|
382 | 382 | self.mktmp(src) |
|
383 | 383 | with tt.AssertPrints('SystemExit'): |
|
384 | 384 | _ip.magic('run %s' % self.fname) |
|
385 | 385 | |
|
386 | 386 | with tt.AssertNotPrints('SystemExit'): |
|
387 | 387 | _ip.magic('run -e %s' % self.fname) |
|
388 | 388 | |
|
389 | 389 | def test_run_nb(self): |
|
390 | 390 | """Test %run notebook.ipynb""" |
|
391 | 391 | from nbformat import v4, writes |
|
392 | 392 | nb = v4.new_notebook( |
|
393 | 393 | cells=[ |
|
394 | 394 | v4.new_markdown_cell("The Ultimate Question of Everything"), |
|
395 | 395 | v4.new_code_cell("answer=42") |
|
396 | 396 | ] |
|
397 | 397 | ) |
|
398 | 398 | src = writes(nb, version=4) |
|
399 | 399 | self.mktmp(src, ext='.ipynb') |
|
400 | 400 | |
|
401 | 401 | _ip.magic("run %s" % self.fname) |
|
402 | 402 | |
|
403 | 403 | nt.assert_equal(_ip.user_ns['answer'], 42) |
|
404 | 404 | |
|
405 | 405 | def test_file_options(self): |
|
406 | 406 | src = ('import sys\n' |
|
407 | 407 | 'a = " ".join(sys.argv[1:])\n') |
|
408 | 408 | self.mktmp(src) |
|
409 | 409 | test_opts = '-x 3 --verbose' |
|
410 | 410 | _ip.run_line_magic("run", '{0} {1}'.format(self.fname, test_opts)) |
|
411 | 411 | nt.assert_equal(_ip.user_ns['a'], test_opts) |
|
412 | 412 | |
|
413 | 413 | |
|
414 | 414 | class TestMagicRunWithPackage(unittest.TestCase): |
|
415 | 415 | |
|
416 | 416 | def writefile(self, name, content): |
|
417 | 417 | path = os.path.join(self.tempdir.name, name) |
|
418 | 418 | d = os.path.dirname(path) |
|
419 | 419 | if not os.path.isdir(d): |
|
420 | 420 | os.makedirs(d) |
|
421 | 421 | with open(path, 'w') as f: |
|
422 | 422 | f.write(textwrap.dedent(content)) |
|
423 | 423 | |
|
424 | 424 | def setUp(self): |
|
425 | 425 | self.package = package = 'tmp{0}'.format(''.join([random.choice(string.ascii_letters) for i in range(10)])) |
|
426 | 426 | """Temporary (probably) valid python package name.""" |
|
427 | 427 | |
|
428 | 428 | self.value = int(random.random() * 10000) |
|
429 | 429 | |
|
430 | 430 | self.tempdir = TemporaryDirectory() |
|
431 | 431 | self.__orig_cwd = os.getcwd() |
|
432 | 432 | sys.path.insert(0, self.tempdir.name) |
|
433 | 433 | |
|
434 | 434 | self.writefile(os.path.join(package, '__init__.py'), '') |
|
435 | 435 | self.writefile(os.path.join(package, 'sub.py'), """ |
|
436 | 436 | x = {0!r} |
|
437 | 437 | """.format(self.value)) |
|
438 | 438 | self.writefile(os.path.join(package, 'relative.py'), """ |
|
439 | 439 | from .sub import x |
|
440 | 440 | """) |
|
441 | 441 | self.writefile(os.path.join(package, 'absolute.py'), """ |
|
442 | 442 | from {0}.sub import x |
|
443 | 443 | """.format(package)) |
|
444 | 444 | self.writefile(os.path.join(package, 'args.py'), """ |
|
445 | 445 | import sys |
|
446 | 446 | a = " ".join(sys.argv[1:]) |
|
447 | 447 | """.format(package)) |
|
448 | 448 | |
|
449 | 449 | def tearDown(self): |
|
450 | 450 | os.chdir(self.__orig_cwd) |
|
451 | 451 | sys.path[:] = [p for p in sys.path if p != self.tempdir.name] |
|
452 | 452 | self.tempdir.cleanup() |
|
453 | 453 | |
|
454 | 454 | def check_run_submodule(self, submodule, opts=''): |
|
455 | 455 | _ip.user_ns.pop('x', None) |
|
456 | 456 | _ip.magic('run {2} -m {0}.{1}'.format(self.package, submodule, opts)) |
|
457 | 457 | self.assertEqual(_ip.user_ns['x'], self.value, |
|
458 | 458 | 'Variable `x` is not loaded from module `{0}`.' |
|
459 | 459 | .format(submodule)) |
|
460 | 460 | |
|
461 | 461 | def test_run_submodule_with_absolute_import(self): |
|
462 | 462 | self.check_run_submodule('absolute') |
|
463 | 463 | |
|
464 | 464 | def test_run_submodule_with_relative_import(self): |
|
465 | 465 | """Run submodule that has a relative import statement (#2727).""" |
|
466 | 466 | self.check_run_submodule('relative') |
|
467 | 467 | |
|
468 | 468 | def test_prun_submodule_with_absolute_import(self): |
|
469 | 469 | self.check_run_submodule('absolute', '-p') |
|
470 | 470 | |
|
471 | 471 | def test_prun_submodule_with_relative_import(self): |
|
472 | 472 | self.check_run_submodule('relative', '-p') |
|
473 | 473 | |
|
474 | 474 | def with_fake_debugger(func): |
|
475 | 475 | @functools.wraps(func) |
|
476 | 476 | def wrapper(*args, **kwds): |
|
477 | 477 | with patch.object(debugger.Pdb, 'run', staticmethod(eval)): |
|
478 | 478 | return func(*args, **kwds) |
|
479 | 479 | return wrapper |
|
480 | 480 | |
|
481 | 481 | @with_fake_debugger |
|
482 | 482 | def test_debug_run_submodule_with_absolute_import(self): |
|
483 | 483 | self.check_run_submodule('absolute', '-d') |
|
484 | 484 | |
|
485 | 485 | @with_fake_debugger |
|
486 | 486 | def test_debug_run_submodule_with_relative_import(self): |
|
487 | 487 | self.check_run_submodule('relative', '-d') |
|
488 | 488 | |
|
489 | 489 | def test_module_options(self): |
|
490 | 490 | _ip.user_ns.pop('a', None) |
|
491 | 491 | test_opts = '-x abc -m test' |
|
492 | 492 | _ip.run_line_magic('run', '-m {0}.args {1}'.format(self.package, test_opts)) |
|
493 | 493 | nt.assert_equal(_ip.user_ns['a'], test_opts) |
|
494 | 494 | |
|
495 | 495 | def test_module_options_with_separator(self): |
|
496 | 496 | _ip.user_ns.pop('a', None) |
|
497 | 497 | test_opts = '-x abc -m test' |
|
498 | 498 | _ip.run_line_magic('run', '-m {0}.args -- {1}'.format(self.package, test_opts)) |
|
499 | 499 | nt.assert_equal(_ip.user_ns['a'], test_opts) |
|
500 | 500 | |
|
501 | 501 | def test_run__name__(): |
|
502 | 502 | with TemporaryDirectory() as td: |
|
503 | 503 | path = pjoin(td, 'foo.py') |
|
504 | 504 | with open(path, 'w') as f: |
|
505 | 505 | f.write("q = __name__") |
|
506 | 506 | |
|
507 | 507 | _ip.user_ns.pop('q', None) |
|
508 | 508 | _ip.magic('run {}'.format(path)) |
|
509 | 509 | nt.assert_equal(_ip.user_ns.pop('q'), '__main__') |
|
510 | 510 | |
|
511 | 511 | _ip.magic('run -n {}'.format(path)) |
|
512 | 512 | nt.assert_equal(_ip.user_ns.pop('q'), 'foo') |
|
513 | 513 | |
|
514 | 514 | try: |
|
515 | 515 | _ip.magic('run -i -n {}'.format(path)) |
|
516 | 516 | nt.assert_equal(_ip.user_ns.pop('q'), 'foo') |
|
517 | 517 | finally: |
|
518 | 518 | _ip.magic('reset -f') |
|
519 | 519 | |
|
520 | 520 | |
|
521 | 521 | def test_run_tb(): |
|
522 | 522 | """Test traceback offset in %run""" |
|
523 | 523 | with TemporaryDirectory() as td: |
|
524 | 524 | path = pjoin(td, 'foo.py') |
|
525 | 525 | with open(path, 'w') as f: |
|
526 | 526 | f.write('\n'.join([ |
|
527 | 527 | "def foo():", |
|
528 | 528 | " return bar()", |
|
529 | 529 | "def bar():", |
|
530 | 530 | " raise RuntimeError('hello!')", |
|
531 | 531 | "foo()", |
|
532 | 532 | ])) |
|
533 | 533 | with capture_output() as io: |
|
534 | 534 | _ip.magic('run {}'.format(path)) |
|
535 | 535 | out = io.stdout |
|
536 | 536 | nt.assert_not_in("execfile", out) |
|
537 | 537 | nt.assert_in("RuntimeError", out) |
|
538 | 538 | nt.assert_equal(out.count("---->"), 3) |
|
539 | 539 | del ip.user_ns['bar'] |
|
540 | 540 | del ip.user_ns['foo'] |
|
541 | 541 | |
|
542 | ||
|
543 | def test_multiprocessing_run(): | |
|
544 | """Set we can run mutiprocesgin without messing up up main namespace | |
|
545 | ||
|
546 | Note that import `nose.tools as nt` mdify the value s | |
|
547 | sys.module['__mp_main__'] so wee need to temporarily set it to None to test | |
|
548 | the issue. | |
|
549 | """ | |
|
550 | with TemporaryDirectory() as td: | |
|
551 | mpm = sys.modules.get('__mp_main__') | |
|
552 | assert mpm is not None | |
|
553 | sys.modules['__mp_main__'] = None | |
|
554 | try: | |
|
555 | path = pjoin(td, 'test.py') | |
|
556 | with open(path, 'w') as f: | |
|
557 | f.write("import multiprocessing\nprint('hoy')") | |
|
558 | with capture_output() as io: | |
|
559 | _ip.run_line_magic('run', path) | |
|
560 | _ip.run_cell("i_m_undefined") | |
|
561 | out = io.stdout | |
|
562 | nt.assert_in("hoy", out) | |
|
563 | nt.assert_not_in("AttributeError", out) | |
|
564 | nt.assert_in("NameError", out) | |
|
565 | nt.assert_equal(out.count("---->"), 1) | |
|
566 | except: | |
|
567 | raise | |
|
568 | finally: | |
|
569 | sys.modules['__mp_main__'] = mpm | |
|
570 | ||
|
542 | 571 | @dec.knownfailureif(sys.platform == 'win32', "writes to io.stdout aren't captured on Windows") |
|
543 | 572 | def test_script_tb(): |
|
544 | 573 | """Test traceback offset in `ipython script.py`""" |
|
545 | 574 | with TemporaryDirectory() as td: |
|
546 | 575 | path = pjoin(td, 'foo.py') |
|
547 | 576 | with open(path, 'w') as f: |
|
548 | 577 | f.write('\n'.join([ |
|
549 | 578 | "def foo():", |
|
550 | 579 | " return bar()", |
|
551 | 580 | "def bar():", |
|
552 | 581 | " raise RuntimeError('hello!')", |
|
553 | 582 | "foo()", |
|
554 | 583 | ])) |
|
555 | 584 | out, err = tt.ipexec(path) |
|
556 | 585 | nt.assert_not_in("execfile", out) |
|
557 | 586 | nt.assert_in("RuntimeError", out) |
|
558 | 587 | nt.assert_equal(out.count("---->"), 3) |
|
559 | 588 |
@@ -1,440 +1,459 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """Tests for IPython.core.ultratb |
|
3 | 3 | """ |
|
4 | 4 | import io |
|
5 | 5 | import logging |
|
6 | 6 | import sys |
|
7 | 7 | import os.path |
|
8 | 8 | from textwrap import dedent |
|
9 | 9 | import traceback |
|
10 | 10 | import unittest |
|
11 | 11 | from unittest import mock |
|
12 | 12 | |
|
13 | 13 | import IPython.core.ultratb as ultratb |
|
14 | 14 | from IPython.core.ultratb import ColorTB, VerboseTB, find_recursion |
|
15 | 15 | |
|
16 | 16 | |
|
17 | 17 | from IPython.testing import tools as tt |
|
18 | 18 | from IPython.testing.decorators import onlyif_unicode_paths |
|
19 | 19 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
20 | 20 | from IPython.utils.tempdir import TemporaryDirectory |
|
21 | 21 | |
|
22 | 22 | file_1 = """1 |
|
23 | 23 | 2 |
|
24 | 24 | 3 |
|
25 | 25 | def f(): |
|
26 | 26 | 1/0 |
|
27 | 27 | """ |
|
28 | 28 | |
|
29 | 29 | file_2 = """def f(): |
|
30 | 30 | 1/0 |
|
31 | 31 | """ |
|
32 | 32 | |
|
33 | 33 | |
|
34 | 34 | def recursionlimit(frames): |
|
35 | 35 | """ |
|
36 | 36 | decorator to set the recursion limit temporarily |
|
37 | 37 | """ |
|
38 | 38 | |
|
39 | 39 | def inner(test_function): |
|
40 | 40 | def wrapper(*args, **kwargs): |
|
41 | 41 | _orig_rec_limit = ultratb._FRAME_RECURSION_LIMIT |
|
42 | 42 | ultratb._FRAME_RECURSION_LIMIT = 50 |
|
43 | 43 | |
|
44 | 44 | rl = sys.getrecursionlimit() |
|
45 | 45 | sys.setrecursionlimit(frames) |
|
46 | 46 | try: |
|
47 | 47 | return test_function(*args, **kwargs) |
|
48 | 48 | finally: |
|
49 | 49 | sys.setrecursionlimit(rl) |
|
50 | 50 | ultratb._FRAME_RECURSION_LIMIT = _orig_rec_limit |
|
51 | 51 | |
|
52 | 52 | return wrapper |
|
53 | 53 | |
|
54 | 54 | return inner |
|
55 | 55 | |
|
56 | 56 | |
|
57 | 57 | class ChangedPyFileTest(unittest.TestCase): |
|
58 | 58 | def test_changing_py_file(self): |
|
59 | 59 | """Traceback produced if the line where the error occurred is missing? |
|
60 | 60 | |
|
61 | 61 | https://github.com/ipython/ipython/issues/1456 |
|
62 | 62 | """ |
|
63 | 63 | with TemporaryDirectory() as td: |
|
64 | 64 | fname = os.path.join(td, "foo.py") |
|
65 | 65 | with open(fname, "w") as f: |
|
66 | 66 | f.write(file_1) |
|
67 | 67 | |
|
68 | 68 | with prepended_to_syspath(td): |
|
69 | 69 | ip.run_cell("import foo") |
|
70 | 70 | |
|
71 | 71 | with tt.AssertPrints("ZeroDivisionError"): |
|
72 | 72 | ip.run_cell("foo.f()") |
|
73 | 73 | |
|
74 | 74 | # Make the file shorter, so the line of the error is missing. |
|
75 | 75 | with open(fname, "w") as f: |
|
76 | 76 | f.write(file_2) |
|
77 | 77 | |
|
78 | 78 | # For some reason, this was failing on the *second* call after |
|
79 | 79 | # changing the file, so we call f() twice. |
|
80 | 80 | with tt.AssertNotPrints("Internal Python error", channel='stderr'): |
|
81 | 81 | with tt.AssertPrints("ZeroDivisionError"): |
|
82 | 82 | ip.run_cell("foo.f()") |
|
83 | 83 | with tt.AssertPrints("ZeroDivisionError"): |
|
84 | 84 | ip.run_cell("foo.f()") |
|
85 | 85 | |
|
86 | 86 | iso_8859_5_file = u'''# coding: iso-8859-5 |
|
87 | 87 | |
|
88 | 88 | def fail(): |
|
89 | 89 | """дбИЖ""" |
|
90 | 90 | 1/0 # дбИЖ |
|
91 | 91 | ''' |
|
92 | 92 | |
|
93 | 93 | class NonAsciiTest(unittest.TestCase): |
|
94 | 94 | @onlyif_unicode_paths |
|
95 | 95 | def test_nonascii_path(self): |
|
96 | 96 | # Non-ascii directory name as well. |
|
97 | 97 | with TemporaryDirectory(suffix=u'é') as td: |
|
98 | 98 | fname = os.path.join(td, u"fooé.py") |
|
99 | 99 | with open(fname, "w") as f: |
|
100 | 100 | f.write(file_1) |
|
101 | 101 | |
|
102 | 102 | with prepended_to_syspath(td): |
|
103 | 103 | ip.run_cell("import foo") |
|
104 | 104 | |
|
105 | 105 | with tt.AssertPrints("ZeroDivisionError"): |
|
106 | 106 | ip.run_cell("foo.f()") |
|
107 | 107 | |
|
108 | 108 | def test_iso8859_5(self): |
|
109 | 109 | with TemporaryDirectory() as td: |
|
110 | 110 | fname = os.path.join(td, 'dfghjkl.py') |
|
111 | 111 | |
|
112 | 112 | with io.open(fname, 'w', encoding='iso-8859-5') as f: |
|
113 | 113 | f.write(iso_8859_5_file) |
|
114 | 114 | |
|
115 | 115 | with prepended_to_syspath(td): |
|
116 | 116 | ip.run_cell("from dfghjkl import fail") |
|
117 | 117 | |
|
118 | 118 | with tt.AssertPrints("ZeroDivisionError"): |
|
119 | 119 | with tt.AssertPrints(u'дбИЖ', suppress=False): |
|
120 | 120 | ip.run_cell('fail()') |
|
121 | 121 | |
|
122 | 122 | def test_nonascii_msg(self): |
|
123 | 123 | cell = u"raise Exception('é')" |
|
124 | 124 | expected = u"Exception('é')" |
|
125 | 125 | ip.run_cell("%xmode plain") |
|
126 | 126 | with tt.AssertPrints(expected): |
|
127 | 127 | ip.run_cell(cell) |
|
128 | 128 | |
|
129 | 129 | ip.run_cell("%xmode verbose") |
|
130 | 130 | with tt.AssertPrints(expected): |
|
131 | 131 | ip.run_cell(cell) |
|
132 | 132 | |
|
133 | 133 | ip.run_cell("%xmode context") |
|
134 | 134 | with tt.AssertPrints(expected): |
|
135 | 135 | ip.run_cell(cell) |
|
136 | 136 | |
|
137 | 137 | ip.run_cell("%xmode minimal") |
|
138 | 138 | with tt.AssertPrints(u"Exception: é"): |
|
139 | 139 | ip.run_cell(cell) |
|
140 | 140 | |
|
141 | 141 | # Put this back into Context mode for later tests. |
|
142 | 142 | ip.run_cell("%xmode context") |
|
143 | 143 | |
|
144 | 144 | class NestedGenExprTestCase(unittest.TestCase): |
|
145 | 145 | """ |
|
146 | 146 | Regression test for the following issues: |
|
147 | 147 | https://github.com/ipython/ipython/issues/8293 |
|
148 | 148 | https://github.com/ipython/ipython/issues/8205 |
|
149 | 149 | """ |
|
150 | 150 | def test_nested_genexpr(self): |
|
151 | 151 | code = dedent( |
|
152 | 152 | """\ |
|
153 | 153 | class SpecificException(Exception): |
|
154 | 154 | pass |
|
155 | 155 | |
|
156 | 156 | def foo(x): |
|
157 | 157 | raise SpecificException("Success!") |
|
158 | 158 | |
|
159 | 159 | sum(sum(foo(x) for _ in [0]) for x in [0]) |
|
160 | 160 | """ |
|
161 | 161 | ) |
|
162 | 162 | with tt.AssertPrints('SpecificException: Success!', suppress=False): |
|
163 | 163 | ip.run_cell(code) |
|
164 | 164 | |
|
165 | 165 | |
|
166 | 166 | indentationerror_file = """if True: |
|
167 | 167 | zoon() |
|
168 | 168 | """ |
|
169 | 169 | |
|
170 | 170 | class IndentationErrorTest(unittest.TestCase): |
|
171 | 171 | def test_indentationerror_shows_line(self): |
|
172 | 172 | # See issue gh-2398 |
|
173 | 173 | with tt.AssertPrints("IndentationError"): |
|
174 | 174 | with tt.AssertPrints("zoon()", suppress=False): |
|
175 | 175 | ip.run_cell(indentationerror_file) |
|
176 | 176 | |
|
177 | 177 | with TemporaryDirectory() as td: |
|
178 | 178 | fname = os.path.join(td, "foo.py") |
|
179 | 179 | with open(fname, "w") as f: |
|
180 | 180 | f.write(indentationerror_file) |
|
181 | 181 | |
|
182 | 182 | with tt.AssertPrints("IndentationError"): |
|
183 | 183 | with tt.AssertPrints("zoon()", suppress=False): |
|
184 | 184 | ip.magic('run %s' % fname) |
|
185 | 185 | |
|
186 | 186 | se_file_1 = """1 |
|
187 | 187 | 2 |
|
188 | 188 | 7/ |
|
189 | 189 | """ |
|
190 | 190 | |
|
191 | 191 | se_file_2 = """7/ |
|
192 | 192 | """ |
|
193 | 193 | |
|
194 | 194 | class SyntaxErrorTest(unittest.TestCase): |
|
195 | 195 | def test_syntaxerror_without_lineno(self): |
|
196 | 196 | with tt.AssertNotPrints("TypeError"): |
|
197 | 197 | with tt.AssertPrints("line unknown"): |
|
198 | 198 | ip.run_cell("raise SyntaxError()") |
|
199 | 199 | |
|
200 | 200 | def test_syntaxerror_no_stacktrace_at_compile_time(self): |
|
201 | 201 | syntax_error_at_compile_time = """ |
|
202 | 202 | def foo(): |
|
203 | 203 | .. |
|
204 | 204 | """ |
|
205 | 205 | with tt.AssertPrints("SyntaxError"): |
|
206 | 206 | ip.run_cell(syntax_error_at_compile_time) |
|
207 | 207 | |
|
208 | 208 | with tt.AssertNotPrints("foo()"): |
|
209 | 209 | ip.run_cell(syntax_error_at_compile_time) |
|
210 | 210 | |
|
211 | 211 | def test_syntaxerror_stacktrace_when_running_compiled_code(self): |
|
212 | 212 | syntax_error_at_runtime = """ |
|
213 | 213 | def foo(): |
|
214 | 214 | eval("..") |
|
215 | 215 | |
|
216 | 216 | def bar(): |
|
217 | 217 | foo() |
|
218 | 218 | |
|
219 | 219 | bar() |
|
220 | 220 | """ |
|
221 | 221 | with tt.AssertPrints("SyntaxError"): |
|
222 | 222 | ip.run_cell(syntax_error_at_runtime) |
|
223 | 223 | # Assert syntax error during runtime generate stacktrace |
|
224 | 224 | with tt.AssertPrints(["foo()", "bar()"]): |
|
225 | 225 | ip.run_cell(syntax_error_at_runtime) |
|
226 | 226 | del ip.user_ns['bar'] |
|
227 | 227 | del ip.user_ns['foo'] |
|
228 | 228 | |
|
229 | 229 | def test_changing_py_file(self): |
|
230 | 230 | with TemporaryDirectory() as td: |
|
231 | 231 | fname = os.path.join(td, "foo.py") |
|
232 | 232 | with open(fname, 'w') as f: |
|
233 | 233 | f.write(se_file_1) |
|
234 | 234 | |
|
235 | 235 | with tt.AssertPrints(["7/", "SyntaxError"]): |
|
236 | 236 | ip.magic("run " + fname) |
|
237 | 237 | |
|
238 | 238 | # Modify the file |
|
239 | 239 | with open(fname, 'w') as f: |
|
240 | 240 | f.write(se_file_2) |
|
241 | 241 | |
|
242 | 242 | # The SyntaxError should point to the correct line |
|
243 | 243 | with tt.AssertPrints(["7/", "SyntaxError"]): |
|
244 | 244 | ip.magic("run " + fname) |
|
245 | 245 | |
|
246 | 246 | def test_non_syntaxerror(self): |
|
247 | 247 | # SyntaxTB may be called with an error other than a SyntaxError |
|
248 | 248 | # See e.g. gh-4361 |
|
249 | 249 | try: |
|
250 | 250 | raise ValueError('QWERTY') |
|
251 | 251 | except ValueError: |
|
252 | 252 | with tt.AssertPrints('QWERTY'): |
|
253 | 253 | ip.showsyntaxerror() |
|
254 | 254 | |
|
255 | 255 | |
|
256 | 256 | class Python3ChainedExceptionsTest(unittest.TestCase): |
|
257 | 257 | DIRECT_CAUSE_ERROR_CODE = """ |
|
258 | 258 | try: |
|
259 | 259 | x = 1 + 2 |
|
260 | 260 | print(not_defined_here) |
|
261 | 261 | except Exception as e: |
|
262 | 262 | x += 55 |
|
263 | 263 | x - 1 |
|
264 | 264 | y = {} |
|
265 | 265 | raise KeyError('uh') from e |
|
266 | 266 | """ |
|
267 | 267 | |
|
268 | 268 | EXCEPTION_DURING_HANDLING_CODE = """ |
|
269 | 269 | try: |
|
270 | 270 | x = 1 + 2 |
|
271 | 271 | print(not_defined_here) |
|
272 | 272 | except Exception as e: |
|
273 | 273 | x += 55 |
|
274 | 274 | x - 1 |
|
275 | 275 | y = {} |
|
276 | 276 | raise KeyError('uh') |
|
277 | 277 | """ |
|
278 | 278 | |
|
279 | 279 | SUPPRESS_CHAINING_CODE = """ |
|
280 | 280 | try: |
|
281 | 281 | 1/0 |
|
282 | 282 | except Exception: |
|
283 | 283 | raise ValueError("Yikes") from None |
|
284 | 284 | """ |
|
285 | 285 | |
|
286 | 286 | def test_direct_cause_error(self): |
|
287 | 287 | with tt.AssertPrints(["KeyError", "NameError", "direct cause"]): |
|
288 | 288 | ip.run_cell(self.DIRECT_CAUSE_ERROR_CODE) |
|
289 | 289 | |
|
290 | 290 | def test_exception_during_handling_error(self): |
|
291 | 291 | with tt.AssertPrints(["KeyError", "NameError", "During handling"]): |
|
292 | 292 | ip.run_cell(self.EXCEPTION_DURING_HANDLING_CODE) |
|
293 | 293 | |
|
294 | 294 | def test_suppress_exception_chaining(self): |
|
295 | 295 | with tt.AssertNotPrints("ZeroDivisionError"), \ |
|
296 | 296 | tt.AssertPrints("ValueError", suppress=False): |
|
297 | 297 | ip.run_cell(self.SUPPRESS_CHAINING_CODE) |
|
298 | 298 | |
|
299 | def test_plain_direct_cause_error(self): | |
|
300 | with tt.AssertPrints(["KeyError", "NameError", "direct cause"]): | |
|
301 | ip.run_cell("%xmode Plain") | |
|
302 | ip.run_cell(self.DIRECT_CAUSE_ERROR_CODE) | |
|
303 | ip.run_cell("%xmode Verbose") | |
|
304 | ||
|
305 | def test_plain_exception_during_handling_error(self): | |
|
306 | with tt.AssertPrints(["KeyError", "NameError", "During handling"]): | |
|
307 | ip.run_cell("%xmode Plain") | |
|
308 | ip.run_cell(self.EXCEPTION_DURING_HANDLING_CODE) | |
|
309 | ip.run_cell("%xmode Verbose") | |
|
310 | ||
|
311 | def test_plain_suppress_exception_chaining(self): | |
|
312 | with tt.AssertNotPrints("ZeroDivisionError"), \ | |
|
313 | tt.AssertPrints("ValueError", suppress=False): | |
|
314 | ip.run_cell("%xmode Plain") | |
|
315 | ip.run_cell(self.SUPPRESS_CHAINING_CODE) | |
|
316 | ip.run_cell("%xmode Verbose") | |
|
317 | ||
|
299 | 318 | |
|
300 | 319 | class RecursionTest(unittest.TestCase): |
|
301 | 320 | DEFINITIONS = """ |
|
302 | 321 | def non_recurs(): |
|
303 | 322 | 1/0 |
|
304 | 323 | |
|
305 | 324 | def r1(): |
|
306 | 325 | r1() |
|
307 | 326 | |
|
308 | 327 | def r3a(): |
|
309 | 328 | r3b() |
|
310 | 329 | |
|
311 | 330 | def r3b(): |
|
312 | 331 | r3c() |
|
313 | 332 | |
|
314 | 333 | def r3c(): |
|
315 | 334 | r3a() |
|
316 | 335 | |
|
317 | 336 | def r3o1(): |
|
318 | 337 | r3a() |
|
319 | 338 | |
|
320 | 339 | def r3o2(): |
|
321 | 340 | r3o1() |
|
322 | 341 | """ |
|
323 | 342 | def setUp(self): |
|
324 | 343 | ip.run_cell(self.DEFINITIONS) |
|
325 | 344 | |
|
326 | 345 | def test_no_recursion(self): |
|
327 | 346 | with tt.AssertNotPrints("frames repeated"): |
|
328 | 347 | ip.run_cell("non_recurs()") |
|
329 | 348 | |
|
330 | 349 | @recursionlimit(150) |
|
331 | 350 | def test_recursion_one_frame(self): |
|
332 | 351 | with tt.AssertPrints("1 frames repeated"): |
|
333 | 352 | ip.run_cell("r1()") |
|
334 | 353 | |
|
335 | 354 | @recursionlimit(150) |
|
336 | 355 | def test_recursion_three_frames(self): |
|
337 | 356 | with tt.AssertPrints("3 frames repeated"): |
|
338 | 357 | ip.run_cell("r3o2()") |
|
339 | 358 | |
|
340 | 359 | @recursionlimit(150) |
|
341 | 360 | def test_find_recursion(self): |
|
342 | 361 | captured = [] |
|
343 | 362 | def capture_exc(*args, **kwargs): |
|
344 | 363 | captured.append(sys.exc_info()) |
|
345 | 364 | with mock.patch.object(ip, 'showtraceback', capture_exc): |
|
346 | 365 | ip.run_cell("r3o2()") |
|
347 | 366 | |
|
348 | 367 | self.assertEqual(len(captured), 1) |
|
349 | 368 | etype, evalue, tb = captured[0] |
|
350 | 369 | self.assertIn("recursion", str(evalue)) |
|
351 | 370 | |
|
352 | 371 | records = ip.InteractiveTB.get_records(tb, 3, ip.InteractiveTB.tb_offset) |
|
353 | 372 | for r in records[:10]: |
|
354 | 373 | print(r[1:4]) |
|
355 | 374 | |
|
356 | 375 | # The outermost frames should be: |
|
357 | 376 | # 0: the 'cell' that was running when the exception came up |
|
358 | 377 | # 1: r3o2() |
|
359 | 378 | # 2: r3o1() |
|
360 | 379 | # 3: r3a() |
|
361 | 380 | # Then repeating r3b, r3c, r3a |
|
362 | 381 | last_unique, repeat_length = find_recursion(etype, evalue, records) |
|
363 | 382 | self.assertEqual(last_unique, 2) |
|
364 | 383 | self.assertEqual(repeat_length, 3) |
|
365 | 384 | |
|
366 | 385 | |
|
367 | 386 | #---------------------------------------------------------------------------- |
|
368 | 387 | |
|
369 | 388 | # module testing (minimal) |
|
370 | 389 | def test_handlers(): |
|
371 | 390 | def spam(c, d_e): |
|
372 | 391 | (d, e) = d_e |
|
373 | 392 | x = c + d |
|
374 | 393 | y = c * d |
|
375 | 394 | foo(x, y) |
|
376 | 395 | |
|
377 | 396 | def foo(a, b, bar=1): |
|
378 | 397 | eggs(a, b + bar) |
|
379 | 398 | |
|
380 | 399 | def eggs(f, g, z=globals()): |
|
381 | 400 | h = f + g |
|
382 | 401 | i = f - g |
|
383 | 402 | return h / i |
|
384 | 403 | |
|
385 | 404 | buff = io.StringIO() |
|
386 | 405 | |
|
387 | 406 | buff.write('') |
|
388 | 407 | buff.write('*** Before ***') |
|
389 | 408 | try: |
|
390 | 409 | buff.write(spam(1, (2, 3))) |
|
391 | 410 | except: |
|
392 | 411 | traceback.print_exc(file=buff) |
|
393 | 412 | |
|
394 | 413 | handler = ColorTB(ostream=buff) |
|
395 | 414 | buff.write('*** ColorTB ***') |
|
396 | 415 | try: |
|
397 | 416 | buff.write(spam(1, (2, 3))) |
|
398 | 417 | except: |
|
399 | 418 | handler(*sys.exc_info()) |
|
400 | 419 | buff.write('') |
|
401 | 420 | |
|
402 | 421 | handler = VerboseTB(ostream=buff) |
|
403 | 422 | buff.write('*** VerboseTB ***') |
|
404 | 423 | try: |
|
405 | 424 | buff.write(spam(1, (2, 3))) |
|
406 | 425 | except: |
|
407 | 426 | handler(*sys.exc_info()) |
|
408 | 427 | buff.write('') |
|
409 | 428 | |
|
410 | 429 | from IPython.testing.decorators import skipif |
|
411 | 430 | |
|
412 | 431 | class TokenizeFailureTest(unittest.TestCase): |
|
413 | 432 | """Tests related to https://github.com/ipython/ipython/issues/6864.""" |
|
414 | 433 | |
|
415 | 434 | # that appear to test that we are handling an exception that can be thrown |
|
416 | 435 | # by the tokenizer due to a bug that seem to have been fixed in 3.8, though |
|
417 | 436 | # I'm unsure if other sequences can make it raise this error. Let's just |
|
418 | 437 | # skip in 3.8 for now |
|
419 | 438 | @skipif(sys.version_info > (3,8)) |
|
420 | 439 | def testLogging(self): |
|
421 | 440 | message = "An unexpected error occurred while tokenizing input" |
|
422 | 441 | cell = 'raise ValueError("""a\nb""")' |
|
423 | 442 | |
|
424 | 443 | stream = io.StringIO() |
|
425 | 444 | handler = logging.StreamHandler(stream) |
|
426 | 445 | logger = logging.getLogger() |
|
427 | 446 | loglevel = logger.level |
|
428 | 447 | logger.addHandler(handler) |
|
429 | 448 | self.addCleanup(lambda: logger.removeHandler(handler)) |
|
430 | 449 | self.addCleanup(lambda: logger.setLevel(loglevel)) |
|
431 | 450 | |
|
432 | 451 | logger.setLevel(logging.INFO) |
|
433 | 452 | with tt.AssertNotPrints(message): |
|
434 | 453 | ip.run_cell(cell) |
|
435 | 454 | self.assertNotIn(message, stream.getvalue()) |
|
436 | 455 | |
|
437 | 456 | logger.setLevel(logging.DEBUG) |
|
438 | 457 | with tt.AssertNotPrints(message): |
|
439 | 458 | ip.run_cell(cell) |
|
440 | 459 | self.assertIn(message, stream.getvalue()) |
@@ -1,1473 +1,1502 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | Verbose and colourful traceback formatting. |
|
4 | 4 | |
|
5 | 5 | **ColorTB** |
|
6 | 6 | |
|
7 | 7 | I've always found it a bit hard to visually parse tracebacks in Python. The |
|
8 | 8 | ColorTB class is a solution to that problem. It colors the different parts of a |
|
9 | 9 | traceback in a manner similar to what you would expect from a syntax-highlighting |
|
10 | 10 | text editor. |
|
11 | 11 | |
|
12 | 12 | Installation instructions for ColorTB:: |
|
13 | 13 | |
|
14 | 14 | import sys,ultratb |
|
15 | 15 | sys.excepthook = ultratb.ColorTB() |
|
16 | 16 | |
|
17 | 17 | **VerboseTB** |
|
18 | 18 | |
|
19 | 19 | I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds |
|
20 | 20 | of useful info when a traceback occurs. Ping originally had it spit out HTML |
|
21 | 21 | and intended it for CGI programmers, but why should they have all the fun? I |
|
22 | 22 | altered it to spit out colored text to the terminal. It's a bit overwhelming, |
|
23 | 23 | but kind of neat, and maybe useful for long-running programs that you believe |
|
24 | 24 | are bug-free. If a crash *does* occur in that type of program you want details. |
|
25 | 25 | Give it a shot--you'll love it or you'll hate it. |
|
26 | 26 | |
|
27 | 27 | .. note:: |
|
28 | 28 | |
|
29 | 29 | The Verbose mode prints the variables currently visible where the exception |
|
30 | 30 | happened (shortening their strings if too long). This can potentially be |
|
31 | 31 | very slow, if you happen to have a huge data structure whose string |
|
32 | 32 | representation is complex to compute. Your computer may appear to freeze for |
|
33 | 33 | a while with cpu usage at 100%. If this occurs, you can cancel the traceback |
|
34 | 34 | with Ctrl-C (maybe hitting it more than once). |
|
35 | 35 | |
|
36 | 36 | If you encounter this kind of situation often, you may want to use the |
|
37 | 37 | Verbose_novars mode instead of the regular Verbose, which avoids formatting |
|
38 | 38 | variables (but otherwise includes the information and context given by |
|
39 | 39 | Verbose). |
|
40 | 40 | |
|
41 | 41 | .. note:: |
|
42 | 42 | |
|
43 | 43 | The verbose mode print all variables in the stack, which means it can |
|
44 | 44 | potentially leak sensitive information like access keys, or unencrypted |
|
45 | 45 | password. |
|
46 | 46 | |
|
47 | 47 | Installation instructions for VerboseTB:: |
|
48 | 48 | |
|
49 | 49 | import sys,ultratb |
|
50 | 50 | sys.excepthook = ultratb.VerboseTB() |
|
51 | 51 | |
|
52 | 52 | Note: Much of the code in this module was lifted verbatim from the standard |
|
53 | 53 | library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'. |
|
54 | 54 | |
|
55 | 55 | Color schemes |
|
56 | 56 | ------------- |
|
57 | 57 | |
|
58 | 58 | The colors are defined in the class TBTools through the use of the |
|
59 | 59 | ColorSchemeTable class. Currently the following exist: |
|
60 | 60 | |
|
61 | 61 | - NoColor: allows all of this module to be used in any terminal (the color |
|
62 | 62 | escapes are just dummy blank strings). |
|
63 | 63 | |
|
64 | 64 | - Linux: is meant to look good in a terminal like the Linux console (black |
|
65 | 65 | or very dark background). |
|
66 | 66 | |
|
67 | 67 | - LightBG: similar to Linux but swaps dark/light colors to be more readable |
|
68 | 68 | in light background terminals. |
|
69 | 69 | |
|
70 | 70 | - Neutral: a neutral color scheme that should be readable on both light and |
|
71 | 71 | dark background |
|
72 | 72 | |
|
73 | 73 | You can implement other color schemes easily, the syntax is fairly |
|
74 | 74 | self-explanatory. Please send back new schemes you develop to the author for |
|
75 | 75 | possible inclusion in future releases. |
|
76 | 76 | |
|
77 | 77 | Inheritance diagram: |
|
78 | 78 | |
|
79 | 79 | .. inheritance-diagram:: IPython.core.ultratb |
|
80 | 80 | :parts: 3 |
|
81 | 81 | """ |
|
82 | 82 | |
|
83 | 83 | #***************************************************************************** |
|
84 | 84 | # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu> |
|
85 | 85 | # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu> |
|
86 | 86 | # |
|
87 | 87 | # Distributed under the terms of the BSD License. The full license is in |
|
88 | 88 | # the file COPYING, distributed as part of this software. |
|
89 | 89 | #***************************************************************************** |
|
90 | 90 | |
|
91 | 91 | |
|
92 | 92 | import dis |
|
93 | 93 | import inspect |
|
94 | 94 | import keyword |
|
95 | 95 | import linecache |
|
96 | 96 | import os |
|
97 | 97 | import pydoc |
|
98 | 98 | import re |
|
99 | 99 | import sys |
|
100 | 100 | import time |
|
101 | 101 | import tokenize |
|
102 | 102 | import traceback |
|
103 | 103 | |
|
104 | 104 | try: # Python 2 |
|
105 | 105 | generate_tokens = tokenize.generate_tokens |
|
106 | 106 | except AttributeError: # Python 3 |
|
107 | 107 | generate_tokens = tokenize.tokenize |
|
108 | 108 | |
|
109 | 109 | # For purposes of monkeypatching inspect to fix a bug in it. |
|
110 | 110 | from inspect import getsourcefile, getfile, getmodule, \ |
|
111 | 111 | ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode |
|
112 | 112 | |
|
113 | 113 | # IPython's own modules |
|
114 | 114 | from IPython import get_ipython |
|
115 | 115 | from IPython.core import debugger |
|
116 | 116 | from IPython.core.display_trap import DisplayTrap |
|
117 | 117 | from IPython.core.excolors import exception_colors |
|
118 | 118 | from IPython.utils import PyColorize |
|
119 | 119 | from IPython.utils import path as util_path |
|
120 | 120 | from IPython.utils import py3compat |
|
121 | 121 | from IPython.utils.data import uniq_stable |
|
122 | 122 | from IPython.utils.terminal import get_terminal_size |
|
123 | 123 | |
|
124 | 124 | from logging import info, error, debug |
|
125 | 125 | |
|
126 | 126 | from importlib.util import source_from_cache |
|
127 | 127 | |
|
128 | 128 | import IPython.utils.colorable as colorable |
|
129 | 129 | |
|
130 | 130 | # Globals |
|
131 | 131 | # amount of space to put line numbers before verbose tracebacks |
|
132 | 132 | INDENT_SIZE = 8 |
|
133 | 133 | |
|
134 | 134 | # Default color scheme. This is used, for example, by the traceback |
|
135 | 135 | # formatter. When running in an actual IPython instance, the user's rc.colors |
|
136 | 136 | # value is used, but having a module global makes this functionality available |
|
137 | 137 | # to users of ultratb who are NOT running inside ipython. |
|
138 | 138 | DEFAULT_SCHEME = 'NoColor' |
|
139 | 139 | |
|
140 | 140 | |
|
141 | 141 | # Number of frame above which we are likely to have a recursion and will |
|
142 | 142 | # **attempt** to detect it. Made modifiable mostly to speedup test suite |
|
143 | 143 | # as detecting recursion is one of our slowest test |
|
144 | 144 | _FRAME_RECURSION_LIMIT = 500 |
|
145 | 145 | |
|
146 | 146 | # --------------------------------------------------------------------------- |
|
147 | 147 | # Code begins |
|
148 | 148 | |
|
149 | 149 | # Utility functions |
|
150 | 150 | def inspect_error(): |
|
151 | 151 | """Print a message about internal inspect errors. |
|
152 | 152 | |
|
153 | 153 | These are unfortunately quite common.""" |
|
154 | 154 | |
|
155 | 155 | error('Internal Python error in the inspect module.\n' |
|
156 | 156 | 'Below is the traceback from this internal error.\n') |
|
157 | 157 | |
|
158 | 158 | |
|
159 | 159 | # This function is a monkeypatch we apply to the Python inspect module. We have |
|
160 | 160 | # now found when it's needed (see discussion on issue gh-1456), and we have a |
|
161 | 161 | # test case (IPython.core.tests.test_ultratb.ChangedPyFileTest) that fails if |
|
162 | 162 | # the monkeypatch is not applied. TK, Aug 2012. |
|
163 | 163 | def findsource(object): |
|
164 | 164 | """Return the entire source file and starting line number for an object. |
|
165 | 165 | |
|
166 | 166 | The argument may be a module, class, method, function, traceback, frame, |
|
167 | 167 | or code object. The source code is returned as a list of all the lines |
|
168 | 168 | in the file and the line number indexes a line in that list. An IOError |
|
169 | 169 | is raised if the source code cannot be retrieved. |
|
170 | 170 | |
|
171 | 171 | FIXED version with which we monkeypatch the stdlib to work around a bug.""" |
|
172 | 172 | |
|
173 | 173 | file = getsourcefile(object) or getfile(object) |
|
174 | 174 | # If the object is a frame, then trying to get the globals dict from its |
|
175 | 175 | # module won't work. Instead, the frame object itself has the globals |
|
176 | 176 | # dictionary. |
|
177 | 177 | globals_dict = None |
|
178 | 178 | if inspect.isframe(object): |
|
179 | 179 | # XXX: can this ever be false? |
|
180 | 180 | globals_dict = object.f_globals |
|
181 | 181 | else: |
|
182 | 182 | module = getmodule(object, file) |
|
183 | 183 | if module: |
|
184 | 184 | globals_dict = module.__dict__ |
|
185 | 185 | lines = linecache.getlines(file, globals_dict) |
|
186 | 186 | if not lines: |
|
187 | 187 | raise IOError('could not get source code') |
|
188 | 188 | |
|
189 | 189 | if ismodule(object): |
|
190 | 190 | return lines, 0 |
|
191 | 191 | |
|
192 | 192 | if isclass(object): |
|
193 | 193 | name = object.__name__ |
|
194 | 194 | pat = re.compile(r'^(\s*)class\s*' + name + r'\b') |
|
195 | 195 | # make some effort to find the best matching class definition: |
|
196 | 196 | # use the one with the least indentation, which is the one |
|
197 | 197 | # that's most probably not inside a function definition. |
|
198 | 198 | candidates = [] |
|
199 | 199 | for i, line in enumerate(lines): |
|
200 | 200 | match = pat.match(line) |
|
201 | 201 | if match: |
|
202 | 202 | # if it's at toplevel, it's already the best one |
|
203 | 203 | if line[0] == 'c': |
|
204 | 204 | return lines, i |
|
205 | 205 | # else add whitespace to candidate list |
|
206 | 206 | candidates.append((match.group(1), i)) |
|
207 | 207 | if candidates: |
|
208 | 208 | # this will sort by whitespace, and by line number, |
|
209 | 209 | # less whitespace first |
|
210 | 210 | candidates.sort() |
|
211 | 211 | return lines, candidates[0][1] |
|
212 | 212 | else: |
|
213 | 213 | raise IOError('could not find class definition') |
|
214 | 214 | |
|
215 | 215 | if ismethod(object): |
|
216 | 216 | object = object.__func__ |
|
217 | 217 | if isfunction(object): |
|
218 | 218 | object = object.__code__ |
|
219 | 219 | if istraceback(object): |
|
220 | 220 | object = object.tb_frame |
|
221 | 221 | if isframe(object): |
|
222 | 222 | object = object.f_code |
|
223 | 223 | if iscode(object): |
|
224 | 224 | if not hasattr(object, 'co_firstlineno'): |
|
225 | 225 | raise IOError('could not find function definition') |
|
226 | 226 | pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)') |
|
227 | 227 | pmatch = pat.match |
|
228 | 228 | # fperez - fix: sometimes, co_firstlineno can give a number larger than |
|
229 | 229 | # the length of lines, which causes an error. Safeguard against that. |
|
230 | 230 | lnum = min(object.co_firstlineno, len(lines)) - 1 |
|
231 | 231 | while lnum > 0: |
|
232 | 232 | if pmatch(lines[lnum]): |
|
233 | 233 | break |
|
234 | 234 | lnum -= 1 |
|
235 | 235 | |
|
236 | 236 | return lines, lnum |
|
237 | 237 | raise IOError('could not find code object') |
|
238 | 238 | |
|
239 | 239 | |
|
240 | 240 | # This is a patched version of inspect.getargs that applies the (unmerged) |
|
241 | 241 | # patch for http://bugs.python.org/issue14611 by Stefano Taschini. This fixes |
|
242 | 242 | # https://github.com/ipython/ipython/issues/8205 and |
|
243 | 243 | # https://github.com/ipython/ipython/issues/8293 |
|
244 | 244 | def getargs(co): |
|
245 | 245 | """Get information about the arguments accepted by a code object. |
|
246 | 246 | |
|
247 | 247 | Three things are returned: (args, varargs, varkw), where 'args' is |
|
248 | 248 | a list of argument names (possibly containing nested lists), and |
|
249 | 249 | 'varargs' and 'varkw' are the names of the * and ** arguments or None.""" |
|
250 | 250 | if not iscode(co): |
|
251 | 251 | raise TypeError('{!r} is not a code object'.format(co)) |
|
252 | 252 | |
|
253 | 253 | nargs = co.co_argcount |
|
254 | 254 | names = co.co_varnames |
|
255 | 255 | args = list(names[:nargs]) |
|
256 | 256 | step = 0 |
|
257 | 257 | |
|
258 | 258 | # The following acrobatics are for anonymous (tuple) arguments. |
|
259 | 259 | for i in range(nargs): |
|
260 | 260 | if args[i][:1] in ('', '.'): |
|
261 | 261 | stack, remain, count = [], [], [] |
|
262 | 262 | while step < len(co.co_code): |
|
263 | 263 | op = ord(co.co_code[step]) |
|
264 | 264 | step = step + 1 |
|
265 | 265 | if op >= dis.HAVE_ARGUMENT: |
|
266 | 266 | opname = dis.opname[op] |
|
267 | 267 | value = ord(co.co_code[step]) + ord(co.co_code[step+1])*256 |
|
268 | 268 | step = step + 2 |
|
269 | 269 | if opname in ('UNPACK_TUPLE', 'UNPACK_SEQUENCE'): |
|
270 | 270 | remain.append(value) |
|
271 | 271 | count.append(value) |
|
272 | 272 | elif opname in ('STORE_FAST', 'STORE_DEREF'): |
|
273 | 273 | if op in dis.haslocal: |
|
274 | 274 | stack.append(co.co_varnames[value]) |
|
275 | 275 | elif op in dis.hasfree: |
|
276 | 276 | stack.append((co.co_cellvars + co.co_freevars)[value]) |
|
277 | 277 | # Special case for sublists of length 1: def foo((bar)) |
|
278 | 278 | # doesn't generate the UNPACK_TUPLE bytecode, so if |
|
279 | 279 | # `remain` is empty here, we have such a sublist. |
|
280 | 280 | if not remain: |
|
281 | 281 | stack[0] = [stack[0]] |
|
282 | 282 | break |
|
283 | 283 | else: |
|
284 | 284 | remain[-1] = remain[-1] - 1 |
|
285 | 285 | while remain[-1] == 0: |
|
286 | 286 | remain.pop() |
|
287 | 287 | size = count.pop() |
|
288 | 288 | stack[-size:] = [stack[-size:]] |
|
289 | 289 | if not remain: |
|
290 | 290 | break |
|
291 | 291 | remain[-1] = remain[-1] - 1 |
|
292 | 292 | if not remain: |
|
293 | 293 | break |
|
294 | 294 | args[i] = stack[0] |
|
295 | 295 | |
|
296 | 296 | varargs = None |
|
297 | 297 | if co.co_flags & inspect.CO_VARARGS: |
|
298 | 298 | varargs = co.co_varnames[nargs] |
|
299 | 299 | nargs = nargs + 1 |
|
300 | 300 | varkw = None |
|
301 | 301 | if co.co_flags & inspect.CO_VARKEYWORDS: |
|
302 | 302 | varkw = co.co_varnames[nargs] |
|
303 | 303 | return inspect.Arguments(args, varargs, varkw) |
|
304 | 304 | |
|
305 | 305 | |
|
306 | 306 | # Monkeypatch inspect to apply our bugfix. |
|
307 | 307 | def with_patch_inspect(f): |
|
308 | 308 | """ |
|
309 | 309 | Deprecated since IPython 6.0 |
|
310 | 310 | decorator for monkeypatching inspect.findsource |
|
311 | 311 | """ |
|
312 | 312 | |
|
313 | 313 | def wrapped(*args, **kwargs): |
|
314 | 314 | save_findsource = inspect.findsource |
|
315 | 315 | save_getargs = inspect.getargs |
|
316 | 316 | inspect.findsource = findsource |
|
317 | 317 | inspect.getargs = getargs |
|
318 | 318 | try: |
|
319 | 319 | return f(*args, **kwargs) |
|
320 | 320 | finally: |
|
321 | 321 | inspect.findsource = save_findsource |
|
322 | 322 | inspect.getargs = save_getargs |
|
323 | 323 | |
|
324 | 324 | return wrapped |
|
325 | 325 | |
|
326 | 326 | |
|
327 | 327 | def fix_frame_records_filenames(records): |
|
328 | 328 | """Try to fix the filenames in each record from inspect.getinnerframes(). |
|
329 | 329 | |
|
330 | 330 | Particularly, modules loaded from within zip files have useless filenames |
|
331 | 331 | attached to their code object, and inspect.getinnerframes() just uses it. |
|
332 | 332 | """ |
|
333 | 333 | fixed_records = [] |
|
334 | 334 | for frame, filename, line_no, func_name, lines, index in records: |
|
335 | 335 | # Look inside the frame's globals dictionary for __file__, |
|
336 | 336 | # which should be better. However, keep Cython filenames since |
|
337 | 337 | # we prefer the source filenames over the compiled .so file. |
|
338 | 338 | if not filename.endswith(('.pyx', '.pxd', '.pxi')): |
|
339 | 339 | better_fn = frame.f_globals.get('__file__', None) |
|
340 | 340 | if isinstance(better_fn, str): |
|
341 | 341 | # Check the type just in case someone did something weird with |
|
342 | 342 | # __file__. It might also be None if the error occurred during |
|
343 | 343 | # import. |
|
344 | 344 | filename = better_fn |
|
345 | 345 | fixed_records.append((frame, filename, line_no, func_name, lines, index)) |
|
346 | 346 | return fixed_records |
|
347 | 347 | |
|
348 | 348 | |
|
349 | 349 | @with_patch_inspect |
|
350 | 350 | def _fixed_getinnerframes(etb, context=1, tb_offset=0): |
|
351 | 351 | LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5 |
|
352 | 352 | |
|
353 | 353 | records = fix_frame_records_filenames(inspect.getinnerframes(etb, context)) |
|
354 | 354 | # If the error is at the console, don't build any context, since it would |
|
355 | 355 | # otherwise produce 5 blank lines printed out (there is no file at the |
|
356 | 356 | # console) |
|
357 | 357 | rec_check = records[tb_offset:] |
|
358 | 358 | try: |
|
359 | 359 | rname = rec_check[0][1] |
|
360 | 360 | if rname == '<ipython console>' or rname.endswith('<string>'): |
|
361 | 361 | return rec_check |
|
362 | 362 | except IndexError: |
|
363 | 363 | pass |
|
364 | 364 | |
|
365 | 365 | aux = traceback.extract_tb(etb) |
|
366 | 366 | assert len(records) == len(aux) |
|
367 | 367 | for i, (file, lnum, _, _) in enumerate(aux): |
|
368 | 368 | maybeStart = lnum - 1 - context // 2 |
|
369 | 369 | start = max(maybeStart, 0) |
|
370 | 370 | end = start + context |
|
371 | 371 | lines = linecache.getlines(file)[start:end] |
|
372 | 372 | buf = list(records[i]) |
|
373 | 373 | buf[LNUM_POS] = lnum |
|
374 | 374 | buf[INDEX_POS] = lnum - 1 - start |
|
375 | 375 | buf[LINES_POS] = lines |
|
376 | 376 | records[i] = tuple(buf) |
|
377 | 377 | return records[tb_offset:] |
|
378 | 378 | |
|
379 | 379 | # Helper function -- largely belongs to VerboseTB, but we need the same |
|
380 | 380 | # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they |
|
381 | 381 | # can be recognized properly by ipython.el's py-traceback-line-re |
|
382 | 382 | # (SyntaxErrors have to be treated specially because they have no traceback) |
|
383 | 383 | |
|
384 | 384 | |
|
385 | 385 | def _format_traceback_lines(lnum, index, lines, Colors, lvals, _line_format): |
|
386 | 386 | """ |
|
387 | 387 | Format tracebacks lines with pointing arrow, leading numbers... |
|
388 | 388 | |
|
389 | 389 | Parameters |
|
390 | 390 | ========== |
|
391 | 391 | |
|
392 | 392 | lnum: int |
|
393 | 393 | index: int |
|
394 | 394 | lines: list[string] |
|
395 | 395 | Colors: |
|
396 | 396 | ColorScheme used. |
|
397 | 397 | lvals: bytes |
|
398 | 398 | Values of local variables, already colored, to inject just after the error line. |
|
399 | 399 | _line_format: f (str) -> (str, bool) |
|
400 | 400 | return (colorized version of str, failure to do so) |
|
401 | 401 | """ |
|
402 | 402 | numbers_width = INDENT_SIZE - 1 |
|
403 | 403 | res = [] |
|
404 | 404 | |
|
405 | 405 | for i,line in enumerate(lines, lnum-index): |
|
406 | 406 | line = py3compat.cast_unicode(line) |
|
407 | 407 | |
|
408 | 408 | new_line, err = _line_format(line, 'str') |
|
409 | 409 | if not err: |
|
410 | 410 | line = new_line |
|
411 | 411 | |
|
412 | 412 | if i == lnum: |
|
413 | 413 | # This is the line with the error |
|
414 | 414 | pad = numbers_width - len(str(i)) |
|
415 | 415 | num = '%s%s' % (debugger.make_arrow(pad), str(lnum)) |
|
416 | 416 | line = '%s%s%s %s%s' % (Colors.linenoEm, num, |
|
417 | 417 | Colors.line, line, Colors.Normal) |
|
418 | 418 | else: |
|
419 | 419 | num = '%*s' % (numbers_width, i) |
|
420 | 420 | line = '%s%s%s %s' % (Colors.lineno, num, |
|
421 | 421 | Colors.Normal, line) |
|
422 | 422 | |
|
423 | 423 | res.append(line) |
|
424 | 424 | if lvals and i == lnum: |
|
425 | 425 | res.append(lvals + '\n') |
|
426 | 426 | return res |
|
427 | 427 | |
|
428 | 428 | def is_recursion_error(etype, value, records): |
|
429 | 429 | try: |
|
430 | 430 | # RecursionError is new in Python 3.5 |
|
431 | 431 | recursion_error_type = RecursionError |
|
432 | 432 | except NameError: |
|
433 | 433 | recursion_error_type = RuntimeError |
|
434 | 434 | |
|
435 | 435 | # The default recursion limit is 1000, but some of that will be taken up |
|
436 | 436 | # by stack frames in IPython itself. >500 frames probably indicates |
|
437 | 437 | # a recursion error. |
|
438 | 438 | return (etype is recursion_error_type) \ |
|
439 | 439 | and "recursion" in str(value).lower() \ |
|
440 | 440 | and len(records) > _FRAME_RECURSION_LIMIT |
|
441 | 441 | |
|
442 | 442 | def find_recursion(etype, value, records): |
|
443 | 443 | """Identify the repeating stack frames from a RecursionError traceback |
|
444 | 444 | |
|
445 | 445 | 'records' is a list as returned by VerboseTB.get_records() |
|
446 | 446 | |
|
447 | 447 | Returns (last_unique, repeat_length) |
|
448 | 448 | """ |
|
449 | 449 | # This involves a bit of guesswork - we want to show enough of the traceback |
|
450 | 450 | # to indicate where the recursion is occurring. We guess that the innermost |
|
451 | 451 | # quarter of the traceback (250 frames by default) is repeats, and find the |
|
452 | 452 | # first frame (from in to out) that looks different. |
|
453 | 453 | if not is_recursion_error(etype, value, records): |
|
454 | 454 | return len(records), 0 |
|
455 | 455 | |
|
456 | 456 | # Select filename, lineno, func_name to track frames with |
|
457 | 457 | records = [r[1:4] for r in records] |
|
458 | 458 | inner_frames = records[-(len(records)//4):] |
|
459 | 459 | frames_repeated = set(inner_frames) |
|
460 | 460 | |
|
461 | 461 | last_seen_at = {} |
|
462 | 462 | longest_repeat = 0 |
|
463 | 463 | i = len(records) |
|
464 | 464 | for frame in reversed(records): |
|
465 | 465 | i -= 1 |
|
466 | 466 | if frame not in frames_repeated: |
|
467 | 467 | last_unique = i |
|
468 | 468 | break |
|
469 | 469 | |
|
470 | 470 | if frame in last_seen_at: |
|
471 | 471 | distance = last_seen_at[frame] - i |
|
472 | 472 | longest_repeat = max(longest_repeat, distance) |
|
473 | 473 | |
|
474 | 474 | last_seen_at[frame] = i |
|
475 | 475 | else: |
|
476 | 476 | last_unique = 0 # The whole traceback was recursion |
|
477 | 477 | |
|
478 | 478 | return last_unique, longest_repeat |
|
479 | 479 | |
|
480 | 480 | #--------------------------------------------------------------------------- |
|
481 | 481 | # Module classes |
|
482 | 482 | class TBTools(colorable.Colorable): |
|
483 | 483 | """Basic tools used by all traceback printer classes.""" |
|
484 | 484 | |
|
485 | 485 | # Number of frames to skip when reporting tracebacks |
|
486 | 486 | tb_offset = 0 |
|
487 | 487 | |
|
488 | 488 | def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None): |
|
489 | 489 | # Whether to call the interactive pdb debugger after printing |
|
490 | 490 | # tracebacks or not |
|
491 | 491 | super(TBTools, self).__init__(parent=parent, config=config) |
|
492 | 492 | self.call_pdb = call_pdb |
|
493 | 493 | |
|
494 | 494 | # Output stream to write to. Note that we store the original value in |
|
495 | 495 | # a private attribute and then make the public ostream a property, so |
|
496 | 496 | # that we can delay accessing sys.stdout until runtime. The way |
|
497 | 497 | # things are written now, the sys.stdout object is dynamically managed |
|
498 | 498 | # so a reference to it should NEVER be stored statically. This |
|
499 | 499 | # property approach confines this detail to a single location, and all |
|
500 | 500 | # subclasses can simply access self.ostream for writing. |
|
501 | 501 | self._ostream = ostream |
|
502 | 502 | |
|
503 | 503 | # Create color table |
|
504 | 504 | self.color_scheme_table = exception_colors() |
|
505 | 505 | |
|
506 | 506 | self.set_colors(color_scheme) |
|
507 | 507 | self.old_scheme = color_scheme # save initial value for toggles |
|
508 | 508 | |
|
509 | 509 | if call_pdb: |
|
510 | 510 | self.pdb = debugger.Pdb() |
|
511 | 511 | else: |
|
512 | 512 | self.pdb = None |
|
513 | 513 | |
|
514 | 514 | def _get_ostream(self): |
|
515 | 515 | """Output stream that exceptions are written to. |
|
516 | 516 | |
|
517 | 517 | Valid values are: |
|
518 | 518 | |
|
519 | 519 | - None: the default, which means that IPython will dynamically resolve |
|
520 | 520 | to sys.stdout. This ensures compatibility with most tools, including |
|
521 | 521 | Windows (where plain stdout doesn't recognize ANSI escapes). |
|
522 | 522 | |
|
523 | 523 | - Any object with 'write' and 'flush' attributes. |
|
524 | 524 | """ |
|
525 | 525 | return sys.stdout if self._ostream is None else self._ostream |
|
526 | 526 | |
|
527 | 527 | def _set_ostream(self, val): |
|
528 | 528 | assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush')) |
|
529 | 529 | self._ostream = val |
|
530 | 530 | |
|
531 | 531 | ostream = property(_get_ostream, _set_ostream) |
|
532 | 532 | |
|
533 | def get_parts_of_chained_exception(self, evalue): | |
|
534 | def get_chained_exception(exception_value): | |
|
535 | cause = getattr(exception_value, '__cause__', None) | |
|
536 | if cause: | |
|
537 | return cause | |
|
538 | if getattr(exception_value, '__suppress_context__', False): | |
|
539 | return None | |
|
540 | return getattr(exception_value, '__context__', None) | |
|
541 | ||
|
542 | chained_evalue = get_chained_exception(evalue) | |
|
543 | ||
|
544 | if chained_evalue: | |
|
545 | return chained_evalue.__class__, chained_evalue, chained_evalue.__traceback__ | |
|
546 | ||
|
547 | def prepare_chained_exception_message(self, cause): | |
|
548 | direct_cause = "\nThe above exception was the direct cause of the following exception:\n" | |
|
549 | exception_during_handling = "\nDuring handling of the above exception, another exception occurred:\n" | |
|
550 | ||
|
551 | if cause: | |
|
552 | message = [[direct_cause]] | |
|
553 | else: | |
|
554 | message = [[exception_during_handling]] | |
|
555 | return message | |
|
556 | ||
|
533 | 557 | def set_colors(self, *args, **kw): |
|
534 | 558 | """Shorthand access to the color table scheme selector method.""" |
|
535 | 559 | |
|
536 | 560 | # Set own color table |
|
537 | 561 | self.color_scheme_table.set_active_scheme(*args, **kw) |
|
538 | 562 | # for convenience, set Colors to the active scheme |
|
539 | 563 | self.Colors = self.color_scheme_table.active_colors |
|
540 | 564 | # Also set colors of debugger |
|
541 | 565 | if hasattr(self, 'pdb') and self.pdb is not None: |
|
542 | 566 | self.pdb.set_colors(*args, **kw) |
|
543 | 567 | |
|
544 | 568 | def color_toggle(self): |
|
545 | 569 | """Toggle between the currently active color scheme and NoColor.""" |
|
546 | 570 | |
|
547 | 571 | if self.color_scheme_table.active_scheme_name == 'NoColor': |
|
548 | 572 | self.color_scheme_table.set_active_scheme(self.old_scheme) |
|
549 | 573 | self.Colors = self.color_scheme_table.active_colors |
|
550 | 574 | else: |
|
551 | 575 | self.old_scheme = self.color_scheme_table.active_scheme_name |
|
552 | 576 | self.color_scheme_table.set_active_scheme('NoColor') |
|
553 | 577 | self.Colors = self.color_scheme_table.active_colors |
|
554 | 578 | |
|
555 | 579 | def stb2text(self, stb): |
|
556 | 580 | """Convert a structured traceback (a list) to a string.""" |
|
557 | 581 | return '\n'.join(stb) |
|
558 | 582 | |
|
559 | 583 | def text(self, etype, value, tb, tb_offset=None, context=5): |
|
560 | 584 | """Return formatted traceback. |
|
561 | 585 | |
|
562 | 586 | Subclasses may override this if they add extra arguments. |
|
563 | 587 | """ |
|
564 | 588 | tb_list = self.structured_traceback(etype, value, tb, |
|
565 | 589 | tb_offset, context) |
|
566 | 590 | return self.stb2text(tb_list) |
|
567 | 591 | |
|
568 | 592 | def structured_traceback(self, etype, evalue, tb, tb_offset=None, |
|
569 | 593 | context=5, mode=None): |
|
570 | 594 | """Return a list of traceback frames. |
|
571 | 595 | |
|
572 | 596 | Must be implemented by each class. |
|
573 | 597 | """ |
|
574 | 598 | raise NotImplementedError() |
|
575 | 599 | |
|
576 | 600 | |
|
577 | 601 | #--------------------------------------------------------------------------- |
|
578 | 602 | class ListTB(TBTools): |
|
579 | 603 | """Print traceback information from a traceback list, with optional color. |
|
580 | 604 | |
|
581 | 605 | Calling requires 3 arguments: (etype, evalue, elist) |
|
582 | 606 | as would be obtained by:: |
|
583 | 607 | |
|
584 | 608 | etype, evalue, tb = sys.exc_info() |
|
585 | 609 | if tb: |
|
586 | 610 | elist = traceback.extract_tb(tb) |
|
587 | 611 | else: |
|
588 | 612 | elist = None |
|
589 | 613 | |
|
590 | 614 | It can thus be used by programs which need to process the traceback before |
|
591 | 615 | printing (such as console replacements based on the code module from the |
|
592 | 616 | standard library). |
|
593 | 617 | |
|
594 | 618 | Because they are meant to be called without a full traceback (only a |
|
595 | 619 | list), instances of this class can't call the interactive pdb debugger.""" |
|
596 | 620 | |
|
597 | 621 | def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None): |
|
598 | 622 | TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, |
|
599 | 623 | ostream=ostream, parent=parent,config=config) |
|
600 | 624 | |
|
601 | 625 | def __call__(self, etype, value, elist): |
|
602 | 626 | self.ostream.flush() |
|
603 | 627 | self.ostream.write(self.text(etype, value, elist)) |
|
604 | 628 | self.ostream.write('\n') |
|
605 | 629 | |
|
606 |
def structured_traceback(self, etype, value, e |
|
|
630 | def structured_traceback(self, etype, evalue, etb=None, tb_offset=None, | |
|
607 | 631 | context=5): |
|
608 | 632 | """Return a color formatted string with the traceback info. |
|
609 | 633 | |
|
610 | 634 | Parameters |
|
611 | 635 | ---------- |
|
612 | 636 | etype : exception type |
|
613 | 637 | Type of the exception raised. |
|
614 | 638 | |
|
615 | value : object | |
|
639 | evalue : object | |
|
616 | 640 | Data stored in the exception |
|
617 | 641 | |
|
618 |
e |
|
|
619 | List of frames, see class docstring for details. | |
|
642 | etb : object | |
|
643 | If list: List of frames, see class docstring for details. | |
|
644 | If Traceback: Traceback of the exception. | |
|
620 | 645 | |
|
621 | 646 | tb_offset : int, optional |
|
622 | 647 | Number of frames in the traceback to skip. If not given, the |
|
623 | instance value is used (set in constructor). | |
|
648 | instance evalue is used (set in constructor). | |
|
624 | 649 | |
|
625 | 650 | context : int, optional |
|
626 | 651 | Number of lines of context information to print. |
|
627 | 652 | |
|
628 | 653 | Returns |
|
629 | 654 | ------- |
|
630 | 655 | String with formatted exception. |
|
631 | 656 | """ |
|
657 | # This is a workaround to get chained_exc_ids in recursive calls | |
|
658 | # etb should not be a tuple if structured_traceback is not recursive | |
|
659 | if isinstance(etb, tuple): | |
|
660 | etb, chained_exc_ids = etb | |
|
661 | else: | |
|
662 | chained_exc_ids = set() | |
|
663 | ||
|
664 | if isinstance(etb, list): | |
|
665 | elist = etb | |
|
666 | elif etb is not None: | |
|
667 | elist = self._extract_tb(etb) | |
|
668 | else: | |
|
669 | elist = [] | |
|
632 | 670 | tb_offset = self.tb_offset if tb_offset is None else tb_offset |
|
633 | 671 | Colors = self.Colors |
|
634 | 672 | out_list = [] |
|
635 | 673 | if elist: |
|
636 | 674 | |
|
637 | 675 | if tb_offset and len(elist) > tb_offset: |
|
638 | 676 | elist = elist[tb_offset:] |
|
639 | 677 | |
|
640 | 678 | out_list.append('Traceback %s(most recent call last)%s:' % |
|
641 | 679 | (Colors.normalEm, Colors.Normal) + '\n') |
|
642 | 680 | out_list.extend(self._format_list(elist)) |
|
643 | 681 | # The exception info should be a single entry in the list. |
|
644 | lines = ''.join(self._format_exception_only(etype, value)) | |
|
682 | lines = ''.join(self._format_exception_only(etype, evalue)) | |
|
645 | 683 | out_list.append(lines) |
|
646 | 684 | |
|
685 | exception = self.get_parts_of_chained_exception(evalue) | |
|
686 | ||
|
687 | if exception and not id(exception[1]) in chained_exc_ids: | |
|
688 | chained_exception_message = self.prepare_chained_exception_message( | |
|
689 | evalue.__cause__)[0] | |
|
690 | etype, evalue, etb = exception | |
|
691 | # Trace exception to avoid infinite 'cause' loop | |
|
692 | chained_exc_ids.add(id(exception[1])) | |
|
693 | chained_exceptions_tb_offset = 0 | |
|
694 | out_list = ( | |
|
695 | self.structured_traceback( | |
|
696 | etype, evalue, (etb, chained_exc_ids), | |
|
697 | chained_exceptions_tb_offset, context) | |
|
698 | + chained_exception_message | |
|
699 | + out_list) | |
|
700 | ||
|
647 | 701 | return out_list |
|
648 | 702 | |
|
649 | 703 | def _format_list(self, extracted_list): |
|
650 | 704 | """Format a list of traceback entry tuples for printing. |
|
651 | 705 | |
|
652 | 706 | Given a list of tuples as returned by extract_tb() or |
|
653 | 707 | extract_stack(), return a list of strings ready for printing. |
|
654 | 708 | Each string in the resulting list corresponds to the item with the |
|
655 | 709 | same index in the argument list. Each string ends in a newline; |
|
656 | 710 | the strings may contain internal newlines as well, for those items |
|
657 | 711 | whose source text line is not None. |
|
658 | 712 | |
|
659 | 713 | Lifted almost verbatim from traceback.py |
|
660 | 714 | """ |
|
661 | 715 | |
|
662 | 716 | Colors = self.Colors |
|
663 | 717 | list = [] |
|
664 | 718 | for filename, lineno, name, line in extracted_list[:-1]: |
|
665 | 719 | item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \ |
|
666 | 720 | (Colors.filename, filename, Colors.Normal, |
|
667 | 721 | Colors.lineno, lineno, Colors.Normal, |
|
668 | 722 | Colors.name, name, Colors.Normal) |
|
669 | 723 | if line: |
|
670 | 724 | item += ' %s\n' % line.strip() |
|
671 | 725 | list.append(item) |
|
672 | 726 | # Emphasize the last entry |
|
673 | 727 | filename, lineno, name, line = extracted_list[-1] |
|
674 | 728 | item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \ |
|
675 | 729 | (Colors.normalEm, |
|
676 | 730 | Colors.filenameEm, filename, Colors.normalEm, |
|
677 | 731 | Colors.linenoEm, lineno, Colors.normalEm, |
|
678 | 732 | Colors.nameEm, name, Colors.normalEm, |
|
679 | 733 | Colors.Normal) |
|
680 | 734 | if line: |
|
681 | 735 | item += '%s %s%s\n' % (Colors.line, line.strip(), |
|
682 | 736 | Colors.Normal) |
|
683 | 737 | list.append(item) |
|
684 | 738 | return list |
|
685 | 739 | |
|
686 | 740 | def _format_exception_only(self, etype, value): |
|
687 | 741 | """Format the exception part of a traceback. |
|
688 | 742 | |
|
689 | 743 | The arguments are the exception type and value such as given by |
|
690 | 744 | sys.exc_info()[:2]. The return value is a list of strings, each ending |
|
691 | 745 | in a newline. Normally, the list contains a single string; however, |
|
692 | 746 | for SyntaxError exceptions, it contains several lines that (when |
|
693 | 747 | printed) display detailed information about where the syntax error |
|
694 | 748 | occurred. The message indicating which exception occurred is the |
|
695 | 749 | always last string in the list. |
|
696 | 750 | |
|
697 | 751 | Also lifted nearly verbatim from traceback.py |
|
698 | 752 | """ |
|
699 | 753 | have_filedata = False |
|
700 | 754 | Colors = self.Colors |
|
701 | 755 | list = [] |
|
702 | 756 | stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal) |
|
703 | 757 | if value is None: |
|
704 | 758 | # Not sure if this can still happen in Python 2.6 and above |
|
705 | 759 | list.append(stype + '\n') |
|
706 | 760 | else: |
|
707 | 761 | if issubclass(etype, SyntaxError): |
|
708 | 762 | have_filedata = True |
|
709 | 763 | if not value.filename: value.filename = "<string>" |
|
710 | 764 | if value.lineno: |
|
711 | 765 | lineno = value.lineno |
|
712 | 766 | textline = linecache.getline(value.filename, value.lineno) |
|
713 | 767 | else: |
|
714 | 768 | lineno = 'unknown' |
|
715 | 769 | textline = '' |
|
716 | 770 | list.append('%s File %s"%s"%s, line %s%s%s\n' % \ |
|
717 | 771 | (Colors.normalEm, |
|
718 | 772 | Colors.filenameEm, py3compat.cast_unicode(value.filename), Colors.normalEm, |
|
719 | 773 | Colors.linenoEm, lineno, Colors.Normal )) |
|
720 | 774 | if textline == '': |
|
721 | 775 | textline = py3compat.cast_unicode(value.text, "utf-8") |
|
722 | 776 | |
|
723 | 777 | if textline is not None: |
|
724 | 778 | i = 0 |
|
725 | 779 | while i < len(textline) and textline[i].isspace(): |
|
726 | 780 | i += 1 |
|
727 | 781 | list.append('%s %s%s\n' % (Colors.line, |
|
728 | 782 | textline.strip(), |
|
729 | 783 | Colors.Normal)) |
|
730 | 784 | if value.offset is not None: |
|
731 | 785 | s = ' ' |
|
732 | 786 | for c in textline[i:value.offset - 1]: |
|
733 | 787 | if c.isspace(): |
|
734 | 788 | s += c |
|
735 | 789 | else: |
|
736 | 790 | s += ' ' |
|
737 | 791 | list.append('%s%s^%s\n' % (Colors.caret, s, |
|
738 | 792 | Colors.Normal)) |
|
739 | 793 | |
|
740 | 794 | try: |
|
741 | 795 | s = value.msg |
|
742 | 796 | except Exception: |
|
743 | 797 | s = self._some_str(value) |
|
744 | 798 | if s: |
|
745 | 799 | list.append('%s%s:%s %s\n' % (stype, Colors.excName, |
|
746 | 800 | Colors.Normal, s)) |
|
747 | 801 | else: |
|
748 | 802 | list.append('%s\n' % stype) |
|
749 | 803 | |
|
750 | 804 | # sync with user hooks |
|
751 | 805 | if have_filedata: |
|
752 | 806 | ipinst = get_ipython() |
|
753 | 807 | if ipinst is not None: |
|
754 | 808 | ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0) |
|
755 | 809 | |
|
756 | 810 | return list |
|
757 | 811 | |
|
758 | 812 | def get_exception_only(self, etype, value): |
|
759 | 813 | """Only print the exception type and message, without a traceback. |
|
760 | 814 | |
|
761 | 815 | Parameters |
|
762 | 816 | ---------- |
|
763 | 817 | etype : exception type |
|
764 | 818 | value : exception value |
|
765 | 819 | """ |
|
766 |
return ListTB.structured_traceback(self, etype, value |
|
|
820 | return ListTB.structured_traceback(self, etype, value) | |
|
767 | 821 | |
|
768 | 822 | def show_exception_only(self, etype, evalue): |
|
769 | 823 | """Only print the exception type and message, without a traceback. |
|
770 | 824 | |
|
771 | 825 | Parameters |
|
772 | 826 | ---------- |
|
773 | 827 | etype : exception type |
|
774 | 828 | value : exception value |
|
775 | 829 | """ |
|
776 | 830 | # This method needs to use __call__ from *this* class, not the one from |
|
777 | 831 | # a subclass whose signature or behavior may be different |
|
778 | 832 | ostream = self.ostream |
|
779 | 833 | ostream.flush() |
|
780 | 834 | ostream.write('\n'.join(self.get_exception_only(etype, evalue))) |
|
781 | 835 | ostream.flush() |
|
782 | 836 | |
|
783 | 837 | def _some_str(self, value): |
|
784 | 838 | # Lifted from traceback.py |
|
785 | 839 | try: |
|
786 | 840 | return py3compat.cast_unicode(str(value)) |
|
787 | 841 | except: |
|
788 | 842 | return u'<unprintable %s object>' % type(value).__name__ |
|
789 | 843 | |
|
790 | 844 | |
|
791 | 845 | #---------------------------------------------------------------------------- |
|
792 | 846 | class VerboseTB(TBTools): |
|
793 | 847 | """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead |
|
794 | 848 | of HTML. Requires inspect and pydoc. Crazy, man. |
|
795 | 849 | |
|
796 | 850 | Modified version which optionally strips the topmost entries from the |
|
797 | 851 | traceback, to be used with alternate interpreters (because their own code |
|
798 | 852 | would appear in the traceback).""" |
|
799 | 853 | |
|
800 | 854 | def __init__(self, color_scheme='Linux', call_pdb=False, ostream=None, |
|
801 | 855 | tb_offset=0, long_header=False, include_vars=True, |
|
802 | 856 | check_cache=None, debugger_cls = None, |
|
803 | 857 | parent=None, config=None): |
|
804 | 858 | """Specify traceback offset, headers and color scheme. |
|
805 | 859 | |
|
806 | 860 | Define how many frames to drop from the tracebacks. Calling it with |
|
807 | 861 | tb_offset=1 allows use of this handler in interpreters which will have |
|
808 | 862 | their own code at the top of the traceback (VerboseTB will first |
|
809 | 863 | remove that frame before printing the traceback info).""" |
|
810 | 864 | TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, |
|
811 | 865 | ostream=ostream, parent=parent, config=config) |
|
812 | 866 | self.tb_offset = tb_offset |
|
813 | 867 | self.long_header = long_header |
|
814 | 868 | self.include_vars = include_vars |
|
815 | 869 | # By default we use linecache.checkcache, but the user can provide a |
|
816 | 870 | # different check_cache implementation. This is used by the IPython |
|
817 | 871 | # kernel to provide tracebacks for interactive code that is cached, |
|
818 | 872 | # by a compiler instance that flushes the linecache but preserves its |
|
819 | 873 | # own code cache. |
|
820 | 874 | if check_cache is None: |
|
821 | 875 | check_cache = linecache.checkcache |
|
822 | 876 | self.check_cache = check_cache |
|
823 | 877 | |
|
824 | 878 | self.debugger_cls = debugger_cls or debugger.Pdb |
|
825 | 879 | |
|
826 | 880 | def format_records(self, records, last_unique, recursion_repeat): |
|
827 | 881 | """Format the stack frames of the traceback""" |
|
828 | 882 | frames = [] |
|
829 | 883 | for r in records[:last_unique+recursion_repeat+1]: |
|
830 | 884 | #print '*** record:',file,lnum,func,lines,index # dbg |
|
831 | 885 | frames.append(self.format_record(*r)) |
|
832 | 886 | |
|
833 | 887 | if recursion_repeat: |
|
834 | 888 | frames.append('... last %d frames repeated, from the frame below ...\n' % recursion_repeat) |
|
835 | 889 | frames.append(self.format_record(*records[last_unique+recursion_repeat+1])) |
|
836 | 890 | |
|
837 | 891 | return frames |
|
838 | 892 | |
|
839 | 893 | def format_record(self, frame, file, lnum, func, lines, index): |
|
840 | 894 | """Format a single stack frame""" |
|
841 | 895 | Colors = self.Colors # just a shorthand + quicker name lookup |
|
842 | 896 | ColorsNormal = Colors.Normal # used a lot |
|
843 | 897 | col_scheme = self.color_scheme_table.active_scheme_name |
|
844 | 898 | indent = ' ' * INDENT_SIZE |
|
845 | 899 | em_normal = '%s\n%s%s' % (Colors.valEm, indent, ColorsNormal) |
|
846 | 900 | undefined = '%sundefined%s' % (Colors.em, ColorsNormal) |
|
847 | 901 | tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal) |
|
848 | 902 | tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm, |
|
849 | 903 | ColorsNormal) |
|
850 | 904 | tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \ |
|
851 | 905 | (Colors.vName, Colors.valEm, ColorsNormal) |
|
852 | 906 | tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal) |
|
853 | 907 | tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal, |
|
854 | 908 | Colors.vName, ColorsNormal) |
|
855 | 909 | tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal) |
|
856 | 910 | |
|
857 | 911 | if not file: |
|
858 | 912 | file = '?' |
|
859 | 913 | elif file.startswith(str("<")) and file.endswith(str(">")): |
|
860 | 914 | # Not a real filename, no problem... |
|
861 | 915 | pass |
|
862 | 916 | elif not os.path.isabs(file): |
|
863 | 917 | # Try to make the filename absolute by trying all |
|
864 | 918 | # sys.path entries (which is also what linecache does) |
|
865 | 919 | for dirname in sys.path: |
|
866 | 920 | try: |
|
867 | 921 | fullname = os.path.join(dirname, file) |
|
868 | 922 | if os.path.isfile(fullname): |
|
869 | 923 | file = os.path.abspath(fullname) |
|
870 | 924 | break |
|
871 | 925 | except Exception: |
|
872 | 926 | # Just in case that sys.path contains very |
|
873 | 927 | # strange entries... |
|
874 | 928 | pass |
|
875 | 929 | |
|
876 | 930 | file = py3compat.cast_unicode(file, util_path.fs_encoding) |
|
877 | 931 | link = tpl_link % util_path.compress_user(file) |
|
878 | 932 | args, varargs, varkw, locals_ = inspect.getargvalues(frame) |
|
879 | 933 | |
|
880 | 934 | if func == '?': |
|
881 | 935 | call = '' |
|
882 | 936 | elif func == '<module>': |
|
883 | 937 | call = tpl_call % (func, '') |
|
884 | 938 | else: |
|
885 | 939 | # Decide whether to include variable details or not |
|
886 | 940 | var_repr = eqrepr if self.include_vars else nullrepr |
|
887 | 941 | try: |
|
888 | 942 | call = tpl_call % (func, inspect.formatargvalues(args, |
|
889 | 943 | varargs, varkw, |
|
890 | 944 | locals_, formatvalue=var_repr)) |
|
891 | 945 | except KeyError: |
|
892 | 946 | # This happens in situations like errors inside generator |
|
893 | 947 | # expressions, where local variables are listed in the |
|
894 | 948 | # line, but can't be extracted from the frame. I'm not |
|
895 | 949 | # 100% sure this isn't actually a bug in inspect itself, |
|
896 | 950 | # but since there's no info for us to compute with, the |
|
897 | 951 | # best we can do is report the failure and move on. Here |
|
898 | 952 | # we must *not* call any traceback construction again, |
|
899 | 953 | # because that would mess up use of %debug later on. So we |
|
900 | 954 | # simply report the failure and move on. The only |
|
901 | 955 | # limitation will be that this frame won't have locals |
|
902 | 956 | # listed in the call signature. Quite subtle problem... |
|
903 | 957 | # I can't think of a good way to validate this in a unit |
|
904 | 958 | # test, but running a script consisting of: |
|
905 | 959 | # dict( (k,v.strip()) for (k,v) in range(10) ) |
|
906 | 960 | # will illustrate the error, if this exception catch is |
|
907 | 961 | # disabled. |
|
908 | 962 | call = tpl_call_fail % func |
|
909 | 963 | |
|
910 | 964 | # Don't attempt to tokenize binary files. |
|
911 | 965 | if file.endswith(('.so', '.pyd', '.dll')): |
|
912 | 966 | return '%s %s\n' % (link, call) |
|
913 | 967 | |
|
914 | 968 | elif file.endswith(('.pyc', '.pyo')): |
|
915 | 969 | # Look up the corresponding source file. |
|
916 | 970 | try: |
|
917 | 971 | file = source_from_cache(file) |
|
918 | 972 | except ValueError: |
|
919 | 973 | # Failed to get the source file for some reason |
|
920 | 974 | # E.g. https://github.com/ipython/ipython/issues/9486 |
|
921 | 975 | return '%s %s\n' % (link, call) |
|
922 | 976 | |
|
923 | 977 | def linereader(file=file, lnum=[lnum], getline=linecache.getline): |
|
924 | 978 | line = getline(file, lnum[0]) |
|
925 | 979 | lnum[0] += 1 |
|
926 | 980 | return line |
|
927 | 981 | |
|
928 | 982 | # Build the list of names on this line of code where the exception |
|
929 | 983 | # occurred. |
|
930 | 984 | try: |
|
931 | 985 | names = [] |
|
932 | 986 | name_cont = False |
|
933 | 987 | |
|
934 | 988 | for token_type, token, start, end, line in generate_tokens(linereader): |
|
935 | 989 | # build composite names |
|
936 | 990 | if token_type == tokenize.NAME and token not in keyword.kwlist: |
|
937 | 991 | if name_cont: |
|
938 | 992 | # Continuation of a dotted name |
|
939 | 993 | try: |
|
940 | 994 | names[-1].append(token) |
|
941 | 995 | except IndexError: |
|
942 | 996 | names.append([token]) |
|
943 | 997 | name_cont = False |
|
944 | 998 | else: |
|
945 | 999 | # Regular new names. We append everything, the caller |
|
946 | 1000 | # will be responsible for pruning the list later. It's |
|
947 | 1001 | # very tricky to try to prune as we go, b/c composite |
|
948 | 1002 | # names can fool us. The pruning at the end is easy |
|
949 | 1003 | # to do (or the caller can print a list with repeated |
|
950 | 1004 | # names if so desired. |
|
951 | 1005 | names.append([token]) |
|
952 | 1006 | elif token == '.': |
|
953 | 1007 | name_cont = True |
|
954 | 1008 | elif token_type == tokenize.NEWLINE: |
|
955 | 1009 | break |
|
956 | 1010 | |
|
957 | 1011 | except (IndexError, UnicodeDecodeError, SyntaxError): |
|
958 | 1012 | # signals exit of tokenizer |
|
959 | 1013 | # SyntaxError can occur if the file is not actually Python |
|
960 | 1014 | # - see gh-6300 |
|
961 | 1015 | pass |
|
962 | 1016 | except tokenize.TokenError as msg: |
|
963 | 1017 | # Tokenizing may fail for various reasons, many of which are |
|
964 | 1018 | # harmless. (A good example is when the line in question is the |
|
965 | 1019 | # close of a triple-quoted string, cf gh-6864). We don't want to |
|
966 | 1020 | # show this to users, but want make it available for debugging |
|
967 | 1021 | # purposes. |
|
968 | 1022 | _m = ("An unexpected error occurred while tokenizing input\n" |
|
969 | 1023 | "The following traceback may be corrupted or invalid\n" |
|
970 | 1024 | "The error message is: %s\n" % msg) |
|
971 | 1025 | debug(_m) |
|
972 | 1026 | |
|
973 | 1027 | # Join composite names (e.g. "dict.fromkeys") |
|
974 | 1028 | names = ['.'.join(n) for n in names] |
|
975 | 1029 | # prune names list of duplicates, but keep the right order |
|
976 | 1030 | unique_names = uniq_stable(names) |
|
977 | 1031 | |
|
978 | 1032 | # Start loop over vars |
|
979 | 1033 | lvals = '' |
|
980 | 1034 | lvals_list = [] |
|
981 | 1035 | if self.include_vars: |
|
982 | 1036 | for name_full in unique_names: |
|
983 | 1037 | name_base = name_full.split('.', 1)[0] |
|
984 | 1038 | if name_base in frame.f_code.co_varnames: |
|
985 | 1039 | if name_base in locals_: |
|
986 | 1040 | try: |
|
987 | 1041 | value = repr(eval(name_full, locals_)) |
|
988 | 1042 | except: |
|
989 | 1043 | value = undefined |
|
990 | 1044 | else: |
|
991 | 1045 | value = undefined |
|
992 | 1046 | name = tpl_local_var % name_full |
|
993 | 1047 | else: |
|
994 | 1048 | if name_base in frame.f_globals: |
|
995 | 1049 | try: |
|
996 | 1050 | value = repr(eval(name_full, frame.f_globals)) |
|
997 | 1051 | except: |
|
998 | 1052 | value = undefined |
|
999 | 1053 | else: |
|
1000 | 1054 | value = undefined |
|
1001 | 1055 | name = tpl_global_var % name_full |
|
1002 | 1056 | lvals_list.append(tpl_name_val % (name, value)) |
|
1003 | 1057 | if lvals_list: |
|
1004 | 1058 | lvals = '%s%s' % (indent, em_normal.join(lvals_list)) |
|
1005 | 1059 | |
|
1006 | 1060 | level = '%s %s\n' % (link, call) |
|
1007 | 1061 | |
|
1008 | 1062 | if index is None: |
|
1009 | 1063 | return level |
|
1010 | 1064 | else: |
|
1011 | 1065 | _line_format = PyColorize.Parser(style=col_scheme, parent=self).format2 |
|
1012 | 1066 | return '%s%s' % (level, ''.join( |
|
1013 | 1067 | _format_traceback_lines(lnum, index, lines, Colors, lvals, |
|
1014 | 1068 | _line_format))) |
|
1015 | 1069 | |
|
1016 | def prepare_chained_exception_message(self, cause): | |
|
1017 | direct_cause = "\nThe above exception was the direct cause of the following exception:\n" | |
|
1018 | exception_during_handling = "\nDuring handling of the above exception, another exception occurred:\n" | |
|
1019 | ||
|
1020 | if cause: | |
|
1021 | message = [[direct_cause]] | |
|
1022 | else: | |
|
1023 | message = [[exception_during_handling]] | |
|
1024 | return message | |
|
1025 | ||
|
1026 | 1070 | def prepare_header(self, etype, long_version=False): |
|
1027 | 1071 | colors = self.Colors # just a shorthand + quicker name lookup |
|
1028 | 1072 | colorsnormal = colors.Normal # used a lot |
|
1029 | 1073 | exc = '%s%s%s' % (colors.excName, etype, colorsnormal) |
|
1030 | 1074 | width = min(75, get_terminal_size()[0]) |
|
1031 | 1075 | if long_version: |
|
1032 | 1076 | # Header with the exception type, python version, and date |
|
1033 | 1077 | pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable |
|
1034 | 1078 | date = time.ctime(time.time()) |
|
1035 | 1079 | |
|
1036 | 1080 | head = '%s%s%s\n%s%s%s\n%s' % (colors.topline, '-' * width, colorsnormal, |
|
1037 | 1081 | exc, ' ' * (width - len(str(etype)) - len(pyver)), |
|
1038 | 1082 | pyver, date.rjust(width) ) |
|
1039 | 1083 | head += "\nA problem occurred executing Python code. Here is the sequence of function" \ |
|
1040 | 1084 | "\ncalls leading up to the error, with the most recent (innermost) call last." |
|
1041 | 1085 | else: |
|
1042 | 1086 | # Simplified header |
|
1043 | 1087 | head = '%s%s' % (exc, 'Traceback (most recent call last)'. \ |
|
1044 | 1088 | rjust(width - len(str(etype))) ) |
|
1045 | 1089 | |
|
1046 | 1090 | return head |
|
1047 | 1091 | |
|
1048 | 1092 | def format_exception(self, etype, evalue): |
|
1049 | 1093 | colors = self.Colors # just a shorthand + quicker name lookup |
|
1050 | 1094 | colorsnormal = colors.Normal # used a lot |
|
1051 | 1095 | # Get (safely) a string form of the exception info |
|
1052 | 1096 | try: |
|
1053 | 1097 | etype_str, evalue_str = map(str, (etype, evalue)) |
|
1054 | 1098 | except: |
|
1055 | 1099 | # User exception is improperly defined. |
|
1056 | 1100 | etype, evalue = str, sys.exc_info()[:2] |
|
1057 | 1101 | etype_str, evalue_str = map(str, (etype, evalue)) |
|
1058 | 1102 | # ... and format it |
|
1059 | 1103 | return ['%s%s%s: %s' % (colors.excName, etype_str, |
|
1060 | 1104 | colorsnormal, py3compat.cast_unicode(evalue_str))] |
|
1061 | 1105 | |
|
1062 | 1106 | def format_exception_as_a_whole(self, etype, evalue, etb, number_of_lines_of_context, tb_offset): |
|
1063 | 1107 | """Formats the header, traceback and exception message for a single exception. |
|
1064 | 1108 | |
|
1065 | 1109 | This may be called multiple times by Python 3 exception chaining |
|
1066 | 1110 | (PEP 3134). |
|
1067 | 1111 | """ |
|
1068 | 1112 | # some locals |
|
1069 | 1113 | orig_etype = etype |
|
1070 | 1114 | try: |
|
1071 | 1115 | etype = etype.__name__ |
|
1072 | 1116 | except AttributeError: |
|
1073 | 1117 | pass |
|
1074 | 1118 | |
|
1075 | 1119 | tb_offset = self.tb_offset if tb_offset is None else tb_offset |
|
1076 | 1120 | head = self.prepare_header(etype, self.long_header) |
|
1077 | 1121 | records = self.get_records(etb, number_of_lines_of_context, tb_offset) |
|
1078 | 1122 | |
|
1079 | 1123 | if records is None: |
|
1080 | 1124 | return "" |
|
1081 | 1125 | |
|
1082 | 1126 | last_unique, recursion_repeat = find_recursion(orig_etype, evalue, records) |
|
1083 | 1127 | |
|
1084 | 1128 | frames = self.format_records(records, last_unique, recursion_repeat) |
|
1085 | 1129 | |
|
1086 | 1130 | formatted_exception = self.format_exception(etype, evalue) |
|
1087 | 1131 | if records: |
|
1088 | 1132 | filepath, lnum = records[-1][1:3] |
|
1089 | 1133 | filepath = os.path.abspath(filepath) |
|
1090 | 1134 | ipinst = get_ipython() |
|
1091 | 1135 | if ipinst is not None: |
|
1092 | 1136 | ipinst.hooks.synchronize_with_editor(filepath, lnum, 0) |
|
1093 | 1137 | |
|
1094 | 1138 | return [[head] + frames + [''.join(formatted_exception[0])]] |
|
1095 | 1139 | |
|
1096 | 1140 | def get_records(self, etb, number_of_lines_of_context, tb_offset): |
|
1097 | 1141 | try: |
|
1098 | 1142 | # Try the default getinnerframes and Alex's: Alex's fixes some |
|
1099 | 1143 | # problems, but it generates empty tracebacks for console errors |
|
1100 | 1144 | # (5 blanks lines) where none should be returned. |
|
1101 | 1145 | return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset) |
|
1102 | 1146 | except UnicodeDecodeError: |
|
1103 | 1147 | # This can occur if a file's encoding magic comment is wrong. |
|
1104 | 1148 | # I can't see a way to recover without duplicating a bunch of code |
|
1105 | 1149 | # from the stdlib traceback module. --TK |
|
1106 | 1150 | error('\nUnicodeDecodeError while processing traceback.\n') |
|
1107 | 1151 | return None |
|
1108 | 1152 | except: |
|
1109 | 1153 | # FIXME: I've been getting many crash reports from python 2.3 |
|
1110 | 1154 | # users, traceable to inspect.py. If I can find a small test-case |
|
1111 | 1155 | # to reproduce this, I should either write a better workaround or |
|
1112 | 1156 | # file a bug report against inspect (if that's the real problem). |
|
1113 | 1157 | # So far, I haven't been able to find an isolated example to |
|
1114 | 1158 | # reproduce the problem. |
|
1115 | 1159 | inspect_error() |
|
1116 | 1160 | traceback.print_exc(file=self.ostream) |
|
1117 | 1161 | info('\nUnfortunately, your original traceback can not be constructed.\n') |
|
1118 | 1162 | return None |
|
1119 | 1163 | |
|
1120 | def get_parts_of_chained_exception(self, evalue): | |
|
1121 | def get_chained_exception(exception_value): | |
|
1122 | cause = getattr(exception_value, '__cause__', None) | |
|
1123 | if cause: | |
|
1124 | return cause | |
|
1125 | if getattr(exception_value, '__suppress_context__', False): | |
|
1126 | return None | |
|
1127 | return getattr(exception_value, '__context__', None) | |
|
1128 | ||
|
1129 | chained_evalue = get_chained_exception(evalue) | |
|
1130 | ||
|
1131 | if chained_evalue: | |
|
1132 | return chained_evalue.__class__, chained_evalue, chained_evalue.__traceback__ | |
|
1133 | ||
|
1134 | 1164 | def structured_traceback(self, etype, evalue, etb, tb_offset=None, |
|
1135 | 1165 | number_of_lines_of_context=5): |
|
1136 | 1166 | """Return a nice text document describing the traceback.""" |
|
1137 | 1167 | |
|
1138 | 1168 | formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context, |
|
1139 | 1169 | tb_offset) |
|
1140 | 1170 | |
|
1141 | 1171 | colors = self.Colors # just a shorthand + quicker name lookup |
|
1142 | 1172 | colorsnormal = colors.Normal # used a lot |
|
1143 | 1173 | head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal) |
|
1144 | 1174 | structured_traceback_parts = [head] |
|
1145 | 1175 | chained_exceptions_tb_offset = 0 |
|
1146 | 1176 | lines_of_context = 3 |
|
1147 | 1177 | formatted_exceptions = formatted_exception |
|
1148 | 1178 | exception = self.get_parts_of_chained_exception(evalue) |
|
1149 | 1179 | if exception: |
|
1150 | 1180 | formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__) |
|
1151 | 1181 | etype, evalue, etb = exception |
|
1152 | 1182 | else: |
|
1153 | 1183 | evalue = None |
|
1154 | 1184 | chained_exc_ids = set() |
|
1155 | 1185 | while evalue: |
|
1156 | 1186 | formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context, |
|
1157 | 1187 | chained_exceptions_tb_offset) |
|
1158 | 1188 | exception = self.get_parts_of_chained_exception(evalue) |
|
1159 | 1189 | |
|
1160 | 1190 | if exception and not id(exception[1]) in chained_exc_ids: |
|
1161 | 1191 | chained_exc_ids.add(id(exception[1])) # trace exception to avoid infinite 'cause' loop |
|
1162 | 1192 | formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__) |
|
1163 | 1193 | etype, evalue, etb = exception |
|
1164 | 1194 | else: |
|
1165 | 1195 | evalue = None |
|
1166 | 1196 | |
|
1167 | 1197 | # we want to see exceptions in a reversed order: |
|
1168 | 1198 | # the first exception should be on top |
|
1169 | 1199 | for formatted_exception in reversed(formatted_exceptions): |
|
1170 | 1200 | structured_traceback_parts += formatted_exception |
|
1171 | 1201 | |
|
1172 | 1202 | return structured_traceback_parts |
|
1173 | 1203 | |
|
1174 | 1204 | def debugger(self, force=False): |
|
1175 | 1205 | """Call up the pdb debugger if desired, always clean up the tb |
|
1176 | 1206 | reference. |
|
1177 | 1207 | |
|
1178 | 1208 | Keywords: |
|
1179 | 1209 | |
|
1180 | 1210 | - force(False): by default, this routine checks the instance call_pdb |
|
1181 | 1211 | flag and does not actually invoke the debugger if the flag is false. |
|
1182 | 1212 | The 'force' option forces the debugger to activate even if the flag |
|
1183 | 1213 | is false. |
|
1184 | 1214 | |
|
1185 | 1215 | If the call_pdb flag is set, the pdb interactive debugger is |
|
1186 | 1216 | invoked. In all cases, the self.tb reference to the current traceback |
|
1187 | 1217 | is deleted to prevent lingering references which hamper memory |
|
1188 | 1218 | management. |
|
1189 | 1219 | |
|
1190 | 1220 | Note that each call to pdb() does an 'import readline', so if your app |
|
1191 | 1221 | requires a special setup for the readline completers, you'll have to |
|
1192 | 1222 | fix that by hand after invoking the exception handler.""" |
|
1193 | 1223 | |
|
1194 | 1224 | if force or self.call_pdb: |
|
1195 | 1225 | if self.pdb is None: |
|
1196 | 1226 | self.pdb = self.debugger_cls() |
|
1197 | 1227 | # the system displayhook may have changed, restore the original |
|
1198 | 1228 | # for pdb |
|
1199 | 1229 | display_trap = DisplayTrap(hook=sys.__displayhook__) |
|
1200 | 1230 | with display_trap: |
|
1201 | 1231 | self.pdb.reset() |
|
1202 | 1232 | # Find the right frame so we don't pop up inside ipython itself |
|
1203 | 1233 | if hasattr(self, 'tb') and self.tb is not None: |
|
1204 | 1234 | etb = self.tb |
|
1205 | 1235 | else: |
|
1206 | 1236 | etb = self.tb = sys.last_traceback |
|
1207 | 1237 | while self.tb is not None and self.tb.tb_next is not None: |
|
1208 | 1238 | self.tb = self.tb.tb_next |
|
1209 | 1239 | if etb and etb.tb_next: |
|
1210 | 1240 | etb = etb.tb_next |
|
1211 | 1241 | self.pdb.botframe = etb.tb_frame |
|
1212 | 1242 | self.pdb.interaction(None, etb) |
|
1213 | 1243 | |
|
1214 | 1244 | if hasattr(self, 'tb'): |
|
1215 | 1245 | del self.tb |
|
1216 | 1246 | |
|
1217 | 1247 | def handler(self, info=None): |
|
1218 | 1248 | (etype, evalue, etb) = info or sys.exc_info() |
|
1219 | 1249 | self.tb = etb |
|
1220 | 1250 | ostream = self.ostream |
|
1221 | 1251 | ostream.flush() |
|
1222 | 1252 | ostream.write(self.text(etype, evalue, etb)) |
|
1223 | 1253 | ostream.write('\n') |
|
1224 | 1254 | ostream.flush() |
|
1225 | 1255 | |
|
1226 | 1256 | # Changed so an instance can just be called as VerboseTB_inst() and print |
|
1227 | 1257 | # out the right info on its own. |
|
1228 | 1258 | def __call__(self, etype=None, evalue=None, etb=None): |
|
1229 | 1259 | """This hook can replace sys.excepthook (for Python 2.1 or higher).""" |
|
1230 | 1260 | if etb is None: |
|
1231 | 1261 | self.handler() |
|
1232 | 1262 | else: |
|
1233 | 1263 | self.handler((etype, evalue, etb)) |
|
1234 | 1264 | try: |
|
1235 | 1265 | self.debugger() |
|
1236 | 1266 | except KeyboardInterrupt: |
|
1237 | 1267 | print("\nKeyboardInterrupt") |
|
1238 | 1268 | |
|
1239 | 1269 | |
|
1240 | 1270 | #---------------------------------------------------------------------------- |
|
1241 | 1271 | class FormattedTB(VerboseTB, ListTB): |
|
1242 | 1272 | """Subclass ListTB but allow calling with a traceback. |
|
1243 | 1273 | |
|
1244 | 1274 | It can thus be used as a sys.excepthook for Python > 2.1. |
|
1245 | 1275 | |
|
1246 | 1276 | Also adds 'Context' and 'Verbose' modes, not available in ListTB. |
|
1247 | 1277 | |
|
1248 | 1278 | Allows a tb_offset to be specified. This is useful for situations where |
|
1249 | 1279 | one needs to remove a number of topmost frames from the traceback (such as |
|
1250 | 1280 | occurs with python programs that themselves execute other python code, |
|
1251 | 1281 | like Python shells). """ |
|
1252 | 1282 | |
|
1253 | 1283 | def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False, |
|
1254 | 1284 | ostream=None, |
|
1255 | 1285 | tb_offset=0, long_header=False, include_vars=False, |
|
1256 | 1286 | check_cache=None, debugger_cls=None, |
|
1257 | 1287 | parent=None, config=None): |
|
1258 | 1288 | |
|
1259 | 1289 | # NEVER change the order of this list. Put new modes at the end: |
|
1260 | 1290 | self.valid_modes = ['Plain', 'Context', 'Verbose', 'Minimal'] |
|
1261 | 1291 | self.verbose_modes = self.valid_modes[1:3] |
|
1262 | 1292 | |
|
1263 | 1293 | VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, |
|
1264 | 1294 | ostream=ostream, tb_offset=tb_offset, |
|
1265 | 1295 | long_header=long_header, include_vars=include_vars, |
|
1266 | 1296 | check_cache=check_cache, debugger_cls=debugger_cls, |
|
1267 | 1297 | parent=parent, config=config) |
|
1268 | 1298 | |
|
1269 | 1299 | # Different types of tracebacks are joined with different separators to |
|
1270 | 1300 | # form a single string. They are taken from this dict |
|
1271 | 1301 | self._join_chars = dict(Plain='', Context='\n', Verbose='\n', |
|
1272 | 1302 | Minimal='') |
|
1273 | 1303 | # set_mode also sets the tb_join_char attribute |
|
1274 | 1304 | self.set_mode(mode) |
|
1275 | 1305 | |
|
1276 | 1306 | def _extract_tb(self, tb): |
|
1277 | 1307 | if tb: |
|
1278 | 1308 | return traceback.extract_tb(tb) |
|
1279 | 1309 | else: |
|
1280 | 1310 | return None |
|
1281 | 1311 | |
|
1282 | 1312 | def structured_traceback(self, etype, value, tb, tb_offset=None, number_of_lines_of_context=5): |
|
1283 | 1313 | tb_offset = self.tb_offset if tb_offset is None else tb_offset |
|
1284 | 1314 | mode = self.mode |
|
1285 | 1315 | if mode in self.verbose_modes: |
|
1286 | 1316 | # Verbose modes need a full traceback |
|
1287 | 1317 | return VerboseTB.structured_traceback( |
|
1288 | 1318 | self, etype, value, tb, tb_offset, number_of_lines_of_context |
|
1289 | 1319 | ) |
|
1290 | 1320 | elif mode == 'Minimal': |
|
1291 | 1321 | return ListTB.get_exception_only(self, etype, value) |
|
1292 | 1322 | else: |
|
1293 | 1323 | # We must check the source cache because otherwise we can print |
|
1294 | 1324 | # out-of-date source code. |
|
1295 | 1325 | self.check_cache() |
|
1296 | 1326 | # Now we can extract and format the exception |
|
1297 | elist = self._extract_tb(tb) | |
|
1298 | 1327 | return ListTB.structured_traceback( |
|
1299 |
self, etype, value, |
|
|
1328 | self, etype, value, tb, tb_offset, number_of_lines_of_context | |
|
1300 | 1329 | ) |
|
1301 | 1330 | |
|
1302 | 1331 | def stb2text(self, stb): |
|
1303 | 1332 | """Convert a structured traceback (a list) to a string.""" |
|
1304 | 1333 | return self.tb_join_char.join(stb) |
|
1305 | 1334 | |
|
1306 | 1335 | |
|
1307 | 1336 | def set_mode(self, mode=None): |
|
1308 | 1337 | """Switch to the desired mode. |
|
1309 | 1338 | |
|
1310 | 1339 | If mode is not specified, cycles through the available modes.""" |
|
1311 | 1340 | |
|
1312 | 1341 | if not mode: |
|
1313 | 1342 | new_idx = (self.valid_modes.index(self.mode) + 1 ) % \ |
|
1314 | 1343 | len(self.valid_modes) |
|
1315 | 1344 | self.mode = self.valid_modes[new_idx] |
|
1316 | 1345 | elif mode not in self.valid_modes: |
|
1317 | 1346 | raise ValueError('Unrecognized mode in FormattedTB: <' + mode + '>\n' |
|
1318 | 1347 | 'Valid modes: ' + str(self.valid_modes)) |
|
1319 | 1348 | else: |
|
1320 | 1349 | self.mode = mode |
|
1321 | 1350 | # include variable details only in 'Verbose' mode |
|
1322 | 1351 | self.include_vars = (self.mode == self.valid_modes[2]) |
|
1323 | 1352 | # Set the join character for generating text tracebacks |
|
1324 | 1353 | self.tb_join_char = self._join_chars[self.mode] |
|
1325 | 1354 | |
|
1326 | 1355 | # some convenient shortcuts |
|
1327 | 1356 | def plain(self): |
|
1328 | 1357 | self.set_mode(self.valid_modes[0]) |
|
1329 | 1358 | |
|
1330 | 1359 | def context(self): |
|
1331 | 1360 | self.set_mode(self.valid_modes[1]) |
|
1332 | 1361 | |
|
1333 | 1362 | def verbose(self): |
|
1334 | 1363 | self.set_mode(self.valid_modes[2]) |
|
1335 | 1364 | |
|
1336 | 1365 | def minimal(self): |
|
1337 | 1366 | self.set_mode(self.valid_modes[3]) |
|
1338 | 1367 | |
|
1339 | 1368 | |
|
1340 | 1369 | #---------------------------------------------------------------------------- |
|
1341 | 1370 | class AutoFormattedTB(FormattedTB): |
|
1342 | 1371 | """A traceback printer which can be called on the fly. |
|
1343 | 1372 | |
|
1344 | 1373 | It will find out about exceptions by itself. |
|
1345 | 1374 | |
|
1346 | 1375 | A brief example:: |
|
1347 | 1376 | |
|
1348 | 1377 | AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux') |
|
1349 | 1378 | try: |
|
1350 | 1379 | ... |
|
1351 | 1380 | except: |
|
1352 | 1381 | AutoTB() # or AutoTB(out=logfile) where logfile is an open file object |
|
1353 | 1382 | """ |
|
1354 | 1383 | |
|
1355 | 1384 | def __call__(self, etype=None, evalue=None, etb=None, |
|
1356 | 1385 | out=None, tb_offset=None): |
|
1357 | 1386 | """Print out a formatted exception traceback. |
|
1358 | 1387 | |
|
1359 | 1388 | Optional arguments: |
|
1360 | 1389 | - out: an open file-like object to direct output to. |
|
1361 | 1390 | |
|
1362 | 1391 | - tb_offset: the number of frames to skip over in the stack, on a |
|
1363 | 1392 | per-call basis (this overrides temporarily the instance's tb_offset |
|
1364 | 1393 | given at initialization time. """ |
|
1365 | 1394 | |
|
1366 | 1395 | if out is None: |
|
1367 | 1396 | out = self.ostream |
|
1368 | 1397 | out.flush() |
|
1369 | 1398 | out.write(self.text(etype, evalue, etb, tb_offset)) |
|
1370 | 1399 | out.write('\n') |
|
1371 | 1400 | out.flush() |
|
1372 | 1401 | # FIXME: we should remove the auto pdb behavior from here and leave |
|
1373 | 1402 | # that to the clients. |
|
1374 | 1403 | try: |
|
1375 | 1404 | self.debugger() |
|
1376 | 1405 | except KeyboardInterrupt: |
|
1377 | 1406 | print("\nKeyboardInterrupt") |
|
1378 | 1407 | |
|
1379 | 1408 | def structured_traceback(self, etype=None, value=None, tb=None, |
|
1380 | 1409 | tb_offset=None, number_of_lines_of_context=5): |
|
1381 | 1410 | if etype is None: |
|
1382 | 1411 | etype, value, tb = sys.exc_info() |
|
1383 | 1412 | self.tb = tb |
|
1384 | 1413 | return FormattedTB.structured_traceback( |
|
1385 | 1414 | self, etype, value, tb, tb_offset, number_of_lines_of_context) |
|
1386 | 1415 | |
|
1387 | 1416 | |
|
1388 | 1417 | #--------------------------------------------------------------------------- |
|
1389 | 1418 | |
|
1390 | 1419 | # A simple class to preserve Nathan's original functionality. |
|
1391 | 1420 | class ColorTB(FormattedTB): |
|
1392 | 1421 | """Shorthand to initialize a FormattedTB in Linux colors mode.""" |
|
1393 | 1422 | |
|
1394 | 1423 | def __init__(self, color_scheme='Linux', call_pdb=0, **kwargs): |
|
1395 | 1424 | FormattedTB.__init__(self, color_scheme=color_scheme, |
|
1396 | 1425 | call_pdb=call_pdb, **kwargs) |
|
1397 | 1426 | |
|
1398 | 1427 | |
|
1399 | 1428 | class SyntaxTB(ListTB): |
|
1400 | 1429 | """Extension which holds some state: the last exception value""" |
|
1401 | 1430 | |
|
1402 | 1431 | def __init__(self, color_scheme='NoColor', parent=None, config=None): |
|
1403 | 1432 | ListTB.__init__(self, color_scheme, parent=parent, config=config) |
|
1404 | 1433 | self.last_syntax_error = None |
|
1405 | 1434 | |
|
1406 | 1435 | def __call__(self, etype, value, elist): |
|
1407 | 1436 | self.last_syntax_error = value |
|
1408 | 1437 | |
|
1409 | 1438 | ListTB.__call__(self, etype, value, elist) |
|
1410 | 1439 | |
|
1411 | 1440 | def structured_traceback(self, etype, value, elist, tb_offset=None, |
|
1412 | 1441 | context=5): |
|
1413 | 1442 | # If the source file has been edited, the line in the syntax error can |
|
1414 | 1443 | # be wrong (retrieved from an outdated cache). This replaces it with |
|
1415 | 1444 | # the current value. |
|
1416 | 1445 | if isinstance(value, SyntaxError) \ |
|
1417 | 1446 | and isinstance(value.filename, str) \ |
|
1418 | 1447 | and isinstance(value.lineno, int): |
|
1419 | 1448 | linecache.checkcache(value.filename) |
|
1420 | 1449 | newtext = linecache.getline(value.filename, value.lineno) |
|
1421 | 1450 | if newtext: |
|
1422 | 1451 | value.text = newtext |
|
1423 | 1452 | self.last_syntax_error = value |
|
1424 | 1453 | return super(SyntaxTB, self).structured_traceback(etype, value, elist, |
|
1425 | 1454 | tb_offset=tb_offset, context=context) |
|
1426 | 1455 | |
|
1427 | 1456 | def clear_err_state(self): |
|
1428 | 1457 | """Return the current error state and clear it""" |
|
1429 | 1458 | e = self.last_syntax_error |
|
1430 | 1459 | self.last_syntax_error = None |
|
1431 | 1460 | return e |
|
1432 | 1461 | |
|
1433 | 1462 | def stb2text(self, stb): |
|
1434 | 1463 | """Convert a structured traceback (a list) to a string.""" |
|
1435 | 1464 | return ''.join(stb) |
|
1436 | 1465 | |
|
1437 | 1466 | |
|
1438 | 1467 | # some internal-use functions |
|
1439 | 1468 | def text_repr(value): |
|
1440 | 1469 | """Hopefully pretty robust repr equivalent.""" |
|
1441 | 1470 | # this is pretty horrible but should always return *something* |
|
1442 | 1471 | try: |
|
1443 | 1472 | return pydoc.text.repr(value) |
|
1444 | 1473 | except KeyboardInterrupt: |
|
1445 | 1474 | raise |
|
1446 | 1475 | except: |
|
1447 | 1476 | try: |
|
1448 | 1477 | return repr(value) |
|
1449 | 1478 | except KeyboardInterrupt: |
|
1450 | 1479 | raise |
|
1451 | 1480 | except: |
|
1452 | 1481 | try: |
|
1453 | 1482 | # all still in an except block so we catch |
|
1454 | 1483 | # getattr raising |
|
1455 | 1484 | name = getattr(value, '__name__', None) |
|
1456 | 1485 | if name: |
|
1457 | 1486 | # ick, recursion |
|
1458 | 1487 | return text_repr(name) |
|
1459 | 1488 | klass = getattr(value, '__class__', None) |
|
1460 | 1489 | if klass: |
|
1461 | 1490 | return '%s instance' % text_repr(klass) |
|
1462 | 1491 | except KeyboardInterrupt: |
|
1463 | 1492 | raise |
|
1464 | 1493 | except: |
|
1465 | 1494 | return 'UNRECOVERABLE REPR FAILURE' |
|
1466 | 1495 | |
|
1467 | 1496 | |
|
1468 | 1497 | def eqrepr(value, repr=text_repr): |
|
1469 | 1498 | return '=%s' % repr(value) |
|
1470 | 1499 | |
|
1471 | 1500 | |
|
1472 | 1501 | def nullrepr(value, repr=text_repr): |
|
1473 | 1502 | return '' |
@@ -1,69 +1,69 b'' | |||
|
1 | 1 | """ Utilities for accessing the platform's clipboard. |
|
2 | 2 | """ |
|
3 | 3 | |
|
4 | 4 | import subprocess |
|
5 | 5 | |
|
6 | 6 | from IPython.core.error import TryNext |
|
7 | 7 | import IPython.utils.py3compat as py3compat |
|
8 | 8 | |
|
9 | 9 | class ClipboardEmpty(ValueError): |
|
10 | 10 | pass |
|
11 | 11 | |
|
12 | 12 | def win32_clipboard_get(): |
|
13 | 13 | """ Get the current clipboard's text on Windows. |
|
14 | 14 | |
|
15 | 15 | Requires Mark Hammond's pywin32 extensions. |
|
16 | 16 | """ |
|
17 | 17 | try: |
|
18 | 18 | import win32clipboard |
|
19 | 19 | except ImportError: |
|
20 | 20 | raise TryNext("Getting text from the clipboard requires the pywin32 " |
|
21 | 21 | "extensions: http://sourceforge.net/projects/pywin32/") |
|
22 | 22 | win32clipboard.OpenClipboard() |
|
23 | 23 | try: |
|
24 | 24 | text = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT) |
|
25 | 25 | except (TypeError, win32clipboard.error): |
|
26 | 26 | try: |
|
27 | 27 | text = win32clipboard.GetClipboardData(win32clipboard.CF_TEXT) |
|
28 | 28 | text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING) |
|
29 | 29 | except (TypeError, win32clipboard.error): |
|
30 | 30 | raise ClipboardEmpty |
|
31 | 31 | finally: |
|
32 | 32 | win32clipboard.CloseClipboard() |
|
33 | 33 | return text |
|
34 | 34 | |
|
35 | def osx_clipboard_get(): | |
|
35 | def osx_clipboard_get() -> str: | |
|
36 | 36 | """ Get the clipboard's text on OS X. |
|
37 | 37 | """ |
|
38 | 38 | p = subprocess.Popen(['pbpaste', '-Prefer', 'ascii'], |
|
39 | 39 | stdout=subprocess.PIPE) |
|
40 |
|
|
|
40 | bytes_, stderr = p.communicate() | |
|
41 | 41 | # Text comes in with old Mac \r line endings. Change them to \n. |
|
42 |
|
|
|
43 | text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING) | |
|
42 | bytes_ = bytes_.replace(b'\r', b'\n') | |
|
43 | text = py3compat.decode(bytes_) | |
|
44 | 44 | return text |
|
45 | 45 | |
|
46 | 46 | def tkinter_clipboard_get(): |
|
47 | 47 | """ Get the clipboard's text using Tkinter. |
|
48 | 48 | |
|
49 | 49 | This is the default on systems that are not Windows or OS X. It may |
|
50 | 50 | interfere with other UI toolkits and should be replaced with an |
|
51 | 51 | implementation that uses that toolkit. |
|
52 | 52 | """ |
|
53 | 53 | try: |
|
54 | 54 | from tkinter import Tk, TclError |
|
55 | 55 | except ImportError: |
|
56 | 56 | raise TryNext("Getting text from the clipboard on this platform requires tkinter.") |
|
57 | 57 | |
|
58 | 58 | root = Tk() |
|
59 | 59 | root.withdraw() |
|
60 | 60 | try: |
|
61 | 61 | text = root.clipboard_get() |
|
62 | 62 | except TclError: |
|
63 | 63 | raise ClipboardEmpty |
|
64 | 64 | finally: |
|
65 | 65 | root.destroy() |
|
66 | 66 | text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING) |
|
67 | 67 | return text |
|
68 | 68 | |
|
69 | 69 |
@@ -1,871 +1,863 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | Python advanced pretty printer. This pretty printer is intended to |
|
4 | 4 | replace the old `pprint` python module which does not allow developers |
|
5 | 5 | to provide their own pretty print callbacks. |
|
6 | 6 | |
|
7 | 7 | This module is based on ruby's `prettyprint.rb` library by `Tanaka Akira`. |
|
8 | 8 | |
|
9 | 9 | |
|
10 | 10 | Example Usage |
|
11 | 11 | ------------- |
|
12 | 12 | |
|
13 | 13 | To directly print the representation of an object use `pprint`:: |
|
14 | 14 | |
|
15 | 15 | from pretty import pprint |
|
16 | 16 | pprint(complex_object) |
|
17 | 17 | |
|
18 | 18 | To get a string of the output use `pretty`:: |
|
19 | 19 | |
|
20 | 20 | from pretty import pretty |
|
21 | 21 | string = pretty(complex_object) |
|
22 | 22 | |
|
23 | 23 | |
|
24 | 24 | Extending |
|
25 | 25 | --------- |
|
26 | 26 | |
|
27 | 27 | The pretty library allows developers to add pretty printing rules for their |
|
28 | 28 | own objects. This process is straightforward. All you have to do is to |
|
29 | 29 | add a `_repr_pretty_` method to your object and call the methods on the |
|
30 | 30 | pretty printer passed:: |
|
31 | 31 | |
|
32 | 32 | class MyObject(object): |
|
33 | 33 | |
|
34 | 34 | def _repr_pretty_(self, p, cycle): |
|
35 | 35 | ... |
|
36 | 36 | |
|
37 | 37 | Here is an example implementation of a `_repr_pretty_` method for a list |
|
38 | 38 | subclass:: |
|
39 | 39 | |
|
40 | 40 | class MyList(list): |
|
41 | 41 | |
|
42 | 42 | def _repr_pretty_(self, p, cycle): |
|
43 | 43 | if cycle: |
|
44 | 44 | p.text('MyList(...)') |
|
45 | 45 | else: |
|
46 | 46 | with p.group(8, 'MyList([', '])'): |
|
47 | 47 | for idx, item in enumerate(self): |
|
48 | 48 | if idx: |
|
49 | 49 | p.text(',') |
|
50 | 50 | p.breakable() |
|
51 | 51 | p.pretty(item) |
|
52 | 52 | |
|
53 | 53 | The `cycle` parameter is `True` if pretty detected a cycle. You *have* to |
|
54 | 54 | react to that or the result is an infinite loop. `p.text()` just adds |
|
55 | 55 | non breaking text to the output, `p.breakable()` either adds a whitespace |
|
56 | 56 | or breaks here. If you pass it an argument it's used instead of the |
|
57 | 57 | default space. `p.pretty` prettyprints another object using the pretty print |
|
58 | 58 | method. |
|
59 | 59 | |
|
60 | 60 | The first parameter to the `group` function specifies the extra indentation |
|
61 | 61 | of the next line. In this example the next item will either be on the same |
|
62 | 62 | line (if the items are short enough) or aligned with the right edge of the |
|
63 | 63 | opening bracket of `MyList`. |
|
64 | 64 | |
|
65 | 65 | If you just want to indent something you can use the group function |
|
66 | 66 | without open / close parameters. You can also use this code:: |
|
67 | 67 | |
|
68 | 68 | with p.indent(2): |
|
69 | 69 | ... |
|
70 | 70 | |
|
71 | 71 | Inheritance diagram: |
|
72 | 72 | |
|
73 | 73 | .. inheritance-diagram:: IPython.lib.pretty |
|
74 | 74 | :parts: 3 |
|
75 | 75 | |
|
76 | 76 | :copyright: 2007 by Armin Ronacher. |
|
77 | 77 | Portions (c) 2009 by Robert Kern. |
|
78 | 78 | :license: BSD License. |
|
79 | 79 | """ |
|
80 | 80 | |
|
81 | 81 | from contextlib import contextmanager |
|
82 | 82 | import datetime |
|
83 | 83 | import os |
|
84 | 84 | import re |
|
85 | 85 | import sys |
|
86 | 86 | import types |
|
87 | 87 | from collections import deque |
|
88 | 88 | from inspect import signature |
|
89 | 89 | from io import StringIO |
|
90 | 90 | from warnings import warn |
|
91 | 91 | |
|
92 | 92 | from IPython.utils.decorators import undoc |
|
93 | 93 | from IPython.utils.py3compat import PYPY |
|
94 | 94 | |
|
95 | 95 | __all__ = ['pretty', 'pprint', 'PrettyPrinter', 'RepresentationPrinter', |
|
96 | 96 | 'for_type', 'for_type_by_name'] |
|
97 | 97 | |
|
98 | 98 | |
|
99 | 99 | MAX_SEQ_LENGTH = 1000 |
|
100 | # The language spec says that dicts preserve order from 3.7, but CPython | |
|
101 | # does so from 3.6, so it seems likely that people will expect that. | |
|
102 | DICT_IS_ORDERED = True | |
|
103 | 100 | _re_pattern_type = type(re.compile('')) |
|
104 | 101 | |
|
105 | 102 | def _safe_getattr(obj, attr, default=None): |
|
106 | 103 | """Safe version of getattr. |
|
107 | 104 | |
|
108 | 105 | Same as getattr, but will return ``default`` on any Exception, |
|
109 | 106 | rather than raising. |
|
110 | 107 | """ |
|
111 | 108 | try: |
|
112 | 109 | return getattr(obj, attr, default) |
|
113 | 110 | except Exception: |
|
114 | 111 | return default |
|
115 | 112 | |
|
116 | 113 | @undoc |
|
117 | 114 | class CUnicodeIO(StringIO): |
|
118 | 115 | def __init__(self, *args, **kwargs): |
|
119 | 116 | super().__init__(*args, **kwargs) |
|
120 | 117 | warn(("CUnicodeIO is deprecated since IPython 6.0. " |
|
121 | 118 | "Please use io.StringIO instead."), |
|
122 | 119 | DeprecationWarning, stacklevel=2) |
|
123 | 120 | |
|
124 | 121 | def _sorted_for_pprint(items): |
|
125 | 122 | """ |
|
126 | 123 | Sort the given items for pretty printing. Since some predictable |
|
127 | 124 | sorting is better than no sorting at all, we sort on the string |
|
128 | 125 | representation if normal sorting fails. |
|
129 | 126 | """ |
|
130 | 127 | items = list(items) |
|
131 | 128 | try: |
|
132 | 129 | return sorted(items) |
|
133 | 130 | except Exception: |
|
134 | 131 | try: |
|
135 | 132 | return sorted(items, key=str) |
|
136 | 133 | except Exception: |
|
137 | 134 | return items |
|
138 | 135 | |
|
139 | 136 | def pretty(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH): |
|
140 | 137 | """ |
|
141 | 138 | Pretty print the object's representation. |
|
142 | 139 | """ |
|
143 | 140 | stream = StringIO() |
|
144 | 141 | printer = RepresentationPrinter(stream, verbose, max_width, newline, max_seq_length=max_seq_length) |
|
145 | 142 | printer.pretty(obj) |
|
146 | 143 | printer.flush() |
|
147 | 144 | return stream.getvalue() |
|
148 | 145 | |
|
149 | 146 | |
|
150 | 147 | def pprint(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH): |
|
151 | 148 | """ |
|
152 | 149 | Like `pretty` but print to stdout. |
|
153 | 150 | """ |
|
154 | 151 | printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline, max_seq_length=max_seq_length) |
|
155 | 152 | printer.pretty(obj) |
|
156 | 153 | printer.flush() |
|
157 | 154 | sys.stdout.write(newline) |
|
158 | 155 | sys.stdout.flush() |
|
159 | 156 | |
|
160 | 157 | class _PrettyPrinterBase(object): |
|
161 | 158 | |
|
162 | 159 | @contextmanager |
|
163 | 160 | def indent(self, indent): |
|
164 | 161 | """with statement support for indenting/dedenting.""" |
|
165 | 162 | self.indentation += indent |
|
166 | 163 | try: |
|
167 | 164 | yield |
|
168 | 165 | finally: |
|
169 | 166 | self.indentation -= indent |
|
170 | 167 | |
|
171 | 168 | @contextmanager |
|
172 | 169 | def group(self, indent=0, open='', close=''): |
|
173 | 170 | """like begin_group / end_group but for the with statement.""" |
|
174 | 171 | self.begin_group(indent, open) |
|
175 | 172 | try: |
|
176 | 173 | yield |
|
177 | 174 | finally: |
|
178 | 175 | self.end_group(indent, close) |
|
179 | 176 | |
|
180 | 177 | class PrettyPrinter(_PrettyPrinterBase): |
|
181 | 178 | """ |
|
182 | 179 | Baseclass for the `RepresentationPrinter` prettyprinter that is used to |
|
183 | 180 | generate pretty reprs of objects. Contrary to the `RepresentationPrinter` |
|
184 | 181 | this printer knows nothing about the default pprinters or the `_repr_pretty_` |
|
185 | 182 | callback method. |
|
186 | 183 | """ |
|
187 | 184 | |
|
188 | 185 | def __init__(self, output, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH): |
|
189 | 186 | self.output = output |
|
190 | 187 | self.max_width = max_width |
|
191 | 188 | self.newline = newline |
|
192 | 189 | self.max_seq_length = max_seq_length |
|
193 | 190 | self.output_width = 0 |
|
194 | 191 | self.buffer_width = 0 |
|
195 | 192 | self.buffer = deque() |
|
196 | 193 | |
|
197 | 194 | root_group = Group(0) |
|
198 | 195 | self.group_stack = [root_group] |
|
199 | 196 | self.group_queue = GroupQueue(root_group) |
|
200 | 197 | self.indentation = 0 |
|
201 | 198 | |
|
202 | 199 | def _break_outer_groups(self): |
|
203 | 200 | while self.max_width < self.output_width + self.buffer_width: |
|
204 | 201 | group = self.group_queue.deq() |
|
205 | 202 | if not group: |
|
206 | 203 | return |
|
207 | 204 | while group.breakables: |
|
208 | 205 | x = self.buffer.popleft() |
|
209 | 206 | self.output_width = x.output(self.output, self.output_width) |
|
210 | 207 | self.buffer_width -= x.width |
|
211 | 208 | while self.buffer and isinstance(self.buffer[0], Text): |
|
212 | 209 | x = self.buffer.popleft() |
|
213 | 210 | self.output_width = x.output(self.output, self.output_width) |
|
214 | 211 | self.buffer_width -= x.width |
|
215 | 212 | |
|
216 | 213 | def text(self, obj): |
|
217 | 214 | """Add literal text to the output.""" |
|
218 | 215 | width = len(obj) |
|
219 | 216 | if self.buffer: |
|
220 | 217 | text = self.buffer[-1] |
|
221 | 218 | if not isinstance(text, Text): |
|
222 | 219 | text = Text() |
|
223 | 220 | self.buffer.append(text) |
|
224 | 221 | text.add(obj, width) |
|
225 | 222 | self.buffer_width += width |
|
226 | 223 | self._break_outer_groups() |
|
227 | 224 | else: |
|
228 | 225 | self.output.write(obj) |
|
229 | 226 | self.output_width += width |
|
230 | 227 | |
|
231 | 228 | def breakable(self, sep=' '): |
|
232 | 229 | """ |
|
233 | 230 | Add a breakable separator to the output. This does not mean that it |
|
234 | 231 | will automatically break here. If no breaking on this position takes |
|
235 | 232 | place the `sep` is inserted which default to one space. |
|
236 | 233 | """ |
|
237 | 234 | width = len(sep) |
|
238 | 235 | group = self.group_stack[-1] |
|
239 | 236 | if group.want_break: |
|
240 | 237 | self.flush() |
|
241 | 238 | self.output.write(self.newline) |
|
242 | 239 | self.output.write(' ' * self.indentation) |
|
243 | 240 | self.output_width = self.indentation |
|
244 | 241 | self.buffer_width = 0 |
|
245 | 242 | else: |
|
246 | 243 | self.buffer.append(Breakable(sep, width, self)) |
|
247 | 244 | self.buffer_width += width |
|
248 | 245 | self._break_outer_groups() |
|
249 | 246 | |
|
250 | 247 | def break_(self): |
|
251 | 248 | """ |
|
252 | 249 | Explicitly insert a newline into the output, maintaining correct indentation. |
|
253 | 250 | """ |
|
254 | 251 | self.flush() |
|
255 | 252 | self.output.write(self.newline) |
|
256 | 253 | self.output.write(' ' * self.indentation) |
|
257 | 254 | self.output_width = self.indentation |
|
258 | 255 | self.buffer_width = 0 |
|
259 | 256 | |
|
260 | 257 | |
|
261 | 258 | def begin_group(self, indent=0, open=''): |
|
262 | 259 | """ |
|
263 | 260 | Begin a group. If you want support for python < 2.5 which doesn't has |
|
264 | 261 | the with statement this is the preferred way: |
|
265 | 262 | |
|
266 | 263 | p.begin_group(1, '{') |
|
267 | 264 | ... |
|
268 | 265 | p.end_group(1, '}') |
|
269 | 266 | |
|
270 | 267 | The python 2.5 expression would be this: |
|
271 | 268 | |
|
272 | 269 | with p.group(1, '{', '}'): |
|
273 | 270 | ... |
|
274 | 271 | |
|
275 | 272 | The first parameter specifies the indentation for the next line (usually |
|
276 | 273 | the width of the opening text), the second the opening text. All |
|
277 | 274 | parameters are optional. |
|
278 | 275 | """ |
|
279 | 276 | if open: |
|
280 | 277 | self.text(open) |
|
281 | 278 | group = Group(self.group_stack[-1].depth + 1) |
|
282 | 279 | self.group_stack.append(group) |
|
283 | 280 | self.group_queue.enq(group) |
|
284 | 281 | self.indentation += indent |
|
285 | 282 | |
|
286 | 283 | def _enumerate(self, seq): |
|
287 | 284 | """like enumerate, but with an upper limit on the number of items""" |
|
288 | 285 | for idx, x in enumerate(seq): |
|
289 | 286 | if self.max_seq_length and idx >= self.max_seq_length: |
|
290 | 287 | self.text(',') |
|
291 | 288 | self.breakable() |
|
292 | 289 | self.text('...') |
|
293 | 290 | return |
|
294 | 291 | yield idx, x |
|
295 | 292 | |
|
296 | 293 | def end_group(self, dedent=0, close=''): |
|
297 | 294 | """End a group. See `begin_group` for more details.""" |
|
298 | 295 | self.indentation -= dedent |
|
299 | 296 | group = self.group_stack.pop() |
|
300 | 297 | if not group.breakables: |
|
301 | 298 | self.group_queue.remove(group) |
|
302 | 299 | if close: |
|
303 | 300 | self.text(close) |
|
304 | 301 | |
|
305 | 302 | def flush(self): |
|
306 | 303 | """Flush data that is left in the buffer.""" |
|
307 | 304 | for data in self.buffer: |
|
308 | 305 | self.output_width += data.output(self.output, self.output_width) |
|
309 | 306 | self.buffer.clear() |
|
310 | 307 | self.buffer_width = 0 |
|
311 | 308 | |
|
312 | 309 | |
|
313 | 310 | def _get_mro(obj_class): |
|
314 | 311 | """ Get a reasonable method resolution order of a class and its superclasses |
|
315 | 312 | for both old-style and new-style classes. |
|
316 | 313 | """ |
|
317 | 314 | if not hasattr(obj_class, '__mro__'): |
|
318 | 315 | # Old-style class. Mix in object to make a fake new-style class. |
|
319 | 316 | try: |
|
320 | 317 | obj_class = type(obj_class.__name__, (obj_class, object), {}) |
|
321 | 318 | except TypeError: |
|
322 | 319 | # Old-style extension type that does not descend from object. |
|
323 | 320 | # FIXME: try to construct a more thorough MRO. |
|
324 | 321 | mro = [obj_class] |
|
325 | 322 | else: |
|
326 | 323 | mro = obj_class.__mro__[1:-1] |
|
327 | 324 | else: |
|
328 | 325 | mro = obj_class.__mro__ |
|
329 | 326 | return mro |
|
330 | 327 | |
|
331 | 328 | |
|
332 | 329 | class RepresentationPrinter(PrettyPrinter): |
|
333 | 330 | """ |
|
334 | 331 | Special pretty printer that has a `pretty` method that calls the pretty |
|
335 | 332 | printer for a python object. |
|
336 | 333 | |
|
337 | 334 | This class stores processing data on `self` so you must *never* use |
|
338 | 335 | this class in a threaded environment. Always lock it or reinstanciate |
|
339 | 336 | it. |
|
340 | 337 | |
|
341 | 338 | Instances also have a verbose flag callbacks can access to control their |
|
342 | 339 | output. For example the default instance repr prints all attributes and |
|
343 | 340 | methods that are not prefixed by an underscore if the printer is in |
|
344 | 341 | verbose mode. |
|
345 | 342 | """ |
|
346 | 343 | |
|
347 | 344 | def __init__(self, output, verbose=False, max_width=79, newline='\n', |
|
348 | 345 | singleton_pprinters=None, type_pprinters=None, deferred_pprinters=None, |
|
349 | 346 | max_seq_length=MAX_SEQ_LENGTH): |
|
350 | 347 | |
|
351 | 348 | PrettyPrinter.__init__(self, output, max_width, newline, max_seq_length=max_seq_length) |
|
352 | 349 | self.verbose = verbose |
|
353 | 350 | self.stack = [] |
|
354 | 351 | if singleton_pprinters is None: |
|
355 | 352 | singleton_pprinters = _singleton_pprinters.copy() |
|
356 | 353 | self.singleton_pprinters = singleton_pprinters |
|
357 | 354 | if type_pprinters is None: |
|
358 | 355 | type_pprinters = _type_pprinters.copy() |
|
359 | 356 | self.type_pprinters = type_pprinters |
|
360 | 357 | if deferred_pprinters is None: |
|
361 | 358 | deferred_pprinters = _deferred_type_pprinters.copy() |
|
362 | 359 | self.deferred_pprinters = deferred_pprinters |
|
363 | 360 | |
|
364 | 361 | def pretty(self, obj): |
|
365 | 362 | """Pretty print the given object.""" |
|
366 | 363 | obj_id = id(obj) |
|
367 | 364 | cycle = obj_id in self.stack |
|
368 | 365 | self.stack.append(obj_id) |
|
369 | 366 | self.begin_group() |
|
370 | 367 | try: |
|
371 | 368 | obj_class = _safe_getattr(obj, '__class__', None) or type(obj) |
|
372 | 369 | # First try to find registered singleton printers for the type. |
|
373 | 370 | try: |
|
374 | 371 | printer = self.singleton_pprinters[obj_id] |
|
375 | 372 | except (TypeError, KeyError): |
|
376 | 373 | pass |
|
377 | 374 | else: |
|
378 | 375 | return printer(obj, self, cycle) |
|
379 | 376 | # Next walk the mro and check for either: |
|
380 | 377 | # 1) a registered printer |
|
381 | 378 | # 2) a _repr_pretty_ method |
|
382 | 379 | for cls in _get_mro(obj_class): |
|
383 | 380 | if cls in self.type_pprinters: |
|
384 | 381 | # printer registered in self.type_pprinters |
|
385 | 382 | return self.type_pprinters[cls](obj, self, cycle) |
|
386 | 383 | else: |
|
387 | 384 | # deferred printer |
|
388 | 385 | printer = self._in_deferred_types(cls) |
|
389 | 386 | if printer is not None: |
|
390 | 387 | return printer(obj, self, cycle) |
|
391 | 388 | else: |
|
392 | 389 | # Finally look for special method names. |
|
393 | 390 | # Some objects automatically create any requested |
|
394 | 391 | # attribute. Try to ignore most of them by checking for |
|
395 | 392 | # callability. |
|
396 | 393 | if '_repr_pretty_' in cls.__dict__: |
|
397 | 394 | meth = cls._repr_pretty_ |
|
398 | 395 | if callable(meth): |
|
399 | 396 | return meth(obj, self, cycle) |
|
400 | 397 | if cls is not object \ |
|
401 | 398 | and callable(cls.__dict__.get('__repr__')): |
|
402 | 399 | return _repr_pprint(obj, self, cycle) |
|
403 | 400 | |
|
404 | 401 | return _default_pprint(obj, self, cycle) |
|
405 | 402 | finally: |
|
406 | 403 | self.end_group() |
|
407 | 404 | self.stack.pop() |
|
408 | 405 | |
|
409 | 406 | def _in_deferred_types(self, cls): |
|
410 | 407 | """ |
|
411 | 408 | Check if the given class is specified in the deferred type registry. |
|
412 | 409 | |
|
413 | 410 | Returns the printer from the registry if it exists, and None if the |
|
414 | 411 | class is not in the registry. Successful matches will be moved to the |
|
415 | 412 | regular type registry for future use. |
|
416 | 413 | """ |
|
417 | 414 | mod = _safe_getattr(cls, '__module__', None) |
|
418 | 415 | name = _safe_getattr(cls, '__name__', None) |
|
419 | 416 | key = (mod, name) |
|
420 | 417 | printer = None |
|
421 | 418 | if key in self.deferred_pprinters: |
|
422 | 419 | # Move the printer over to the regular registry. |
|
423 | 420 | printer = self.deferred_pprinters.pop(key) |
|
424 | 421 | self.type_pprinters[cls] = printer |
|
425 | 422 | return printer |
|
426 | 423 | |
|
427 | 424 | |
|
428 | 425 | class Printable(object): |
|
429 | 426 | |
|
430 | 427 | def output(self, stream, output_width): |
|
431 | 428 | return output_width |
|
432 | 429 | |
|
433 | 430 | |
|
434 | 431 | class Text(Printable): |
|
435 | 432 | |
|
436 | 433 | def __init__(self): |
|
437 | 434 | self.objs = [] |
|
438 | 435 | self.width = 0 |
|
439 | 436 | |
|
440 | 437 | def output(self, stream, output_width): |
|
441 | 438 | for obj in self.objs: |
|
442 | 439 | stream.write(obj) |
|
443 | 440 | return output_width + self.width |
|
444 | 441 | |
|
445 | 442 | def add(self, obj, width): |
|
446 | 443 | self.objs.append(obj) |
|
447 | 444 | self.width += width |
|
448 | 445 | |
|
449 | 446 | |
|
450 | 447 | class Breakable(Printable): |
|
451 | 448 | |
|
452 | 449 | def __init__(self, seq, width, pretty): |
|
453 | 450 | self.obj = seq |
|
454 | 451 | self.width = width |
|
455 | 452 | self.pretty = pretty |
|
456 | 453 | self.indentation = pretty.indentation |
|
457 | 454 | self.group = pretty.group_stack[-1] |
|
458 | 455 | self.group.breakables.append(self) |
|
459 | 456 | |
|
460 | 457 | def output(self, stream, output_width): |
|
461 | 458 | self.group.breakables.popleft() |
|
462 | 459 | if self.group.want_break: |
|
463 | 460 | stream.write(self.pretty.newline) |
|
464 | 461 | stream.write(' ' * self.indentation) |
|
465 | 462 | return self.indentation |
|
466 | 463 | if not self.group.breakables: |
|
467 | 464 | self.pretty.group_queue.remove(self.group) |
|
468 | 465 | stream.write(self.obj) |
|
469 | 466 | return output_width + self.width |
|
470 | 467 | |
|
471 | 468 | |
|
472 | 469 | class Group(Printable): |
|
473 | 470 | |
|
474 | 471 | def __init__(self, depth): |
|
475 | 472 | self.depth = depth |
|
476 | 473 | self.breakables = deque() |
|
477 | 474 | self.want_break = False |
|
478 | 475 | |
|
479 | 476 | |
|
480 | 477 | class GroupQueue(object): |
|
481 | 478 | |
|
482 | 479 | def __init__(self, *groups): |
|
483 | 480 | self.queue = [] |
|
484 | 481 | for group in groups: |
|
485 | 482 | self.enq(group) |
|
486 | 483 | |
|
487 | 484 | def enq(self, group): |
|
488 | 485 | depth = group.depth |
|
489 | 486 | while depth > len(self.queue) - 1: |
|
490 | 487 | self.queue.append([]) |
|
491 | 488 | self.queue[depth].append(group) |
|
492 | 489 | |
|
493 | 490 | def deq(self): |
|
494 | 491 | for stack in self.queue: |
|
495 | 492 | for idx, group in enumerate(reversed(stack)): |
|
496 | 493 | if group.breakables: |
|
497 | 494 | del stack[idx] |
|
498 | 495 | group.want_break = True |
|
499 | 496 | return group |
|
500 | 497 | for group in stack: |
|
501 | 498 | group.want_break = True |
|
502 | 499 | del stack[:] |
|
503 | 500 | |
|
504 | 501 | def remove(self, group): |
|
505 | 502 | try: |
|
506 | 503 | self.queue[group.depth].remove(group) |
|
507 | 504 | except ValueError: |
|
508 | 505 | pass |
|
509 | 506 | |
|
510 | 507 | |
|
511 | 508 | def _default_pprint(obj, p, cycle): |
|
512 | 509 | """ |
|
513 | 510 | The default print function. Used if an object does not provide one and |
|
514 | 511 | it's none of the builtin objects. |
|
515 | 512 | """ |
|
516 | 513 | klass = _safe_getattr(obj, '__class__', None) or type(obj) |
|
517 | 514 | if _safe_getattr(klass, '__repr__', None) is not object.__repr__: |
|
518 | 515 | # A user-provided repr. Find newlines and replace them with p.break_() |
|
519 | 516 | _repr_pprint(obj, p, cycle) |
|
520 | 517 | return |
|
521 | 518 | p.begin_group(1, '<') |
|
522 | 519 | p.pretty(klass) |
|
523 | 520 | p.text(' at 0x%x' % id(obj)) |
|
524 | 521 | if cycle: |
|
525 | 522 | p.text(' ...') |
|
526 | 523 | elif p.verbose: |
|
527 | 524 | first = True |
|
528 | 525 | for key in dir(obj): |
|
529 | 526 | if not key.startswith('_'): |
|
530 | 527 | try: |
|
531 | 528 | value = getattr(obj, key) |
|
532 | 529 | except AttributeError: |
|
533 | 530 | continue |
|
534 | 531 | if isinstance(value, types.MethodType): |
|
535 | 532 | continue |
|
536 | 533 | if not first: |
|
537 | 534 | p.text(',') |
|
538 | 535 | p.breakable() |
|
539 | 536 | p.text(key) |
|
540 | 537 | p.text('=') |
|
541 | 538 | step = len(key) + 1 |
|
542 | 539 | p.indentation += step |
|
543 | 540 | p.pretty(value) |
|
544 | 541 | p.indentation -= step |
|
545 | 542 | first = False |
|
546 | 543 | p.end_group(1, '>') |
|
547 | 544 | |
|
548 | 545 | |
|
549 | 546 | def _seq_pprinter_factory(start, end): |
|
550 | 547 | """ |
|
551 | 548 | Factory that returns a pprint function useful for sequences. Used by |
|
552 | 549 | the default pprint for tuples, dicts, and lists. |
|
553 | 550 | """ |
|
554 | 551 | def inner(obj, p, cycle): |
|
555 | 552 | if cycle: |
|
556 | 553 | return p.text(start + '...' + end) |
|
557 | 554 | step = len(start) |
|
558 | 555 | p.begin_group(step, start) |
|
559 | 556 | for idx, x in p._enumerate(obj): |
|
560 | 557 | if idx: |
|
561 | 558 | p.text(',') |
|
562 | 559 | p.breakable() |
|
563 | 560 | p.pretty(x) |
|
564 | 561 | if len(obj) == 1 and type(obj) is tuple: |
|
565 | 562 | # Special case for 1-item tuples. |
|
566 | 563 | p.text(',') |
|
567 | 564 | p.end_group(step, end) |
|
568 | 565 | return inner |
|
569 | 566 | |
|
570 | 567 | |
|
571 | 568 | def _set_pprinter_factory(start, end): |
|
572 | 569 | """ |
|
573 | 570 | Factory that returns a pprint function useful for sets and frozensets. |
|
574 | 571 | """ |
|
575 | 572 | def inner(obj, p, cycle): |
|
576 | 573 | if cycle: |
|
577 | 574 | return p.text(start + '...' + end) |
|
578 | 575 | if len(obj) == 0: |
|
579 | 576 | # Special case. |
|
580 | 577 | p.text(type(obj).__name__ + '()') |
|
581 | 578 | else: |
|
582 | 579 | step = len(start) |
|
583 | 580 | p.begin_group(step, start) |
|
584 | 581 | # Like dictionary keys, we will try to sort the items if there aren't too many |
|
585 | 582 | if not (p.max_seq_length and len(obj) >= p.max_seq_length): |
|
586 | 583 | items = _sorted_for_pprint(obj) |
|
587 | 584 | else: |
|
588 | 585 | items = obj |
|
589 | 586 | for idx, x in p._enumerate(items): |
|
590 | 587 | if idx: |
|
591 | 588 | p.text(',') |
|
592 | 589 | p.breakable() |
|
593 | 590 | p.pretty(x) |
|
594 | 591 | p.end_group(step, end) |
|
595 | 592 | return inner |
|
596 | 593 | |
|
597 | 594 | |
|
598 | 595 | def _dict_pprinter_factory(start, end): |
|
599 | 596 | """ |
|
600 | 597 | Factory that returns a pprint function used by the default pprint of |
|
601 | 598 | dicts and dict proxies. |
|
602 | 599 | """ |
|
603 | 600 | def inner(obj, p, cycle): |
|
604 | 601 | if cycle: |
|
605 | 602 | return p.text('{...}') |
|
606 | 603 | step = len(start) |
|
607 | 604 | p.begin_group(step, start) |
|
608 | 605 | keys = obj.keys() |
|
609 | # if dict isn't large enough to be truncated, sort keys before displaying | |
|
610 | # From Python 3.7, dicts preserve order by definition, so we don't sort. | |
|
611 | if not DICT_IS_ORDERED \ | |
|
612 | and not (p.max_seq_length and len(obj) >= p.max_seq_length): | |
|
613 | keys = _sorted_for_pprint(keys) | |
|
614 | 606 | for idx, key in p._enumerate(keys): |
|
615 | 607 | if idx: |
|
616 | 608 | p.text(',') |
|
617 | 609 | p.breakable() |
|
618 | 610 | p.pretty(key) |
|
619 | 611 | p.text(': ') |
|
620 | 612 | p.pretty(obj[key]) |
|
621 | 613 | p.end_group(step, end) |
|
622 | 614 | return inner |
|
623 | 615 | |
|
624 | 616 | |
|
625 | 617 | def _super_pprint(obj, p, cycle): |
|
626 | 618 | """The pprint for the super type.""" |
|
627 | 619 | p.begin_group(8, '<super: ') |
|
628 | 620 | p.pretty(obj.__thisclass__) |
|
629 | 621 | p.text(',') |
|
630 | 622 | p.breakable() |
|
631 | 623 | if PYPY: # In PyPy, super() objects don't have __self__ attributes |
|
632 | 624 | dself = obj.__repr__.__self__ |
|
633 | 625 | p.pretty(None if dself is obj else dself) |
|
634 | 626 | else: |
|
635 | 627 | p.pretty(obj.__self__) |
|
636 | 628 | p.end_group(8, '>') |
|
637 | 629 | |
|
638 | 630 | |
|
639 | 631 | def _re_pattern_pprint(obj, p, cycle): |
|
640 | 632 | """The pprint function for regular expression patterns.""" |
|
641 | 633 | p.text('re.compile(') |
|
642 | 634 | pattern = repr(obj.pattern) |
|
643 | 635 | if pattern[:1] in 'uU': |
|
644 | 636 | pattern = pattern[1:] |
|
645 | 637 | prefix = 'ur' |
|
646 | 638 | else: |
|
647 | 639 | prefix = 'r' |
|
648 | 640 | pattern = prefix + pattern.replace('\\\\', '\\') |
|
649 | 641 | p.text(pattern) |
|
650 | 642 | if obj.flags: |
|
651 | 643 | p.text(',') |
|
652 | 644 | p.breakable() |
|
653 | 645 | done_one = False |
|
654 | 646 | for flag in ('TEMPLATE', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL', |
|
655 | 647 | 'UNICODE', 'VERBOSE', 'DEBUG'): |
|
656 | 648 | if obj.flags & getattr(re, flag): |
|
657 | 649 | if done_one: |
|
658 | 650 | p.text('|') |
|
659 | 651 | p.text('re.' + flag) |
|
660 | 652 | done_one = True |
|
661 | 653 | p.text(')') |
|
662 | 654 | |
|
663 | 655 | |
|
664 | 656 | def _type_pprint(obj, p, cycle): |
|
665 | 657 | """The pprint for classes and types.""" |
|
666 | 658 | # Heap allocated types might not have the module attribute, |
|
667 | 659 | # and others may set it to None. |
|
668 | 660 | |
|
669 | 661 | # Checks for a __repr__ override in the metaclass. Can't compare the |
|
670 | 662 | # type(obj).__repr__ directly because in PyPy the representation function |
|
671 | 663 | # inherited from type isn't the same type.__repr__ |
|
672 | 664 | if [m for m in _get_mro(type(obj)) if "__repr__" in vars(m)][:1] != [type]: |
|
673 | 665 | _repr_pprint(obj, p, cycle) |
|
674 | 666 | return |
|
675 | 667 | |
|
676 | 668 | mod = _safe_getattr(obj, '__module__', None) |
|
677 | 669 | try: |
|
678 | 670 | name = obj.__qualname__ |
|
679 | 671 | if not isinstance(name, str): |
|
680 | 672 | # This can happen if the type implements __qualname__ as a property |
|
681 | 673 | # or other descriptor in Python 2. |
|
682 | 674 | raise Exception("Try __name__") |
|
683 | 675 | except Exception: |
|
684 | 676 | name = obj.__name__ |
|
685 | 677 | if not isinstance(name, str): |
|
686 | 678 | name = '<unknown type>' |
|
687 | 679 | |
|
688 | 680 | if mod in (None, '__builtin__', 'builtins', 'exceptions'): |
|
689 | 681 | p.text(name) |
|
690 | 682 | else: |
|
691 | 683 | p.text(mod + '.' + name) |
|
692 | 684 | |
|
693 | 685 | |
|
694 | 686 | def _repr_pprint(obj, p, cycle): |
|
695 | 687 | """A pprint that just redirects to the normal repr function.""" |
|
696 | 688 | # Find newlines and replace them with p.break_() |
|
697 | 689 | output = repr(obj) |
|
698 | 690 | for idx,output_line in enumerate(output.splitlines()): |
|
699 | 691 | if idx: |
|
700 | 692 | p.break_() |
|
701 | 693 | p.text(output_line) |
|
702 | 694 | |
|
703 | 695 | |
|
704 | 696 | def _function_pprint(obj, p, cycle): |
|
705 | 697 | """Base pprint for all functions and builtin functions.""" |
|
706 | 698 | name = _safe_getattr(obj, '__qualname__', obj.__name__) |
|
707 | 699 | mod = obj.__module__ |
|
708 | 700 | if mod and mod not in ('__builtin__', 'builtins', 'exceptions'): |
|
709 | 701 | name = mod + '.' + name |
|
710 | 702 | try: |
|
711 | 703 | func_def = name + str(signature(obj)) |
|
712 | 704 | except ValueError: |
|
713 | 705 | func_def = name |
|
714 | 706 | p.text('<function %s>' % func_def) |
|
715 | 707 | |
|
716 | 708 | |
|
717 | 709 | def _exception_pprint(obj, p, cycle): |
|
718 | 710 | """Base pprint for all exceptions.""" |
|
719 | 711 | name = getattr(obj.__class__, '__qualname__', obj.__class__.__name__) |
|
720 | 712 | if obj.__class__.__module__ not in ('exceptions', 'builtins'): |
|
721 | 713 | name = '%s.%s' % (obj.__class__.__module__, name) |
|
722 | 714 | step = len(name) + 1 |
|
723 | 715 | p.begin_group(step, name + '(') |
|
724 | 716 | for idx, arg in enumerate(getattr(obj, 'args', ())): |
|
725 | 717 | if idx: |
|
726 | 718 | p.text(',') |
|
727 | 719 | p.breakable() |
|
728 | 720 | p.pretty(arg) |
|
729 | 721 | p.end_group(step, ')') |
|
730 | 722 | |
|
731 | 723 | |
|
732 | 724 | #: the exception base |
|
733 | 725 | try: |
|
734 | 726 | _exception_base = BaseException |
|
735 | 727 | except NameError: |
|
736 | 728 | _exception_base = Exception |
|
737 | 729 | |
|
738 | 730 | |
|
739 | 731 | #: printers for builtin types |
|
740 | 732 | _type_pprinters = { |
|
741 | 733 | int: _repr_pprint, |
|
742 | 734 | float: _repr_pprint, |
|
743 | 735 | str: _repr_pprint, |
|
744 | 736 | tuple: _seq_pprinter_factory('(', ')'), |
|
745 | 737 | list: _seq_pprinter_factory('[', ']'), |
|
746 | 738 | dict: _dict_pprinter_factory('{', '}'), |
|
747 | 739 | set: _set_pprinter_factory('{', '}'), |
|
748 | 740 | frozenset: _set_pprinter_factory('frozenset({', '})'), |
|
749 | 741 | super: _super_pprint, |
|
750 | 742 | _re_pattern_type: _re_pattern_pprint, |
|
751 | 743 | type: _type_pprint, |
|
752 | 744 | types.FunctionType: _function_pprint, |
|
753 | 745 | types.BuiltinFunctionType: _function_pprint, |
|
754 | 746 | types.MethodType: _repr_pprint, |
|
755 | 747 | datetime.datetime: _repr_pprint, |
|
756 | 748 | datetime.timedelta: _repr_pprint, |
|
757 | 749 | _exception_base: _exception_pprint |
|
758 | 750 | } |
|
759 | 751 | |
|
760 | 752 | # render os.environ like a dict |
|
761 | 753 | _env_type = type(os.environ) |
|
762 | 754 | # future-proof in case os.environ becomes a plain dict? |
|
763 | 755 | if _env_type is not dict: |
|
764 | 756 | _type_pprinters[_env_type] = _dict_pprinter_factory('environ{', '}') |
|
765 | 757 | |
|
766 | 758 | try: |
|
767 | 759 | # In PyPy, types.DictProxyType is dict, setting the dictproxy printer |
|
768 | 760 | # using dict.setdefault avoids overwriting the dict printer |
|
769 | 761 | _type_pprinters.setdefault(types.DictProxyType, |
|
770 | 762 | _dict_pprinter_factory('dict_proxy({', '})')) |
|
771 | 763 | _type_pprinters[types.ClassType] = _type_pprint |
|
772 | 764 | _type_pprinters[types.SliceType] = _repr_pprint |
|
773 | 765 | except AttributeError: # Python 3 |
|
774 | 766 | _type_pprinters[types.MappingProxyType] = \ |
|
775 | 767 | _dict_pprinter_factory('mappingproxy({', '})') |
|
776 | 768 | _type_pprinters[slice] = _repr_pprint |
|
777 | 769 | |
|
778 | 770 | try: |
|
779 | 771 | _type_pprinters[long] = _repr_pprint |
|
780 | 772 | _type_pprinters[unicode] = _repr_pprint |
|
781 | 773 | except NameError: |
|
782 | 774 | _type_pprinters[range] = _repr_pprint |
|
783 | 775 | _type_pprinters[bytes] = _repr_pprint |
|
784 | 776 | |
|
785 | 777 | #: printers for types specified by name |
|
786 | 778 | _deferred_type_pprinters = { |
|
787 | 779 | } |
|
788 | 780 | |
|
789 | 781 | def for_type(typ, func): |
|
790 | 782 | """ |
|
791 | 783 | Add a pretty printer for a given type. |
|
792 | 784 | """ |
|
793 | 785 | oldfunc = _type_pprinters.get(typ, None) |
|
794 | 786 | if func is not None: |
|
795 | 787 | # To support easy restoration of old pprinters, we need to ignore Nones. |
|
796 | 788 | _type_pprinters[typ] = func |
|
797 | 789 | return oldfunc |
|
798 | 790 | |
|
799 | 791 | def for_type_by_name(type_module, type_name, func): |
|
800 | 792 | """ |
|
801 | 793 | Add a pretty printer for a type specified by the module and name of a type |
|
802 | 794 | rather than the type object itself. |
|
803 | 795 | """ |
|
804 | 796 | key = (type_module, type_name) |
|
805 | 797 | oldfunc = _deferred_type_pprinters.get(key, None) |
|
806 | 798 | if func is not None: |
|
807 | 799 | # To support easy restoration of old pprinters, we need to ignore Nones. |
|
808 | 800 | _deferred_type_pprinters[key] = func |
|
809 | 801 | return oldfunc |
|
810 | 802 | |
|
811 | 803 | |
|
812 | 804 | #: printers for the default singletons |
|
813 | 805 | _singleton_pprinters = dict.fromkeys(map(id, [None, True, False, Ellipsis, |
|
814 | 806 | NotImplemented]), _repr_pprint) |
|
815 | 807 | |
|
816 | 808 | |
|
817 | 809 | def _defaultdict_pprint(obj, p, cycle): |
|
818 | 810 | name = obj.__class__.__name__ |
|
819 | 811 | with p.group(len(name) + 1, name + '(', ')'): |
|
820 | 812 | if cycle: |
|
821 | 813 | p.text('...') |
|
822 | 814 | else: |
|
823 | 815 | p.pretty(obj.default_factory) |
|
824 | 816 | p.text(',') |
|
825 | 817 | p.breakable() |
|
826 | 818 | p.pretty(dict(obj)) |
|
827 | 819 | |
|
828 | 820 | def _ordereddict_pprint(obj, p, cycle): |
|
829 | 821 | name = obj.__class__.__name__ |
|
830 | 822 | with p.group(len(name) + 1, name + '(', ')'): |
|
831 | 823 | if cycle: |
|
832 | 824 | p.text('...') |
|
833 | 825 | elif len(obj): |
|
834 | 826 | p.pretty(list(obj.items())) |
|
835 | 827 | |
|
836 | 828 | def _deque_pprint(obj, p, cycle): |
|
837 | 829 | name = obj.__class__.__name__ |
|
838 | 830 | with p.group(len(name) + 1, name + '(', ')'): |
|
839 | 831 | if cycle: |
|
840 | 832 | p.text('...') |
|
841 | 833 | else: |
|
842 | 834 | p.pretty(list(obj)) |
|
843 | 835 | |
|
844 | 836 | |
|
845 | 837 | def _counter_pprint(obj, p, cycle): |
|
846 | 838 | name = obj.__class__.__name__ |
|
847 | 839 | with p.group(len(name) + 1, name + '(', ')'): |
|
848 | 840 | if cycle: |
|
849 | 841 | p.text('...') |
|
850 | 842 | elif len(obj): |
|
851 | 843 | p.pretty(dict(obj)) |
|
852 | 844 | |
|
853 | 845 | for_type_by_name('collections', 'defaultdict', _defaultdict_pprint) |
|
854 | 846 | for_type_by_name('collections', 'OrderedDict', _ordereddict_pprint) |
|
855 | 847 | for_type_by_name('collections', 'deque', _deque_pprint) |
|
856 | 848 | for_type_by_name('collections', 'Counter', _counter_pprint) |
|
857 | 849 | |
|
858 | 850 | if __name__ == '__main__': |
|
859 | 851 | from random import randrange |
|
860 | 852 | class Foo(object): |
|
861 | 853 | def __init__(self): |
|
862 | 854 | self.foo = 1 |
|
863 | 855 | self.bar = re.compile(r'\s+') |
|
864 | 856 | self.blub = dict.fromkeys(range(30), randrange(1, 40)) |
|
865 | 857 | self.hehe = 23424.234234 |
|
866 | 858 | self.list = ["blub", "blah", self] |
|
867 | 859 | |
|
868 | 860 | def get_foo(self): |
|
869 | 861 | print("foo") |
|
870 | 862 | |
|
871 | 863 | pprint(Foo(), verbose=True) |
@@ -1,119 +1,119 b'' | |||
|
1 | 1 | """Find files and directories which IPython uses. |
|
2 | 2 | """ |
|
3 | 3 | import os.path |
|
4 | 4 | import shutil |
|
5 | 5 | import tempfile |
|
6 | 6 | from warnings import warn |
|
7 | 7 | |
|
8 | 8 | import IPython |
|
9 | 9 | from IPython.utils.importstring import import_item |
|
10 | 10 | from IPython.utils.path import ( |
|
11 | 11 | get_home_dir, get_xdg_dir, get_xdg_cache_dir, compress_user, _writable_dir, |
|
12 | 12 | ensure_dir_exists, fs_encoding) |
|
13 | 13 | from IPython.utils import py3compat |
|
14 | 14 | |
|
15 | def get_ipython_dir(): | |
|
15 | def get_ipython_dir() -> str: | |
|
16 | 16 | """Get the IPython directory for this platform and user. |
|
17 | 17 | |
|
18 | 18 | This uses the logic in `get_home_dir` to find the home directory |
|
19 | 19 | and then adds .ipython to the end of the path. |
|
20 | 20 | """ |
|
21 | 21 | |
|
22 | 22 | env = os.environ |
|
23 | 23 | pjoin = os.path.join |
|
24 | 24 | |
|
25 | 25 | |
|
26 | 26 | ipdir_def = '.ipython' |
|
27 | 27 | |
|
28 | 28 | home_dir = get_home_dir() |
|
29 | 29 | xdg_dir = get_xdg_dir() |
|
30 | 30 | |
|
31 | # import pdb; pdb.set_trace() # dbg | |
|
32 | 31 | if 'IPYTHON_DIR' in env: |
|
33 | warn('The environment variable IPYTHON_DIR is deprecated. ' | |
|
34 | 'Please use IPYTHONDIR instead.') | |
|
32 | warn('The environment variable IPYTHON_DIR is deprecated since IPython 3.0. ' | |
|
33 | 'Please use IPYTHONDIR instead.', DeprecationWarning) | |
|
35 | 34 | ipdir = env.get('IPYTHONDIR', env.get('IPYTHON_DIR', None)) |
|
36 | 35 | if ipdir is None: |
|
37 | 36 | # not set explicitly, use ~/.ipython |
|
38 | 37 | ipdir = pjoin(home_dir, ipdir_def) |
|
39 | 38 | if xdg_dir: |
|
40 | 39 | # Several IPython versions (up to 1.x) defaulted to .config/ipython |
|
41 | 40 | # on Linux. We have decided to go back to using .ipython everywhere |
|
42 | 41 | xdg_ipdir = pjoin(xdg_dir, 'ipython') |
|
43 | 42 | |
|
44 | 43 | if _writable_dir(xdg_ipdir): |
|
45 | 44 | cu = compress_user |
|
46 | 45 | if os.path.exists(ipdir): |
|
47 | 46 | warn(('Ignoring {0} in favour of {1}. Remove {0} to ' |
|
48 | 47 | 'get rid of this message').format(cu(xdg_ipdir), cu(ipdir))) |
|
49 | 48 | elif os.path.islink(xdg_ipdir): |
|
50 | 49 | warn(('{0} is deprecated. Move link to {1} to ' |
|
51 | 50 | 'get rid of this message').format(cu(xdg_ipdir), cu(ipdir))) |
|
52 | 51 | else: |
|
53 | 52 | warn('Moving {0} to {1}'.format(cu(xdg_ipdir), cu(ipdir))) |
|
54 | 53 | shutil.move(xdg_ipdir, ipdir) |
|
55 | 54 | |
|
56 | 55 | ipdir = os.path.normpath(os.path.expanduser(ipdir)) |
|
57 | 56 | |
|
58 | 57 | if os.path.exists(ipdir) and not _writable_dir(ipdir): |
|
59 | 58 | # ipdir exists, but is not writable |
|
60 | 59 | warn("IPython dir '{0}' is not a writable location," |
|
61 | 60 | " using a temp directory.".format(ipdir)) |
|
62 | 61 | ipdir = tempfile.mkdtemp() |
|
63 | 62 | elif not os.path.exists(ipdir): |
|
64 | 63 | parent = os.path.dirname(ipdir) |
|
65 | 64 | if not _writable_dir(parent): |
|
66 | 65 | # ipdir does not exist and parent isn't writable |
|
67 | 66 | warn("IPython parent '{0}' is not a writable location," |
|
68 | 67 | " using a temp directory.".format(parent)) |
|
69 | 68 | ipdir = tempfile.mkdtemp() |
|
69 | assert isinstance(ipdir, str), "all path manipulation should be str(unicode), but are not." | |
|
70 | return ipdir | |
|
70 | 71 | |
|
71 | return py3compat.cast_unicode(ipdir, fs_encoding) | |
|
72 | 72 | |
|
73 | ||
|
74 | def get_ipython_cache_dir(): | |
|
73 | def get_ipython_cache_dir() -> str: | |
|
75 | 74 | """Get the cache directory it is created if it does not exist.""" |
|
76 | 75 | xdgdir = get_xdg_cache_dir() |
|
77 | 76 | if xdgdir is None: |
|
78 | 77 | return get_ipython_dir() |
|
79 | 78 | ipdir = os.path.join(xdgdir, "ipython") |
|
80 | 79 | if not os.path.exists(ipdir) and _writable_dir(xdgdir): |
|
81 | 80 | ensure_dir_exists(ipdir) |
|
82 | 81 | elif not _writable_dir(xdgdir): |
|
83 | 82 | return get_ipython_dir() |
|
84 | 83 | |
|
85 | return py3compat.cast_unicode(ipdir, fs_encoding) | |
|
84 | return ipdir | |
|
86 | 85 | |
|
87 | 86 | |
|
88 | def get_ipython_package_dir(): | |
|
87 | def get_ipython_package_dir() -> str: | |
|
89 | 88 | """Get the base directory where IPython itself is installed.""" |
|
90 | 89 | ipdir = os.path.dirname(IPython.__file__) |
|
91 | return py3compat.cast_unicode(ipdir, fs_encoding) | |
|
90 | assert isinstance(ipdir, str) | |
|
91 | return ipdir | |
|
92 | 92 | |
|
93 | 93 | |
|
94 | 94 | def get_ipython_module_path(module_str): |
|
95 | 95 | """Find the path to an IPython module in this version of IPython. |
|
96 | 96 | |
|
97 | 97 | This will always find the version of the module that is in this importable |
|
98 | 98 | IPython package. This will always return the path to the ``.py`` |
|
99 | 99 | version of the module. |
|
100 | 100 | """ |
|
101 | 101 | if module_str == 'IPython': |
|
102 | 102 | return os.path.join(get_ipython_package_dir(), '__init__.py') |
|
103 | 103 | mod = import_item(module_str) |
|
104 | 104 | the_path = mod.__file__.replace('.pyc', '.py') |
|
105 | 105 | the_path = the_path.replace('.pyo', '.py') |
|
106 | 106 | return py3compat.cast_unicode(the_path, fs_encoding) |
|
107 | 107 | |
|
108 | 108 | def locate_profile(profile='default'): |
|
109 | 109 | """Find the path to the folder associated with a given profile. |
|
110 | 110 | |
|
111 | 111 | I.e. find $IPYTHONDIR/profile_whatever. |
|
112 | 112 | """ |
|
113 | 113 | from IPython.core.profiledir import ProfileDir, ProfileDirError |
|
114 | 114 | try: |
|
115 | 115 | pd = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile) |
|
116 | 116 | except ProfileDirError: |
|
117 | 117 | # IOError makes more sense when people are expecting a path |
|
118 | 118 | raise IOError("Couldn't find profile %r" % profile) |
|
119 | 119 | return pd.location |
@@ -1,120 +1,126 b'' | |||
|
1 | 1 | import signal |
|
2 | 2 | import sys |
|
3 | 3 | |
|
4 | 4 | from IPython.core.debugger import Pdb |
|
5 | 5 | |
|
6 | 6 | from IPython.core.completer import IPCompleter |
|
7 | 7 | from .ptutils import IPythonPTCompleter |
|
8 | 8 | from .shortcuts import suspend_to_bg, cursor_in_leading_ws |
|
9 | 9 | |
|
10 | 10 | from prompt_toolkit.enums import DEFAULT_BUFFER |
|
11 | 11 | from prompt_toolkit.filters import (Condition, has_focus, has_selection, |
|
12 | 12 | vi_insert_mode, emacs_insert_mode) |
|
13 | 13 | from prompt_toolkit.key_binding import KeyBindings |
|
14 | 14 | from prompt_toolkit.key_binding.bindings.completion import display_completions_like_readline |
|
15 | 15 | from pygments.token import Token |
|
16 | 16 | from prompt_toolkit.shortcuts.prompt import PromptSession |
|
17 | 17 | from prompt_toolkit.enums import EditingMode |
|
18 | 18 | from prompt_toolkit.formatted_text import PygmentsTokens |
|
19 | 19 | |
|
20 | from prompt_toolkit import __version__ as ptk_version | |
|
21 | PTK3 = ptk_version.startswith('3.') | |
|
22 | ||
|
20 | 23 | |
|
21 | 24 | class TerminalPdb(Pdb): |
|
22 | 25 | """Standalone IPython debugger.""" |
|
23 | 26 | |
|
24 | 27 | def __init__(self, *args, **kwargs): |
|
25 | 28 | Pdb.__init__(self, *args, **kwargs) |
|
26 | 29 | self._ptcomp = None |
|
27 | 30 | self.pt_init() |
|
28 | 31 | |
|
29 | 32 | def pt_init(self): |
|
30 | 33 | def get_prompt_tokens(): |
|
31 | 34 | return [(Token.Prompt, self.prompt)] |
|
32 | 35 | |
|
33 | 36 | if self._ptcomp is None: |
|
34 | 37 | compl = IPCompleter(shell=self.shell, |
|
35 | 38 | namespace={}, |
|
36 | 39 | global_namespace={}, |
|
37 | 40 | parent=self.shell, |
|
38 | 41 | ) |
|
39 | 42 | self._ptcomp = IPythonPTCompleter(compl) |
|
40 | 43 | |
|
41 | 44 | kb = KeyBindings() |
|
42 | 45 | supports_suspend = Condition(lambda: hasattr(signal, 'SIGTSTP')) |
|
43 | 46 | kb.add('c-z', filter=supports_suspend)(suspend_to_bg) |
|
44 | 47 | |
|
45 | 48 | if self.shell.display_completions == 'readlinelike': |
|
46 | 49 | kb.add('tab', filter=(has_focus(DEFAULT_BUFFER) |
|
47 | 50 | & ~has_selection |
|
48 | 51 | & vi_insert_mode | emacs_insert_mode |
|
49 | 52 | & ~cursor_in_leading_ws |
|
50 | 53 | ))(display_completions_like_readline) |
|
51 | 54 | |
|
52 | self.pt_app = PromptSession( | |
|
53 |
|
|
|
54 |
|
|
|
55 |
|
|
|
56 |
|
|
|
57 |
|
|
|
58 |
|
|
|
59 |
|
|
|
60 |
|
|
|
61 |
|
|
|
62 | inputhook=self.shell.inputhook, | |
|
63 | color_depth=self.shell.color_depth, | |
|
55 | options = dict( | |
|
56 | message=(lambda: PygmentsTokens(get_prompt_tokens())), | |
|
57 | editing_mode=getattr(EditingMode, self.shell.editing_mode.upper()), | |
|
58 | key_bindings=kb, | |
|
59 | history=self.shell.debugger_history, | |
|
60 | completer=self._ptcomp, | |
|
61 | enable_history_search=True, | |
|
62 | mouse_support=self.shell.mouse_support, | |
|
63 | complete_style=self.shell.pt_complete_style, | |
|
64 | style=self.shell.style, | |
|
65 | color_depth=self.shell.color_depth, | |
|
64 | 66 | ) |
|
65 | 67 | |
|
68 | if not PTK3: | |
|
69 | options['inputhook'] = self.shell.inputhook | |
|
70 | self.pt_app = PromptSession(**options) | |
|
71 | ||
|
66 | 72 | def cmdloop(self, intro=None): |
|
67 | 73 | """Repeatedly issue a prompt, accept input, parse an initial prefix |
|
68 | 74 | off the received input, and dispatch to action methods, passing them |
|
69 | 75 | the remainder of the line as argument. |
|
70 | 76 | |
|
71 | 77 | override the same methods from cmd.Cmd to provide prompt toolkit replacement. |
|
72 | 78 | """ |
|
73 | 79 | if not self.use_rawinput: |
|
74 | 80 | raise ValueError('Sorry ipdb does not support use_rawinput=False') |
|
75 | 81 | |
|
76 | 82 | self.preloop() |
|
77 | 83 | |
|
78 | 84 | try: |
|
79 | 85 | if intro is not None: |
|
80 | 86 | self.intro = intro |
|
81 | 87 | if self.intro: |
|
82 | 88 | self.stdout.write(str(self.intro)+"\n") |
|
83 | 89 | stop = None |
|
84 | 90 | while not stop: |
|
85 | 91 | if self.cmdqueue: |
|
86 | 92 | line = self.cmdqueue.pop(0) |
|
87 | 93 | else: |
|
88 | 94 | self._ptcomp.ipy_completer.namespace = self.curframe_locals |
|
89 | 95 | self._ptcomp.ipy_completer.global_namespace = self.curframe.f_globals |
|
90 | 96 | try: |
|
91 | 97 | line = self.pt_app.prompt() # reset_current_buffer=True) |
|
92 | 98 | except EOFError: |
|
93 | 99 | line = 'EOF' |
|
94 | 100 | line = self.precmd(line) |
|
95 | 101 | stop = self.onecmd(line) |
|
96 | 102 | stop = self.postcmd(stop, line) |
|
97 | 103 | self.postloop() |
|
98 | 104 | except Exception: |
|
99 | 105 | raise |
|
100 | 106 | |
|
101 | 107 | |
|
102 | 108 | def set_trace(frame=None): |
|
103 | 109 | """ |
|
104 | 110 | Start debugging from `frame`. |
|
105 | 111 | |
|
106 | 112 | If frame is not specified, debugging starts from caller's frame. |
|
107 | 113 | """ |
|
108 | 114 | TerminalPdb().set_trace(frame or sys._getframe().f_back) |
|
109 | 115 | |
|
110 | 116 | |
|
111 | 117 | if __name__ == '__main__': |
|
112 | 118 | import pdb |
|
113 | 119 | # IPython.core.debugger.Pdb.trace_dispatch shall not catch |
|
114 | 120 | # bdb.BdbQuit. When started through __main__ and an exception |
|
115 | 121 | # happened after hitting "c", this is needed in order to |
|
116 | 122 | # be able to quit the debugging session (see #9950). |
|
117 | 123 | old_trace_dispatch = pdb.Pdb.trace_dispatch |
|
118 | 124 | pdb.Pdb = TerminalPdb |
|
119 | 125 | pdb.Pdb.trace_dispatch = old_trace_dispatch |
|
120 | 126 | pdb.main() |
@@ -1,570 +1,640 b'' | |||
|
1 | 1 | """IPython terminal interface using prompt_toolkit""" |
|
2 | 2 | |
|
3 | import asyncio | |
|
3 | 4 | import os |
|
4 | 5 | import sys |
|
5 | 6 | import warnings |
|
6 | 7 | from warnings import warn |
|
7 | 8 | |
|
8 | 9 | from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC |
|
9 | 10 | from IPython.utils import io |
|
10 | 11 | from IPython.utils.py3compat import input |
|
11 | 12 | from IPython.utils.terminal import toggle_set_term_title, set_term_title, restore_term_title |
|
12 | 13 | from IPython.utils.process import abbrev_cwd |
|
13 | 14 | from traitlets import ( |
|
14 | 15 | Bool, Unicode, Dict, Integer, observe, Instance, Type, default, Enum, Union, |
|
15 | 16 | Any, validate |
|
16 | 17 | ) |
|
17 | 18 | |
|
18 | 19 | from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode |
|
19 | 20 | from prompt_toolkit.filters import (HasFocus, Condition, IsDone) |
|
20 | 21 | from prompt_toolkit.formatted_text import PygmentsTokens |
|
21 | 22 | from prompt_toolkit.history import InMemoryHistory |
|
22 | 23 | from prompt_toolkit.layout.processors import ConditionalProcessor, HighlightMatchingBracketProcessor |
|
23 | 24 | from prompt_toolkit.output import ColorDepth |
|
24 | 25 | from prompt_toolkit.patch_stdout import patch_stdout |
|
25 | 26 | from prompt_toolkit.shortcuts import PromptSession, CompleteStyle, print_formatted_text |
|
26 | 27 | from prompt_toolkit.styles import DynamicStyle, merge_styles |
|
27 | 28 | from prompt_toolkit.styles.pygments import style_from_pygments_cls, style_from_pygments_dict |
|
29 | from prompt_toolkit import __version__ as ptk_version | |
|
28 | 30 | |
|
29 | 31 | from pygments.styles import get_style_by_name |
|
30 | 32 | from pygments.style import Style |
|
31 | 33 | from pygments.token import Token |
|
32 | 34 | |
|
33 | 35 | from .debugger import TerminalPdb, Pdb |
|
34 | 36 | from .magics import TerminalMagics |
|
35 | 37 | from .pt_inputhooks import get_inputhook_name_and_func |
|
36 | 38 | from .prompts import Prompts, ClassicPrompts, RichPromptDisplayHook |
|
37 | 39 | from .ptutils import IPythonPTCompleter, IPythonPTLexer |
|
38 | 40 | from .shortcuts import create_ipython_shortcuts |
|
39 | 41 | |
|
40 | 42 | DISPLAY_BANNER_DEPRECATED = object() |
|
43 | PTK3 = ptk_version.startswith('3.') | |
|
41 | 44 | |
|
42 | 45 | |
|
43 | 46 | class _NoStyle(Style): pass |
|
44 | 47 | |
|
45 | 48 | |
|
46 | 49 | |
|
47 | 50 | _style_overrides_light_bg = { |
|
48 | 51 | Token.Prompt: '#0000ff', |
|
49 | 52 | Token.PromptNum: '#0000ee bold', |
|
50 | 53 | Token.OutPrompt: '#cc0000', |
|
51 | 54 | Token.OutPromptNum: '#bb0000 bold', |
|
52 | 55 | } |
|
53 | 56 | |
|
54 | 57 | _style_overrides_linux = { |
|
55 | 58 | Token.Prompt: '#00cc00', |
|
56 | 59 | Token.PromptNum: '#00bb00 bold', |
|
57 | 60 | Token.OutPrompt: '#cc0000', |
|
58 | 61 | Token.OutPromptNum: '#bb0000 bold', |
|
59 | 62 | } |
|
60 | 63 | |
|
61 | 64 | def get_default_editor(): |
|
62 | 65 | try: |
|
63 | 66 | return os.environ['EDITOR'] |
|
64 | 67 | except KeyError: |
|
65 | 68 | pass |
|
66 | 69 | except UnicodeError: |
|
67 | 70 | warn("$EDITOR environment variable is not pure ASCII. Using platform " |
|
68 | 71 | "default editor.") |
|
69 | 72 | |
|
70 | 73 | if os.name == 'posix': |
|
71 | 74 | return 'vi' # the only one guaranteed to be there! |
|
72 | 75 | else: |
|
73 | 76 | return 'notepad' # same in Windows! |
|
74 | 77 | |
|
75 | 78 | # conservatively check for tty |
|
76 | 79 | # overridden streams can result in things like: |
|
77 | 80 | # - sys.stdin = None |
|
78 | 81 | # - no isatty method |
|
79 | 82 | for _name in ('stdin', 'stdout', 'stderr'): |
|
80 | 83 | _stream = getattr(sys, _name) |
|
81 | 84 | if not _stream or not hasattr(_stream, 'isatty') or not _stream.isatty(): |
|
82 | 85 | _is_tty = False |
|
83 | 86 | break |
|
84 | 87 | else: |
|
85 | 88 | _is_tty = True |
|
86 | 89 | |
|
87 | 90 | |
|
88 | 91 | _use_simple_prompt = ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or (not _is_tty) |
|
89 | 92 | |
|
93 | def black_reformat_handler(text_before_cursor): | |
|
94 | import black | |
|
95 | formatted_text = black.format_str(text_before_cursor, mode=black.FileMode()) | |
|
96 | if not text_before_cursor.endswith('\n') and formatted_text.endswith('\n'): | |
|
97 | formatted_text = formatted_text[:-1] | |
|
98 | return formatted_text | |
|
99 | ||
|
100 | ||
|
90 | 101 | class TerminalInteractiveShell(InteractiveShell): |
|
102 | mime_renderers = Dict().tag(config=True) | |
|
103 | ||
|
91 | 104 | space_for_menu = Integer(6, help='Number of line at the bottom of the screen ' |
|
92 | 105 | 'to reserve for the completion menu' |
|
93 | 106 | ).tag(config=True) |
|
94 | 107 | |
|
95 | 108 | pt_app = None |
|
96 | 109 | debugger_history = None |
|
97 | 110 | |
|
98 | 111 | simple_prompt = Bool(_use_simple_prompt, |
|
99 | 112 | help="""Use `raw_input` for the REPL, without completion and prompt colors. |
|
100 | 113 | |
|
101 | 114 | Useful when controlling IPython as a subprocess, and piping STDIN/OUT/ERR. Known usage are: |
|
102 | 115 | IPython own testing machinery, and emacs inferior-shell integration through elpy. |
|
103 | 116 | |
|
104 | 117 | This mode default to `True` if the `IPY_TEST_SIMPLE_PROMPT` |
|
105 | 118 | environment variable is set, or the current terminal is not a tty.""" |
|
106 | 119 | ).tag(config=True) |
|
107 | 120 | |
|
108 | 121 | @property |
|
109 | 122 | def debugger_cls(self): |
|
110 | 123 | return Pdb if self.simple_prompt else TerminalPdb |
|
111 | 124 | |
|
112 | 125 | confirm_exit = Bool(True, |
|
113 | 126 | help=""" |
|
114 | 127 | Set to confirm when you try to exit IPython with an EOF (Control-D |
|
115 | 128 | in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit', |
|
116 | 129 | you can force a direct exit without any confirmation.""", |
|
117 | 130 | ).tag(config=True) |
|
118 | 131 | |
|
119 | 132 | editing_mode = Unicode('emacs', |
|
120 | 133 | help="Shortcut style to use at the prompt. 'vi' or 'emacs'.", |
|
121 | 134 | ).tag(config=True) |
|
122 | 135 | |
|
136 | autoformatter = Unicode(None, | |
|
137 | help="Autoformatter to reformat Terminal code. Can be `'black'` or `None`", | |
|
138 | allow_none=True | |
|
139 | ).tag(config=True) | |
|
140 | ||
|
123 | 141 | mouse_support = Bool(False, |
|
124 | 142 | help="Enable mouse support in the prompt\n(Note: prevents selecting text with the mouse)" |
|
125 | 143 | ).tag(config=True) |
|
126 | 144 | |
|
127 | 145 | # We don't load the list of styles for the help string, because loading |
|
128 | 146 | # Pygments plugins takes time and can cause unexpected errors. |
|
129 | 147 | highlighting_style = Union([Unicode('legacy'), Type(klass=Style)], |
|
130 | 148 | help="""The name or class of a Pygments style to use for syntax |
|
131 | 149 | highlighting. To see available styles, run `pygmentize -L styles`.""" |
|
132 | 150 | ).tag(config=True) |
|
133 | 151 | |
|
134 | 152 | @validate('editing_mode') |
|
135 | 153 | def _validate_editing_mode(self, proposal): |
|
136 | 154 | if proposal['value'].lower() == 'vim': |
|
137 | 155 | proposal['value']= 'vi' |
|
138 | 156 | elif proposal['value'].lower() == 'default': |
|
139 | 157 | proposal['value']= 'emacs' |
|
140 | 158 | |
|
141 | 159 | if hasattr(EditingMode, proposal['value'].upper()): |
|
142 | 160 | return proposal['value'].lower() |
|
143 | 161 | |
|
144 | 162 | return self.editing_mode |
|
145 | 163 | |
|
146 | 164 | |
|
147 | 165 | @observe('editing_mode') |
|
148 | 166 | def _editing_mode(self, change): |
|
149 | 167 | u_mode = change.new.upper() |
|
150 | 168 | if self.pt_app: |
|
151 | 169 | self.pt_app.editing_mode = u_mode |
|
152 | 170 | |
|
171 | @observe('autoformatter') | |
|
172 | def _autoformatter_changed(self, change): | |
|
173 | formatter = change.new | |
|
174 | if formatter is None: | |
|
175 | self.reformat_handler = lambda x:x | |
|
176 | elif formatter == 'black': | |
|
177 | self.reformat_handler = black_reformat_handler | |
|
178 | else: | |
|
179 | raise ValueError | |
|
180 | ||
|
153 | 181 | @observe('highlighting_style') |
|
154 | 182 | @observe('colors') |
|
155 | 183 | def _highlighting_style_changed(self, change): |
|
156 | 184 | self.refresh_style() |
|
157 | 185 | |
|
158 | 186 | def refresh_style(self): |
|
159 | 187 | self._style = self._make_style_from_name_or_cls(self.highlighting_style) |
|
160 | 188 | |
|
161 | 189 | |
|
162 | 190 | highlighting_style_overrides = Dict( |
|
163 | 191 | help="Override highlighting format for specific tokens" |
|
164 | 192 | ).tag(config=True) |
|
165 | 193 | |
|
166 | 194 | true_color = Bool(False, |
|
167 | 195 | help=("Use 24bit colors instead of 256 colors in prompt highlighting. " |
|
168 | 196 | "If your terminal supports true color, the following command " |
|
169 | 197 | "should print 'TRUECOLOR' in orange: " |
|
170 | 198 | "printf \"\\x1b[38;2;255;100;0mTRUECOLOR\\x1b[0m\\n\"") |
|
171 | 199 | ).tag(config=True) |
|
172 | 200 | |
|
173 | 201 | editor = Unicode(get_default_editor(), |
|
174 | 202 | help="Set the editor used by IPython (default to $EDITOR/vi/notepad)." |
|
175 | 203 | ).tag(config=True) |
|
176 | 204 | |
|
177 | 205 | prompts_class = Type(Prompts, help='Class used to generate Prompt token for prompt_toolkit').tag(config=True) |
|
178 | 206 | |
|
179 | 207 | prompts = Instance(Prompts) |
|
180 | 208 | |
|
181 | 209 | @default('prompts') |
|
182 | 210 | def _prompts_default(self): |
|
183 | 211 | return self.prompts_class(self) |
|
184 | 212 | |
|
185 | 213 | # @observe('prompts') |
|
186 | 214 | # def _(self, change): |
|
187 | 215 | # self._update_layout() |
|
188 | 216 | |
|
189 | 217 | @default('displayhook_class') |
|
190 | 218 | def _displayhook_class_default(self): |
|
191 | 219 | return RichPromptDisplayHook |
|
192 | 220 | |
|
193 | 221 | term_title = Bool(True, |
|
194 | 222 | help="Automatically set the terminal title" |
|
195 | 223 | ).tag(config=True) |
|
196 | 224 | |
|
197 | 225 | term_title_format = Unicode("IPython: {cwd}", |
|
198 | 226 | help="Customize the terminal title format. This is a python format string. " + |
|
199 | 227 | "Available substitutions are: {cwd}." |
|
200 | 228 | ).tag(config=True) |
|
201 | 229 | |
|
202 | 230 | display_completions = Enum(('column', 'multicolumn','readlinelike'), |
|
203 | 231 | help= ( "Options for displaying tab completions, 'column', 'multicolumn', and " |
|
204 | 232 | "'readlinelike'. These options are for `prompt_toolkit`, see " |
|
205 | 233 | "`prompt_toolkit` documentation for more information." |
|
206 | 234 | ), |
|
207 | 235 | default_value='multicolumn').tag(config=True) |
|
208 | 236 | |
|
209 | 237 | highlight_matching_brackets = Bool(True, |
|
210 | 238 | help="Highlight matching brackets.", |
|
211 | 239 | ).tag(config=True) |
|
212 | 240 | |
|
213 | 241 | extra_open_editor_shortcuts = Bool(False, |
|
214 | 242 | help="Enable vi (v) or Emacs (C-X C-E) shortcuts to open an external editor. " |
|
215 | 243 | "This is in addition to the F2 binding, which is always enabled." |
|
216 | 244 | ).tag(config=True) |
|
217 | 245 | |
|
218 | 246 | handle_return = Any(None, |
|
219 | 247 | help="Provide an alternative handler to be called when the user presses " |
|
220 | 248 | "Return. This is an advanced option intended for debugging, which " |
|
221 | 249 | "may be changed or removed in later releases." |
|
222 | 250 | ).tag(config=True) |
|
223 | 251 | |
|
224 | 252 | enable_history_search = Bool(True, |
|
225 | 253 | help="Allows to enable/disable the prompt toolkit history search" |
|
226 | 254 | ).tag(config=True) |
|
227 | 255 | |
|
228 | 256 | prompt_includes_vi_mode = Bool(True, |
|
229 | 257 | help="Display the current vi mode (when using vi editing mode)." |
|
230 | 258 | ).tag(config=True) |
|
231 | 259 | |
|
232 | 260 | @observe('term_title') |
|
233 | 261 | def init_term_title(self, change=None): |
|
234 | 262 | # Enable or disable the terminal title. |
|
235 | 263 | if self.term_title: |
|
236 | 264 | toggle_set_term_title(True) |
|
237 | 265 | set_term_title(self.term_title_format.format(cwd=abbrev_cwd())) |
|
238 | 266 | else: |
|
239 | 267 | toggle_set_term_title(False) |
|
240 | 268 | |
|
241 | 269 | def restore_term_title(self): |
|
242 | 270 | if self.term_title: |
|
243 | 271 | restore_term_title() |
|
244 | 272 | |
|
245 | 273 | def init_display_formatter(self): |
|
246 | 274 | super(TerminalInteractiveShell, self).init_display_formatter() |
|
247 | 275 | # terminal only supports plain text |
|
248 | 276 | self.display_formatter.active_types = ['text/plain'] |
|
249 | 277 | # disable `_ipython_display_` |
|
250 | 278 | self.display_formatter.ipython_display_formatter.enabled = False |
|
251 | 279 | |
|
252 | 280 | def init_prompt_toolkit_cli(self): |
|
253 | 281 | if self.simple_prompt: |
|
254 | 282 | # Fall back to plain non-interactive output for tests. |
|
255 | 283 | # This is very limited. |
|
256 | 284 | def prompt(): |
|
257 | 285 | prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens()) |
|
258 | 286 | lines = [input(prompt_text)] |
|
259 | 287 | prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens()) |
|
260 | 288 | while self.check_complete('\n'.join(lines))[0] == 'incomplete': |
|
261 | 289 | lines.append( input(prompt_continuation) ) |
|
262 | 290 | return '\n'.join(lines) |
|
263 | 291 | self.prompt_for_code = prompt |
|
264 | 292 | return |
|
265 | 293 | |
|
266 | 294 | # Set up keyboard shortcuts |
|
267 | 295 | key_bindings = create_ipython_shortcuts(self) |
|
268 | 296 | |
|
269 | 297 | # Pre-populate history from IPython's history database |
|
270 | 298 | history = InMemoryHistory() |
|
271 | 299 | last_cell = u"" |
|
272 | 300 | for __, ___, cell in self.history_manager.get_tail(self.history_load_length, |
|
273 | 301 | include_latest=True): |
|
274 | 302 | # Ignore blank lines and consecutive duplicates |
|
275 | 303 | cell = cell.rstrip() |
|
276 | 304 | if cell and (cell != last_cell): |
|
277 | 305 | history.append_string(cell) |
|
278 | 306 | last_cell = cell |
|
279 | 307 | |
|
280 | 308 | self._style = self._make_style_from_name_or_cls(self.highlighting_style) |
|
281 | 309 | self.style = DynamicStyle(lambda: self._style) |
|
282 | 310 | |
|
283 | 311 | editing_mode = getattr(EditingMode, self.editing_mode.upper()) |
|
284 | 312 | |
|
313 | self.pt_loop = asyncio.new_event_loop() | |
|
285 | 314 | self.pt_app = PromptSession( |
|
286 | 315 | editing_mode=editing_mode, |
|
287 | 316 | key_bindings=key_bindings, |
|
288 | 317 | history=history, |
|
289 | 318 | completer=IPythonPTCompleter(shell=self), |
|
290 | 319 | enable_history_search = self.enable_history_search, |
|
291 | 320 | style=self.style, |
|
292 | 321 | include_default_pygments_style=False, |
|
293 | 322 | mouse_support=self.mouse_support, |
|
294 | 323 | enable_open_in_editor=self.extra_open_editor_shortcuts, |
|
295 | 324 | color_depth=self.color_depth, |
|
296 | 325 | **self._extra_prompt_options()) |
|
297 | 326 | |
|
298 | 327 | def _make_style_from_name_or_cls(self, name_or_cls): |
|
299 | 328 | """ |
|
300 | 329 | Small wrapper that make an IPython compatible style from a style name |
|
301 | 330 | |
|
302 | 331 | We need that to add style for prompt ... etc. |
|
303 | 332 | """ |
|
304 | 333 | style_overrides = {} |
|
305 | 334 | if name_or_cls == 'legacy': |
|
306 | 335 | legacy = self.colors.lower() |
|
307 | 336 | if legacy == 'linux': |
|
308 | 337 | style_cls = get_style_by_name('monokai') |
|
309 | 338 | style_overrides = _style_overrides_linux |
|
310 | 339 | elif legacy == 'lightbg': |
|
311 | 340 | style_overrides = _style_overrides_light_bg |
|
312 | 341 | style_cls = get_style_by_name('pastie') |
|
313 | 342 | elif legacy == 'neutral': |
|
314 | 343 | # The default theme needs to be visible on both a dark background |
|
315 | 344 | # and a light background, because we can't tell what the terminal |
|
316 | 345 | # looks like. These tweaks to the default theme help with that. |
|
317 | 346 | style_cls = get_style_by_name('default') |
|
318 | 347 | style_overrides.update({ |
|
319 | 348 | Token.Number: '#007700', |
|
320 | 349 | Token.Operator: 'noinherit', |
|
321 | 350 | Token.String: '#BB6622', |
|
322 | 351 | Token.Name.Function: '#2080D0', |
|
323 | 352 | Token.Name.Class: 'bold #2080D0', |
|
324 | 353 | Token.Name.Namespace: 'bold #2080D0', |
|
325 | 354 | Token.Prompt: '#009900', |
|
326 | 355 | Token.PromptNum: '#ansibrightgreen bold', |
|
327 | 356 | Token.OutPrompt: '#990000', |
|
328 | 357 | Token.OutPromptNum: '#ansibrightred bold', |
|
329 | 358 | }) |
|
330 | 359 | |
|
331 | 360 | # Hack: Due to limited color support on the Windows console |
|
332 | 361 | # the prompt colors will be wrong without this |
|
333 | 362 | if os.name == 'nt': |
|
334 | 363 | style_overrides.update({ |
|
335 | 364 | Token.Prompt: '#ansidarkgreen', |
|
336 | 365 | Token.PromptNum: '#ansigreen bold', |
|
337 | 366 | Token.OutPrompt: '#ansidarkred', |
|
338 | 367 | Token.OutPromptNum: '#ansired bold', |
|
339 | 368 | }) |
|
340 | 369 | elif legacy =='nocolor': |
|
341 | 370 | style_cls=_NoStyle |
|
342 | 371 | style_overrides = {} |
|
343 | 372 | else : |
|
344 | 373 | raise ValueError('Got unknown colors: ', legacy) |
|
345 | 374 | else : |
|
346 | 375 | if isinstance(name_or_cls, str): |
|
347 | 376 | style_cls = get_style_by_name(name_or_cls) |
|
348 | 377 | else: |
|
349 | 378 | style_cls = name_or_cls |
|
350 | 379 | style_overrides = { |
|
351 | 380 | Token.Prompt: '#009900', |
|
352 | 381 | Token.PromptNum: '#ansibrightgreen bold', |
|
353 | 382 | Token.OutPrompt: '#990000', |
|
354 | 383 | Token.OutPromptNum: '#ansibrightred bold', |
|
355 | 384 | } |
|
356 | 385 | style_overrides.update(self.highlighting_style_overrides) |
|
357 | 386 | style = merge_styles([ |
|
358 | 387 | style_from_pygments_cls(style_cls), |
|
359 | 388 | style_from_pygments_dict(style_overrides), |
|
360 | 389 | ]) |
|
361 | 390 | |
|
362 | 391 | return style |
|
363 | 392 | |
|
364 | 393 | @property |
|
365 | 394 | def pt_complete_style(self): |
|
366 | 395 | return { |
|
367 | 396 | 'multicolumn': CompleteStyle.MULTI_COLUMN, |
|
368 | 397 | 'column': CompleteStyle.COLUMN, |
|
369 | 398 | 'readlinelike': CompleteStyle.READLINE_LIKE, |
|
370 | 399 | }[self.display_completions] |
|
371 | 400 | |
|
372 | 401 | @property |
|
373 | 402 | def color_depth(self): |
|
374 | 403 | return (ColorDepth.TRUE_COLOR if self.true_color else None) |
|
375 | 404 | |
|
376 | 405 | def _extra_prompt_options(self): |
|
377 | 406 | """ |
|
378 | 407 | Return the current layout option for the current Terminal InteractiveShell |
|
379 | 408 | """ |
|
380 | 409 | def get_message(): |
|
381 | 410 | return PygmentsTokens(self.prompts.in_prompt_tokens()) |
|
382 | 411 | |
|
383 | 412 | if self.editing_mode == 'emacs': |
|
384 | 413 | # with emacs mode the prompt is (usually) static, so we call only |
|
385 | 414 | # the function once. With VI mode it can toggle between [ins] and |
|
386 | 415 | # [nor] so we can't precompute. |
|
387 | 416 | # here I'm going to favor the default keybinding which almost |
|
388 | 417 | # everybody uses to decrease CPU usage. |
|
389 | 418 | # if we have issues with users with custom Prompts we can see how to |
|
390 | 419 | # work around this. |
|
391 | 420 | get_message = get_message() |
|
392 | 421 | |
|
393 |
|
|
|
422 | options = { | |
|
394 | 423 | 'complete_in_thread': False, |
|
395 | 424 | 'lexer':IPythonPTLexer(), |
|
396 | 425 | 'reserve_space_for_menu':self.space_for_menu, |
|
397 | 426 | 'message': get_message, |
|
398 | 427 | 'prompt_continuation': ( |
|
399 | 428 | lambda width, lineno, is_soft_wrap: |
|
400 | 429 | PygmentsTokens(self.prompts.continuation_prompt_tokens(width))), |
|
401 | 430 | 'multiline': True, |
|
402 | 431 | 'complete_style': self.pt_complete_style, |
|
403 | 432 | |
|
404 | 433 | # Highlight matching brackets, but only when this setting is |
|
405 | 434 | # enabled, and only when the DEFAULT_BUFFER has the focus. |
|
406 | 435 | 'input_processors': [ConditionalProcessor( |
|
407 | 436 | processor=HighlightMatchingBracketProcessor(chars='[](){}'), |
|
408 | 437 | filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() & |
|
409 | 438 | Condition(lambda: self.highlight_matching_brackets))], |
|
410 | 'inputhook': self.inputhook, | |
|
411 | 439 | } |
|
440 | if not PTK3: | |
|
441 | options['inputhook'] = self.inputhook | |
|
442 | ||
|
443 | return options | |
|
412 | 444 | |
|
413 | 445 | def prompt_for_code(self): |
|
414 | 446 | if self.rl_next_input: |
|
415 | 447 | default = self.rl_next_input |
|
416 | 448 | self.rl_next_input = None |
|
417 | 449 | else: |
|
418 | 450 | default = '' |
|
419 | 451 | |
|
420 | with patch_stdout(raw=True): | |
|
421 | text = self.pt_app.prompt( | |
|
422 | default=default, | |
|
423 | # pre_run=self.pre_prompt,# reset_current_buffer=True, | |
|
424 | **self._extra_prompt_options()) | |
|
452 | # In order to make sure that asyncio code written in the | |
|
453 | # interactive shell doesn't interfere with the prompt, we run the | |
|
454 | # prompt in a different event loop. | |
|
455 | # If we don't do this, people could spawn coroutine with a | |
|
456 | # while/true inside which will freeze the prompt. | |
|
457 | ||
|
458 | try: | |
|
459 | old_loop = asyncio.get_event_loop() | |
|
460 | except RuntimeError: | |
|
461 | # This happens when the user used `asyncio.run()`. | |
|
462 | old_loop = None | |
|
463 | ||
|
464 | asyncio.set_event_loop(self.pt_loop) | |
|
465 | try: | |
|
466 | with patch_stdout(raw=True): | |
|
467 | text = self.pt_app.prompt( | |
|
468 | default=default, | |
|
469 | **self._extra_prompt_options()) | |
|
470 | finally: | |
|
471 | # Restore the original event loop. | |
|
472 | asyncio.set_event_loop(old_loop) | |
|
473 | ||
|
425 | 474 | return text |
|
426 | 475 | |
|
427 | 476 | def enable_win_unicode_console(self): |
|
428 | 477 | # Since IPython 7.10 doesn't support python < 3.6 and PEP 528, Python uses the unicode APIs for the Windows |
|
429 | 478 | # console by default, so WUC shouldn't be needed. |
|
430 | 479 | from warnings import warn |
|
431 | 480 | warn("`enable_win_unicode_console` is deprecated since IPython 7.10, does not do anything and will be removed in the future", |
|
432 | 481 | DeprecationWarning, |
|
433 | 482 | stacklevel=2) |
|
434 | 483 | |
|
435 | 484 | def init_io(self): |
|
436 | 485 | if sys.platform not in {'win32', 'cli'}: |
|
437 | 486 | return |
|
438 | 487 | |
|
439 | 488 | import colorama |
|
440 | 489 | colorama.init() |
|
441 | 490 | |
|
442 | 491 | # For some reason we make these wrappers around stdout/stderr. |
|
443 | 492 | # For now, we need to reset them so all output gets coloured. |
|
444 | 493 | # https://github.com/ipython/ipython/issues/8669 |
|
445 | 494 | # io.std* are deprecated, but don't show our own deprecation warnings |
|
446 | 495 | # during initialization of the deprecated API. |
|
447 | 496 | with warnings.catch_warnings(): |
|
448 | 497 | warnings.simplefilter('ignore', DeprecationWarning) |
|
449 | 498 | io.stdout = io.IOStream(sys.stdout) |
|
450 | 499 | io.stderr = io.IOStream(sys.stderr) |
|
451 | 500 | |
|
452 | 501 | def init_magics(self): |
|
453 | 502 | super(TerminalInteractiveShell, self).init_magics() |
|
454 | 503 | self.register_magics(TerminalMagics) |
|
455 | 504 | |
|
456 | 505 | def init_alias(self): |
|
457 | 506 | # The parent class defines aliases that can be safely used with any |
|
458 | 507 | # frontend. |
|
459 | 508 | super(TerminalInteractiveShell, self).init_alias() |
|
460 | 509 | |
|
461 | 510 | # Now define aliases that only make sense on the terminal, because they |
|
462 | 511 | # need direct access to the console in a way that we can't emulate in |
|
463 | 512 | # GUI or web frontend |
|
464 | 513 | if os.name == 'posix': |
|
465 | 514 | for cmd in ('clear', 'more', 'less', 'man'): |
|
466 | 515 | self.alias_manager.soft_define_alias(cmd, cmd) |
|
467 | 516 | |
|
468 | 517 | |
|
469 | 518 | def __init__(self, *args, **kwargs): |
|
470 | 519 | super(TerminalInteractiveShell, self).__init__(*args, **kwargs) |
|
471 | 520 | self.init_prompt_toolkit_cli() |
|
472 | 521 | self.init_term_title() |
|
473 | 522 | self.keep_running = True |
|
474 | 523 | |
|
475 | 524 | self.debugger_history = InMemoryHistory() |
|
476 | 525 | |
|
477 | 526 | def ask_exit(self): |
|
478 | 527 | self.keep_running = False |
|
479 | 528 | |
|
480 | 529 | rl_next_input = None |
|
481 | 530 | |
|
482 | 531 | def interact(self, display_banner=DISPLAY_BANNER_DEPRECATED): |
|
483 | 532 | |
|
484 | 533 | if display_banner is not DISPLAY_BANNER_DEPRECATED: |
|
485 | 534 | warn('interact `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2) |
|
486 | 535 | |
|
487 | 536 | self.keep_running = True |
|
488 | 537 | while self.keep_running: |
|
489 | 538 | print(self.separate_in, end='') |
|
490 | 539 | |
|
491 | 540 | try: |
|
492 | 541 | code = self.prompt_for_code() |
|
493 | 542 | except EOFError: |
|
494 | 543 | if (not self.confirm_exit) \ |
|
495 | 544 | or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'): |
|
496 | 545 | self.ask_exit() |
|
497 | 546 | |
|
498 | 547 | else: |
|
499 | 548 | if code: |
|
500 | 549 | self.run_cell(code, store_history=True) |
|
501 | 550 | |
|
502 | 551 | def mainloop(self, display_banner=DISPLAY_BANNER_DEPRECATED): |
|
503 | 552 | # An extra layer of protection in case someone mashing Ctrl-C breaks |
|
504 | 553 | # out of our internal code. |
|
505 | 554 | if display_banner is not DISPLAY_BANNER_DEPRECATED: |
|
506 | 555 | warn('mainloop `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2) |
|
507 | 556 | while True: |
|
508 | 557 | try: |
|
509 | 558 | self.interact() |
|
510 | 559 | break |
|
511 | 560 | except KeyboardInterrupt as e: |
|
512 | 561 | print("\n%s escaped interact()\n" % type(e).__name__) |
|
513 | 562 | finally: |
|
514 | 563 | # An interrupt during the eventloop will mess up the |
|
515 | 564 | # internal state of the prompt_toolkit library. |
|
516 | 565 | # Stopping the eventloop fixes this, see |
|
517 | 566 | # https://github.com/ipython/ipython/pull/9867 |
|
518 | 567 | if hasattr(self, '_eventloop'): |
|
519 | 568 | self._eventloop.stop() |
|
520 | 569 | |
|
521 | 570 | self.restore_term_title() |
|
522 | 571 | |
|
523 | 572 | |
|
524 | 573 | _inputhook = None |
|
525 | 574 | def inputhook(self, context): |
|
526 | 575 | if self._inputhook is not None: |
|
527 | 576 | self._inputhook(context) |
|
528 | 577 | |
|
529 | 578 | active_eventloop = None |
|
530 | 579 | def enable_gui(self, gui=None): |
|
531 | if gui: | |
|
580 | if gui and (gui != 'inline') : | |
|
532 | 581 | self.active_eventloop, self._inputhook =\ |
|
533 | 582 | get_inputhook_name_and_func(gui) |
|
534 | 583 | else: |
|
535 | 584 | self.active_eventloop = self._inputhook = None |
|
536 | 585 | |
|
586 | # For prompt_toolkit 3.0. We have to create an asyncio event loop with | |
|
587 | # this inputhook. | |
|
588 | if PTK3: | |
|
589 | import asyncio | |
|
590 | from prompt_toolkit.eventloop import new_eventloop_with_inputhook | |
|
591 | ||
|
592 | if gui == 'asyncio': | |
|
593 | # When we integrate the asyncio event loop, run the UI in the | |
|
594 | # same event loop as the rest of the code. don't use an actual | |
|
595 | # input hook. (Asyncio is not made for nesting event loops.) | |
|
596 | self.pt_loop = asyncio.get_event_loop() | |
|
597 | ||
|
598 | elif self._inputhook: | |
|
599 | # If an inputhook was set, create a new asyncio event loop with | |
|
600 | # this inputhook for the prompt. | |
|
601 | self.pt_loop = new_eventloop_with_inputhook(self._inputhook) | |
|
602 | else: | |
|
603 | # When there's no inputhook, run the prompt in a separate | |
|
604 | # asyncio event loop. | |
|
605 | self.pt_loop = asyncio.new_event_loop() | |
|
606 | ||
|
537 | 607 | # Run !system commands directly, not through pipes, so terminal programs |
|
538 | 608 | # work correctly. |
|
539 | 609 | system = InteractiveShell.system_raw |
|
540 | 610 | |
|
541 | 611 | def auto_rewrite_input(self, cmd): |
|
542 | 612 | """Overridden from the parent class to use fancy rewriting prompt""" |
|
543 | 613 | if not self.show_rewritten_input: |
|
544 | 614 | return |
|
545 | 615 | |
|
546 | 616 | tokens = self.prompts.rewrite_prompt_tokens() |
|
547 | 617 | if self.pt_app: |
|
548 | 618 | print_formatted_text(PygmentsTokens(tokens), end='', |
|
549 | 619 | style=self.pt_app.app.style) |
|
550 | 620 | print(cmd) |
|
551 | 621 | else: |
|
552 | 622 | prompt = ''.join(s for t, s in tokens) |
|
553 | 623 | print(prompt, cmd, sep='') |
|
554 | 624 | |
|
555 | 625 | _prompts_before = None |
|
556 | 626 | def switch_doctest_mode(self, mode): |
|
557 | 627 | """Switch prompts to classic for %doctest_mode""" |
|
558 | 628 | if mode: |
|
559 | 629 | self._prompts_before = self.prompts |
|
560 | 630 | self.prompts = ClassicPrompts(self) |
|
561 | 631 | elif self._prompts_before: |
|
562 | 632 | self.prompts = self._prompts_before |
|
563 | 633 | self._prompts_before = None |
|
564 | 634 | # self._update_layout() |
|
565 | 635 | |
|
566 | 636 | |
|
567 | 637 | InteractiveShellABC.register(TerminalInteractiveShell) |
|
568 | 638 | |
|
569 | 639 | if __name__ == '__main__': |
|
570 | 640 | TerminalInteractiveShell.instance().interact() |
@@ -1,91 +1,102 b'' | |||
|
1 | 1 | """Terminal input and output prompts.""" |
|
2 | 2 | |
|
3 | 3 | from pygments.token import Token |
|
4 | 4 | import sys |
|
5 | 5 | |
|
6 | 6 | from IPython.core.displayhook import DisplayHook |
|
7 | 7 | |
|
8 | 8 | from prompt_toolkit.formatted_text import fragment_list_width, PygmentsTokens |
|
9 | 9 | from prompt_toolkit.shortcuts import print_formatted_text |
|
10 | 10 | |
|
11 | 11 | |
|
12 | 12 | class Prompts(object): |
|
13 | 13 | def __init__(self, shell): |
|
14 | 14 | self.shell = shell |
|
15 | 15 | |
|
16 | 16 | def vi_mode(self): |
|
17 | 17 | if (getattr(self.shell.pt_app, 'editing_mode', None) == 'VI' |
|
18 | 18 | and self.shell.prompt_includes_vi_mode): |
|
19 | 19 | return '['+str(self.shell.pt_app.app.vi_state.input_mode)[3:6]+'] ' |
|
20 | 20 | return '' |
|
21 | 21 | |
|
22 | 22 | |
|
23 | 23 | def in_prompt_tokens(self): |
|
24 | 24 | return [ |
|
25 | 25 | (Token.Prompt, self.vi_mode() ), |
|
26 | 26 | (Token.Prompt, 'In ['), |
|
27 | 27 | (Token.PromptNum, str(self.shell.execution_count)), |
|
28 | 28 | (Token.Prompt, ']: '), |
|
29 | 29 | ] |
|
30 | 30 | |
|
31 | 31 | def _width(self): |
|
32 | 32 | return fragment_list_width(self.in_prompt_tokens()) |
|
33 | 33 | |
|
34 | 34 | def continuation_prompt_tokens(self, width=None): |
|
35 | 35 | if width is None: |
|
36 | 36 | width = self._width() |
|
37 | 37 | return [ |
|
38 | 38 | (Token.Prompt, (' ' * (width - 5)) + '...: '), |
|
39 | 39 | ] |
|
40 | 40 | |
|
41 | 41 | def rewrite_prompt_tokens(self): |
|
42 | 42 | width = self._width() |
|
43 | 43 | return [ |
|
44 | 44 | (Token.Prompt, ('-' * (width - 2)) + '> '), |
|
45 | 45 | ] |
|
46 | 46 | |
|
47 | 47 | def out_prompt_tokens(self): |
|
48 | 48 | return [ |
|
49 | 49 | (Token.OutPrompt, 'Out['), |
|
50 | 50 | (Token.OutPromptNum, str(self.shell.execution_count)), |
|
51 | 51 | (Token.OutPrompt, ']: '), |
|
52 | 52 | ] |
|
53 | 53 | |
|
54 | 54 | class ClassicPrompts(Prompts): |
|
55 | 55 | def in_prompt_tokens(self): |
|
56 | 56 | return [ |
|
57 | 57 | (Token.Prompt, '>>> '), |
|
58 | 58 | ] |
|
59 | 59 | |
|
60 | 60 | def continuation_prompt_tokens(self, width=None): |
|
61 | 61 | return [ |
|
62 | 62 | (Token.Prompt, '... ') |
|
63 | 63 | ] |
|
64 | 64 | |
|
65 | 65 | def rewrite_prompt_tokens(self): |
|
66 | 66 | return [] |
|
67 | 67 | |
|
68 | 68 | def out_prompt_tokens(self): |
|
69 | 69 | return [] |
|
70 | 70 | |
|
71 | 71 | class RichPromptDisplayHook(DisplayHook): |
|
72 | 72 | """Subclass of base display hook using coloured prompt""" |
|
73 | 73 | def write_output_prompt(self): |
|
74 | 74 | sys.stdout.write(self.shell.separate_out) |
|
75 | 75 | # If we're not displaying a prompt, it effectively ends with a newline, |
|
76 | 76 | # because the output will be left-aligned. |
|
77 | 77 | self.prompt_end_newline = True |
|
78 | 78 | |
|
79 | 79 | if self.do_full_cache: |
|
80 | 80 | tokens = self.shell.prompts.out_prompt_tokens() |
|
81 | 81 | prompt_txt = ''.join(s for t, s in tokens) |
|
82 | 82 | if prompt_txt and not prompt_txt.endswith('\n'): |
|
83 | 83 | # Ask for a newline before multiline output |
|
84 | 84 | self.prompt_end_newline = False |
|
85 | 85 | |
|
86 | 86 | if self.shell.pt_app: |
|
87 | 87 | print_formatted_text(PygmentsTokens(tokens), |
|
88 | 88 | style=self.shell.pt_app.app.style, end='', |
|
89 | 89 | ) |
|
90 | 90 | else: |
|
91 | 91 | sys.stdout.write(prompt_txt) |
|
92 | ||
|
93 | def write_format_data(self, format_dict, md_dict=None) -> None: | |
|
94 | if self.shell.mime_renderers: | |
|
95 | ||
|
96 | for mime, handler in self.shell.mime_renderers.items(): | |
|
97 | if mime in format_dict: | |
|
98 | handler(format_dict[mime], None) | |
|
99 | return | |
|
100 | ||
|
101 | super().write_format_data(format_dict, md_dict) | |
|
102 |
@@ -1,49 +1,50 b'' | |||
|
1 | 1 | import importlib |
|
2 | 2 | import os |
|
3 | 3 | |
|
4 | 4 | aliases = { |
|
5 | 5 | 'qt4': 'qt', |
|
6 | 6 | 'gtk2': 'gtk', |
|
7 | 7 | } |
|
8 | 8 | |
|
9 | 9 | backends = [ |
|
10 | 10 | 'qt', 'qt4', 'qt5', |
|
11 | 11 | 'gtk', 'gtk2', 'gtk3', |
|
12 | 12 | 'tk', |
|
13 | 13 | 'wx', |
|
14 | 14 | 'pyglet', 'glut', |
|
15 | 15 | 'osx', |
|
16 | 'asyncio' | |
|
16 | 17 | ] |
|
17 | 18 | |
|
18 | 19 | registered = {} |
|
19 | 20 | |
|
20 | 21 | def register(name, inputhook): |
|
21 | 22 | """Register the function *inputhook* as an event loop integration.""" |
|
22 | 23 | registered[name] = inputhook |
|
23 | 24 | |
|
24 | 25 | class UnknownBackend(KeyError): |
|
25 | 26 | def __init__(self, name): |
|
26 | 27 | self.name = name |
|
27 | 28 | |
|
28 | 29 | def __str__(self): |
|
29 | 30 | return ("No event loop integration for {!r}. " |
|
30 | 31 | "Supported event loops are: {}").format(self.name, |
|
31 | 32 | ', '.join(backends + sorted(registered))) |
|
32 | 33 | |
|
33 | 34 | def get_inputhook_name_and_func(gui): |
|
34 | 35 | if gui in registered: |
|
35 | 36 | return gui, registered[gui] |
|
36 | 37 | |
|
37 | 38 | if gui not in backends: |
|
38 | 39 | raise UnknownBackend(gui) |
|
39 | 40 | |
|
40 | 41 | if gui in aliases: |
|
41 | 42 | return get_inputhook_name_and_func(aliases[gui]) |
|
42 | 43 | |
|
43 | 44 | gui_mod = gui |
|
44 | 45 | if gui == 'qt5': |
|
45 | 46 | os.environ['QT_API'] = 'pyqt5' |
|
46 | 47 | gui_mod = 'qt' |
|
47 | 48 | |
|
48 | 49 | mod = importlib.import_module('IPython.terminal.pt_inputhooks.'+gui_mod) |
|
49 | 50 | return gui, mod.inputhook |
@@ -1,249 +1,274 b'' | |||
|
1 | 1 | """ |
|
2 | 2 | Module to define and register Terminal IPython shortcuts with |
|
3 | 3 | :mod:`prompt_toolkit` |
|
4 | 4 | """ |
|
5 | 5 | |
|
6 | 6 | # Copyright (c) IPython Development Team. |
|
7 | 7 | # Distributed under the terms of the Modified BSD License. |
|
8 | 8 | |
|
9 | 9 | import warnings |
|
10 | 10 | import signal |
|
11 | 11 | import sys |
|
12 | 12 | from typing import Callable |
|
13 | 13 | |
|
14 | 14 | |
|
15 | 15 | from prompt_toolkit.application.current import get_app |
|
16 | 16 | from prompt_toolkit.enums import DEFAULT_BUFFER, SEARCH_BUFFER |
|
17 | 17 | from prompt_toolkit.filters import (has_focus, has_selection, Condition, |
|
18 | 18 | vi_insert_mode, emacs_insert_mode, has_completions, vi_mode) |
|
19 | 19 | from prompt_toolkit.key_binding.bindings.completion import display_completions_like_readline |
|
20 | 20 | from prompt_toolkit.key_binding import KeyBindings |
|
21 | 21 | |
|
22 | 22 | from IPython.utils.decorators import undoc |
|
23 | 23 | |
|
24 | 24 | @undoc |
|
25 | 25 | @Condition |
|
26 | 26 | def cursor_in_leading_ws(): |
|
27 | 27 | before = get_app().current_buffer.document.current_line_before_cursor |
|
28 | 28 | return (not before) or before.isspace() |
|
29 | 29 | |
|
30 | 30 | |
|
31 | 31 | def create_ipython_shortcuts(shell): |
|
32 | 32 | """Set up the prompt_toolkit keyboard shortcuts for IPython""" |
|
33 | 33 | |
|
34 | 34 | kb = KeyBindings() |
|
35 | 35 | insert_mode = vi_insert_mode | emacs_insert_mode |
|
36 | 36 | |
|
37 | 37 | if getattr(shell, 'handle_return', None): |
|
38 | 38 | return_handler = shell.handle_return(shell) |
|
39 | 39 | else: |
|
40 | 40 | return_handler = newline_or_execute_outer(shell) |
|
41 | 41 | |
|
42 | 42 | kb.add('enter', filter=(has_focus(DEFAULT_BUFFER) |
|
43 | 43 | & ~has_selection |
|
44 | 44 | & insert_mode |
|
45 | 45 | ))(return_handler) |
|
46 | 46 | |
|
47 | def reformat_and_execute(event): | |
|
48 | reformat_text_before_cursor(event.current_buffer, event.current_buffer.document, shell) | |
|
49 | event.current_buffer.validate_and_handle() | |
|
50 | ||
|
51 | kb.add('escape', 'enter', filter=(has_focus(DEFAULT_BUFFER) | |
|
52 | & ~has_selection | |
|
53 | & insert_mode | |
|
54 | ))(reformat_and_execute) | |
|
55 | ||
|
47 | 56 | kb.add('c-\\')(force_exit) |
|
48 | 57 | |
|
49 | 58 | kb.add('c-p', filter=(vi_insert_mode & has_focus(DEFAULT_BUFFER)) |
|
50 | 59 | )(previous_history_or_previous_completion) |
|
51 | 60 | |
|
52 | 61 | kb.add('c-n', filter=(vi_insert_mode & has_focus(DEFAULT_BUFFER)) |
|
53 | 62 | )(next_history_or_next_completion) |
|
54 | 63 | |
|
55 | 64 | kb.add('c-g', filter=(has_focus(DEFAULT_BUFFER) & has_completions) |
|
56 | 65 | )(dismiss_completion) |
|
57 | 66 | |
|
58 | 67 | kb.add('c-c', filter=has_focus(DEFAULT_BUFFER))(reset_buffer) |
|
59 | 68 | |
|
60 | 69 | kb.add('c-c', filter=has_focus(SEARCH_BUFFER))(reset_search_buffer) |
|
61 | 70 | |
|
62 | 71 | supports_suspend = Condition(lambda: hasattr(signal, 'SIGTSTP')) |
|
63 | 72 | kb.add('c-z', filter=supports_suspend)(suspend_to_bg) |
|
64 | 73 | |
|
65 | 74 | # Ctrl+I == Tab |
|
66 | 75 | kb.add('tab', filter=(has_focus(DEFAULT_BUFFER) |
|
67 | 76 | & ~has_selection |
|
68 | 77 | & insert_mode |
|
69 | 78 | & cursor_in_leading_ws |
|
70 | 79 | ))(indent_buffer) |
|
71 | 80 | kb.add('c-o', filter=(has_focus(DEFAULT_BUFFER) & emacs_insert_mode) |
|
72 | 81 | )(newline_autoindent_outer(shell.input_transformer_manager)) |
|
73 | 82 | |
|
74 | 83 | kb.add('f2', filter=has_focus(DEFAULT_BUFFER))(open_input_in_editor) |
|
75 | 84 | |
|
76 | 85 | if shell.display_completions == 'readlinelike': |
|
77 | 86 | kb.add('c-i', filter=(has_focus(DEFAULT_BUFFER) |
|
78 | 87 | & ~has_selection |
|
79 | 88 | & insert_mode |
|
80 | 89 | & ~cursor_in_leading_ws |
|
81 | 90 | ))(display_completions_like_readline) |
|
82 | 91 | |
|
83 | 92 | if sys.platform == 'win32': |
|
84 | 93 | kb.add('c-v', filter=(has_focus(DEFAULT_BUFFER) & ~vi_mode))(win_paste) |
|
85 | 94 | |
|
86 | 95 | return kb |
|
87 | 96 | |
|
88 | 97 | |
|
98 | def reformat_text_before_cursor(buffer, document, shell): | |
|
99 | text = buffer.delete_before_cursor(len(document.text[:document.cursor_position])) | |
|
100 | try: | |
|
101 | formatted_text = shell.reformat_handler(text) | |
|
102 | buffer.insert_text(formatted_text) | |
|
103 | except Exception as e: | |
|
104 | buffer.insert_text(text) | |
|
105 | ||
|
106 | ||
|
89 | 107 | def newline_or_execute_outer(shell): |
|
108 | ||
|
90 | 109 | def newline_or_execute(event): |
|
91 | 110 | """When the user presses return, insert a newline or execute the code.""" |
|
92 | 111 | b = event.current_buffer |
|
93 | 112 | d = b.document |
|
94 | 113 | |
|
95 | 114 | if b.complete_state: |
|
96 | 115 | cc = b.complete_state.current_completion |
|
97 | 116 | if cc: |
|
98 | 117 | b.apply_completion(cc) |
|
99 | 118 | else: |
|
100 | 119 | b.cancel_completion() |
|
101 | 120 | return |
|
102 | 121 | |
|
103 | 122 | # If there's only one line, treat it as if the cursor is at the end. |
|
104 | 123 | # See https://github.com/ipython/ipython/issues/10425 |
|
105 | 124 | if d.line_count == 1: |
|
106 | 125 | check_text = d.text |
|
107 | 126 | else: |
|
108 | 127 | check_text = d.text[:d.cursor_position] |
|
109 | 128 | status, indent = shell.check_complete(check_text) |
|
110 | ||
|
129 | ||
|
130 | # if all we have after the cursor is whitespace: reformat current text | |
|
131 | # before cursor | |
|
132 | after_cursor = d.text[d.cursor_position:] | |
|
133 | if not after_cursor.strip(): | |
|
134 | reformat_text_before_cursor(b, d, shell) | |
|
111 | 135 | if not (d.on_last_line or |
|
112 | 136 | d.cursor_position_row >= d.line_count - d.empty_line_count_at_the_end() |
|
113 | 137 | ): |
|
114 | 138 | if shell.autoindent: |
|
115 | 139 | b.insert_text('\n' + indent) |
|
116 | 140 | else: |
|
117 | 141 | b.insert_text('\n') |
|
118 | 142 | return |
|
119 | 143 | |
|
120 | 144 | if (status != 'incomplete') and b.accept_handler: |
|
145 | reformat_text_before_cursor(b, d, shell) | |
|
121 | 146 | b.validate_and_handle() |
|
122 | 147 | else: |
|
123 | 148 | if shell.autoindent: |
|
124 | 149 | b.insert_text('\n' + indent) |
|
125 | 150 | else: |
|
126 | 151 | b.insert_text('\n') |
|
127 | 152 | return newline_or_execute |
|
128 | 153 | |
|
129 | 154 | |
|
130 | 155 | def previous_history_or_previous_completion(event): |
|
131 | 156 | """ |
|
132 | 157 | Control-P in vi edit mode on readline is history next, unlike default prompt toolkit. |
|
133 | 158 | |
|
134 | 159 | If completer is open this still select previous completion. |
|
135 | 160 | """ |
|
136 | 161 | event.current_buffer.auto_up() |
|
137 | 162 | |
|
138 | 163 | |
|
139 | 164 | def next_history_or_next_completion(event): |
|
140 | 165 | """ |
|
141 | 166 | Control-N in vi edit mode on readline is history previous, unlike default prompt toolkit. |
|
142 | 167 | |
|
143 | 168 | If completer is open this still select next completion. |
|
144 | 169 | """ |
|
145 | 170 | event.current_buffer.auto_down() |
|
146 | 171 | |
|
147 | 172 | |
|
148 | 173 | def dismiss_completion(event): |
|
149 | 174 | b = event.current_buffer |
|
150 | 175 | if b.complete_state: |
|
151 | 176 | b.cancel_completion() |
|
152 | 177 | |
|
153 | 178 | |
|
154 | 179 | def reset_buffer(event): |
|
155 | 180 | b = event.current_buffer |
|
156 | 181 | if b.complete_state: |
|
157 | 182 | b.cancel_completion() |
|
158 | 183 | else: |
|
159 | 184 | b.reset() |
|
160 | 185 | |
|
161 | 186 | |
|
162 | 187 | def reset_search_buffer(event): |
|
163 | 188 | if event.current_buffer.document.text: |
|
164 | 189 | event.current_buffer.reset() |
|
165 | 190 | else: |
|
166 | 191 | event.app.layout.focus(DEFAULT_BUFFER) |
|
167 | 192 | |
|
168 | 193 | def suspend_to_bg(event): |
|
169 | 194 | event.app.suspend_to_background() |
|
170 | 195 | |
|
171 | 196 | def force_exit(event): |
|
172 | 197 | """ |
|
173 | 198 | Force exit (with a non-zero return value) |
|
174 | 199 | """ |
|
175 | 200 | sys.exit("Quit") |
|
176 | 201 | |
|
177 | 202 | def indent_buffer(event): |
|
178 | 203 | event.current_buffer.insert_text(' ' * 4) |
|
179 | 204 | |
|
180 | 205 | @undoc |
|
181 | 206 | def newline_with_copy_margin(event): |
|
182 | 207 | """ |
|
183 | 208 | DEPRECATED since IPython 6.0 |
|
184 | 209 | |
|
185 | 210 | See :any:`newline_autoindent_outer` for a replacement. |
|
186 | 211 | |
|
187 | 212 | Preserve margin and cursor position when using |
|
188 | 213 | Control-O to insert a newline in EMACS mode |
|
189 | 214 | """ |
|
190 | 215 | warnings.warn("`newline_with_copy_margin(event)` is deprecated since IPython 6.0. " |
|
191 | 216 | "see `newline_autoindent_outer(shell)(event)` for a replacement.", |
|
192 | 217 | DeprecationWarning, stacklevel=2) |
|
193 | 218 | |
|
194 | 219 | b = event.current_buffer |
|
195 | 220 | cursor_start_pos = b.document.cursor_position_col |
|
196 | 221 | b.newline(copy_margin=True) |
|
197 | 222 | b.cursor_up(count=1) |
|
198 | 223 | cursor_end_pos = b.document.cursor_position_col |
|
199 | 224 | if cursor_start_pos != cursor_end_pos: |
|
200 | 225 | pos_diff = cursor_start_pos - cursor_end_pos |
|
201 | 226 | b.cursor_right(count=pos_diff) |
|
202 | 227 | |
|
203 | 228 | def newline_autoindent_outer(inputsplitter) -> Callable[..., None]: |
|
204 | 229 | """ |
|
205 | 230 | Return a function suitable for inserting a indented newline after the cursor. |
|
206 | 231 | |
|
207 | 232 | Fancier version of deprecated ``newline_with_copy_margin`` which should |
|
208 | 233 | compute the correct indentation of the inserted line. That is to say, indent |
|
209 | 234 | by 4 extra space after a function definition, class definition, context |
|
210 | 235 | manager... And dedent by 4 space after ``pass``, ``return``, ``raise ...``. |
|
211 | 236 | """ |
|
212 | 237 | |
|
213 | 238 | def newline_autoindent(event): |
|
214 | 239 | """insert a newline after the cursor indented appropriately.""" |
|
215 | 240 | b = event.current_buffer |
|
216 | 241 | d = b.document |
|
217 | 242 | |
|
218 | 243 | if b.complete_state: |
|
219 | 244 | b.cancel_completion() |
|
220 | 245 | text = d.text[:d.cursor_position] + '\n' |
|
221 | 246 | _, indent = inputsplitter.check_complete(text) |
|
222 | 247 | b.insert_text('\n' + (' ' * (indent or 0)), move_cursor=False) |
|
223 | 248 | |
|
224 | 249 | return newline_autoindent |
|
225 | 250 | |
|
226 | 251 | |
|
227 | 252 | def open_input_in_editor(event): |
|
228 | 253 | event.app.current_buffer.tempfile_suffix = ".py" |
|
229 | 254 | event.app.current_buffer.open_in_editor() |
|
230 | 255 | |
|
231 | 256 | |
|
232 | 257 | if sys.platform == 'win32': |
|
233 | 258 | from IPython.core.error import TryNext |
|
234 | 259 | from IPython.lib.clipboard import (ClipboardEmpty, |
|
235 | 260 | win32_clipboard_get, |
|
236 | 261 | tkinter_clipboard_get) |
|
237 | 262 | |
|
238 | 263 | @undoc |
|
239 | 264 | def win_paste(event): |
|
240 | 265 | try: |
|
241 | 266 | text = win32_clipboard_get() |
|
242 | 267 | except TryNext: |
|
243 | 268 | try: |
|
244 | 269 | text = tkinter_clipboard_get() |
|
245 | 270 | except (TryNext, ClipboardEmpty): |
|
246 | 271 | return |
|
247 | 272 | except ClipboardEmpty: |
|
248 | 273 | return |
|
249 | 274 | event.current_buffer.insert_text(text.replace('\t', ' ' * 4)) |
@@ -1,439 +1,436 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """ |
|
3 | 3 | Utilities for path handling. |
|
4 | 4 | """ |
|
5 | 5 | |
|
6 | 6 | # Copyright (c) IPython Development Team. |
|
7 | 7 | # Distributed under the terms of the Modified BSD License. |
|
8 | 8 | |
|
9 | 9 | import os |
|
10 | 10 | import sys |
|
11 | 11 | import errno |
|
12 | 12 | import shutil |
|
13 | 13 | import random |
|
14 | 14 | import glob |
|
15 | 15 | from warnings import warn |
|
16 | 16 | |
|
17 | 17 | from IPython.utils.process import system |
|
18 | 18 | from IPython.utils import py3compat |
|
19 | 19 | from IPython.utils.decorators import undoc |
|
20 | 20 | |
|
21 | 21 | #----------------------------------------------------------------------------- |
|
22 | 22 | # Code |
|
23 | 23 | #----------------------------------------------------------------------------- |
|
24 | 24 | |
|
25 | 25 | fs_encoding = sys.getfilesystemencoding() |
|
26 | 26 | |
|
27 | 27 | def _writable_dir(path): |
|
28 | 28 | """Whether `path` is a directory, to which the user has write access.""" |
|
29 | 29 | return os.path.isdir(path) and os.access(path, os.W_OK) |
|
30 | 30 | |
|
31 | 31 | if sys.platform == 'win32': |
|
32 | 32 | def _get_long_path_name(path): |
|
33 | 33 | """Get a long path name (expand ~) on Windows using ctypes. |
|
34 | 34 | |
|
35 | 35 | Examples |
|
36 | 36 | -------- |
|
37 | 37 | |
|
38 | 38 | >>> get_long_path_name('c:\\docume~1') |
|
39 | 39 | 'c:\\\\Documents and Settings' |
|
40 | 40 | |
|
41 | 41 | """ |
|
42 | 42 | try: |
|
43 | 43 | import ctypes |
|
44 | 44 | except ImportError: |
|
45 | 45 | raise ImportError('you need to have ctypes installed for this to work') |
|
46 | 46 | _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW |
|
47 | 47 | _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p, |
|
48 | 48 | ctypes.c_uint ] |
|
49 | 49 | |
|
50 | 50 | buf = ctypes.create_unicode_buffer(260) |
|
51 | 51 | rv = _GetLongPathName(path, buf, 260) |
|
52 | 52 | if rv == 0 or rv > 260: |
|
53 | 53 | return path |
|
54 | 54 | else: |
|
55 | 55 | return buf.value |
|
56 | 56 | else: |
|
57 | 57 | def _get_long_path_name(path): |
|
58 | 58 | """Dummy no-op.""" |
|
59 | 59 | return path |
|
60 | 60 | |
|
61 | 61 | |
|
62 | 62 | |
|
63 | 63 | def get_long_path_name(path): |
|
64 | 64 | """Expand a path into its long form. |
|
65 | 65 | |
|
66 | 66 | On Windows this expands any ~ in the paths. On other platforms, it is |
|
67 | 67 | a null operation. |
|
68 | 68 | """ |
|
69 | 69 | return _get_long_path_name(path) |
|
70 | 70 | |
|
71 | 71 | |
|
72 | 72 | def unquote_filename(name, win32=(sys.platform=='win32')): |
|
73 | 73 | """ On Windows, remove leading and trailing quotes from filenames. |
|
74 | 74 | |
|
75 | 75 | This function has been deprecated and should not be used any more: |
|
76 | 76 | unquoting is now taken care of by :func:`IPython.utils.process.arg_split`. |
|
77 | 77 | """ |
|
78 | 78 | warn("'unquote_filename' is deprecated since IPython 5.0 and should not " |
|
79 | 79 | "be used anymore", DeprecationWarning, stacklevel=2) |
|
80 | 80 | if win32: |
|
81 | 81 | if name.startswith(("'", '"')) and name.endswith(("'", '"')): |
|
82 | 82 | name = name[1:-1] |
|
83 | 83 | return name |
|
84 | 84 | |
|
85 | 85 | |
|
86 | 86 | def compress_user(path): |
|
87 | 87 | """Reverse of :func:`os.path.expanduser` |
|
88 | 88 | """ |
|
89 | 89 | home = os.path.expanduser('~') |
|
90 | 90 | if path.startswith(home): |
|
91 | 91 | path = "~" + path[len(home):] |
|
92 | 92 | return path |
|
93 | 93 | |
|
94 | 94 | def get_py_filename(name, force_win32=None): |
|
95 | 95 | """Return a valid python filename in the current directory. |
|
96 | 96 | |
|
97 | 97 | If the given name is not a file, it adds '.py' and searches again. |
|
98 | 98 | Raises IOError with an informative message if the file isn't found. |
|
99 | 99 | """ |
|
100 | 100 | |
|
101 | 101 | name = os.path.expanduser(name) |
|
102 | 102 | if force_win32 is not None: |
|
103 | 103 | warn("The 'force_win32' argument to 'get_py_filename' is deprecated " |
|
104 | 104 | "since IPython 5.0 and should not be used anymore", |
|
105 | 105 | DeprecationWarning, stacklevel=2) |
|
106 | 106 | if not os.path.isfile(name) and not name.endswith('.py'): |
|
107 | 107 | name += '.py' |
|
108 | 108 | if os.path.isfile(name): |
|
109 | 109 | return name |
|
110 | 110 | else: |
|
111 | 111 | raise IOError('File `%r` not found.' % name) |
|
112 | 112 | |
|
113 | 113 | |
|
114 | 114 | def filefind(filename, path_dirs=None): |
|
115 | 115 | """Find a file by looking through a sequence of paths. |
|
116 | 116 | |
|
117 | 117 | This iterates through a sequence of paths looking for a file and returns |
|
118 | 118 | the full, absolute path of the first occurrence of the file. If no set of |
|
119 | 119 | path dirs is given, the filename is tested as is, after running through |
|
120 | 120 | :func:`expandvars` and :func:`expanduser`. Thus a simple call:: |
|
121 | 121 | |
|
122 | 122 | filefind('myfile.txt') |
|
123 | 123 | |
|
124 | 124 | will find the file in the current working dir, but:: |
|
125 | 125 | |
|
126 | 126 | filefind('~/myfile.txt') |
|
127 | 127 | |
|
128 | 128 | Will find the file in the users home directory. This function does not |
|
129 | 129 | automatically try any paths, such as the cwd or the user's home directory. |
|
130 | 130 | |
|
131 | 131 | Parameters |
|
132 | 132 | ---------- |
|
133 | 133 | filename : str |
|
134 | 134 | The filename to look for. |
|
135 | 135 | path_dirs : str, None or sequence of str |
|
136 | 136 | The sequence of paths to look for the file in. If None, the filename |
|
137 | 137 | need to be absolute or be in the cwd. If a string, the string is |
|
138 | 138 | put into a sequence and the searched. If a sequence, walk through |
|
139 | 139 | each element and join with ``filename``, calling :func:`expandvars` |
|
140 | 140 | and :func:`expanduser` before testing for existence. |
|
141 | 141 | |
|
142 | 142 | Returns |
|
143 | 143 | ------- |
|
144 | 144 | Raises :exc:`IOError` or returns absolute path to file. |
|
145 | 145 | """ |
|
146 | 146 | |
|
147 | 147 | # If paths are quoted, abspath gets confused, strip them... |
|
148 | 148 | filename = filename.strip('"').strip("'") |
|
149 | 149 | # If the input is an absolute path, just check it exists |
|
150 | 150 | if os.path.isabs(filename) and os.path.isfile(filename): |
|
151 | 151 | return filename |
|
152 | 152 | |
|
153 | 153 | if path_dirs is None: |
|
154 | 154 | path_dirs = ("",) |
|
155 | 155 | elif isinstance(path_dirs, str): |
|
156 | 156 | path_dirs = (path_dirs,) |
|
157 | 157 | |
|
158 | 158 | for path in path_dirs: |
|
159 | 159 | if path == '.': path = os.getcwd() |
|
160 | 160 | testname = expand_path(os.path.join(path, filename)) |
|
161 | 161 | if os.path.isfile(testname): |
|
162 | 162 | return os.path.abspath(testname) |
|
163 | 163 | |
|
164 | 164 | raise IOError("File %r does not exist in any of the search paths: %r" % |
|
165 | 165 | (filename, path_dirs) ) |
|
166 | 166 | |
|
167 | 167 | |
|
168 | 168 | class HomeDirError(Exception): |
|
169 | 169 | pass |
|
170 | 170 | |
|
171 | 171 | |
|
172 | def get_home_dir(require_writable=False): | |
|
172 | def get_home_dir(require_writable=False) -> str: | |
|
173 | 173 | """Return the 'home' directory, as a unicode string. |
|
174 | 174 | |
|
175 | 175 | Uses os.path.expanduser('~'), and checks for writability. |
|
176 | 176 | |
|
177 | 177 | See stdlib docs for how this is determined. |
|
178 | 178 | For Python <3.8, $HOME is first priority on *ALL* platforms. |
|
179 | 179 | For Python >=3.8 on Windows, %HOME% is no longer considered. |
|
180 | 180 | |
|
181 | 181 | Parameters |
|
182 | 182 | ---------- |
|
183 | 183 | |
|
184 | 184 | require_writable : bool [default: False] |
|
185 | 185 | if True: |
|
186 | 186 | guarantees the return value is a writable directory, otherwise |
|
187 | 187 | raises HomeDirError |
|
188 | 188 | if False: |
|
189 | 189 | The path is resolved, but it is not guaranteed to exist or be writable. |
|
190 | 190 | """ |
|
191 | 191 | |
|
192 | 192 | homedir = os.path.expanduser('~') |
|
193 | 193 | # Next line will make things work even when /home/ is a symlink to |
|
194 | 194 | # /usr/home as it is on FreeBSD, for example |
|
195 | 195 | homedir = os.path.realpath(homedir) |
|
196 | 196 | |
|
197 | 197 | if not _writable_dir(homedir) and os.name == 'nt': |
|
198 | 198 | # expanduser failed, use the registry to get the 'My Documents' folder. |
|
199 | 199 | try: |
|
200 | try: | |
|
201 | import winreg as wreg # Py 3 | |
|
202 | except ImportError: | |
|
203 | import _winreg as wreg # Py 2 | |
|
204 | key = wreg.OpenKey( | |
|
200 | import winreg as wreg | |
|
201 | with wreg.OpenKey( | |
|
205 | 202 | wreg.HKEY_CURRENT_USER, |
|
206 | 203 | r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" |
|
207 | ) | |
|
208 | homedir = wreg.QueryValueEx(key,'Personal')[0] | |
|
209 | key.Close() | |
|
204 | ) as key: | |
|
205 | homedir = wreg.QueryValueEx(key,'Personal')[0] | |
|
210 | 206 | except: |
|
211 | 207 | pass |
|
212 | 208 | |
|
213 | 209 | if (not require_writable) or _writable_dir(homedir): |
|
214 | return py3compat.cast_unicode(homedir, fs_encoding) | |
|
210 | assert isinstance(homedir, str), "Homedir shoudl be unicode not bytes" | |
|
211 | return homedir | |
|
215 | 212 | else: |
|
216 | 213 | raise HomeDirError('%s is not a writable dir, ' |
|
217 | 214 | 'set $HOME environment variable to override' % homedir) |
|
218 | 215 | |
|
219 | 216 | def get_xdg_dir(): |
|
220 | 217 | """Return the XDG_CONFIG_HOME, if it is defined and exists, else None. |
|
221 | 218 | |
|
222 | 219 | This is only for non-OS X posix (Linux,Unix,etc.) systems. |
|
223 | 220 | """ |
|
224 | 221 | |
|
225 | 222 | env = os.environ |
|
226 | 223 | |
|
227 | 224 | if os.name == 'posix' and sys.platform != 'darwin': |
|
228 | 225 | # Linux, Unix, AIX, etc. |
|
229 | 226 | # use ~/.config if empty OR not set |
|
230 | 227 | xdg = env.get("XDG_CONFIG_HOME", None) or os.path.join(get_home_dir(), '.config') |
|
231 | 228 | if xdg and _writable_dir(xdg): |
|
232 | 229 | return py3compat.cast_unicode(xdg, fs_encoding) |
|
233 | 230 | |
|
234 | 231 | return None |
|
235 | 232 | |
|
236 | 233 | |
|
237 | 234 | def get_xdg_cache_dir(): |
|
238 | 235 | """Return the XDG_CACHE_HOME, if it is defined and exists, else None. |
|
239 | 236 | |
|
240 | 237 | This is only for non-OS X posix (Linux,Unix,etc.) systems. |
|
241 | 238 | """ |
|
242 | 239 | |
|
243 | 240 | env = os.environ |
|
244 | 241 | |
|
245 | 242 | if os.name == 'posix' and sys.platform != 'darwin': |
|
246 | 243 | # Linux, Unix, AIX, etc. |
|
247 | 244 | # use ~/.cache if empty OR not set |
|
248 | 245 | xdg = env.get("XDG_CACHE_HOME", None) or os.path.join(get_home_dir(), '.cache') |
|
249 | 246 | if xdg and _writable_dir(xdg): |
|
250 | 247 | return py3compat.cast_unicode(xdg, fs_encoding) |
|
251 | 248 | |
|
252 | 249 | return None |
|
253 | 250 | |
|
254 | 251 | |
|
255 | 252 | @undoc |
|
256 | 253 | def get_ipython_dir(): |
|
257 | warn("get_ipython_dir has moved to the IPython.paths module since IPython 4.0.", stacklevel=2) | |
|
254 | warn("get_ipython_dir has moved to the IPython.paths module since IPython 4.0.", DeprecationWarning, stacklevel=2) | |
|
258 | 255 | from IPython.paths import get_ipython_dir |
|
259 | 256 | return get_ipython_dir() |
|
260 | 257 | |
|
261 | 258 | @undoc |
|
262 | 259 | def get_ipython_cache_dir(): |
|
263 | warn("get_ipython_cache_dir has moved to the IPython.paths module since IPython 4.0.", stacklevel=2) | |
|
260 | warn("get_ipython_cache_dir has moved to the IPython.paths module since IPython 4.0.", DeprecationWarning, stacklevel=2) | |
|
264 | 261 | from IPython.paths import get_ipython_cache_dir |
|
265 | 262 | return get_ipython_cache_dir() |
|
266 | 263 | |
|
267 | 264 | @undoc |
|
268 | 265 | def get_ipython_package_dir(): |
|
269 | warn("get_ipython_package_dir has moved to the IPython.paths module since IPython 4.0.", stacklevel=2) | |
|
266 | warn("get_ipython_package_dir has moved to the IPython.paths module since IPython 4.0.", DeprecationWarning, stacklevel=2) | |
|
270 | 267 | from IPython.paths import get_ipython_package_dir |
|
271 | 268 | return get_ipython_package_dir() |
|
272 | 269 | |
|
273 | 270 | @undoc |
|
274 | 271 | def get_ipython_module_path(module_str): |
|
275 | warn("get_ipython_module_path has moved to the IPython.paths module since IPython 4.0.", stacklevel=2) | |
|
272 | warn("get_ipython_module_path has moved to the IPython.paths module since IPython 4.0.", DeprecationWarning, stacklevel=2) | |
|
276 | 273 | from IPython.paths import get_ipython_module_path |
|
277 | 274 | return get_ipython_module_path(module_str) |
|
278 | 275 | |
|
279 | 276 | @undoc |
|
280 | 277 | def locate_profile(profile='default'): |
|
281 | warn("locate_profile has moved to the IPython.paths module since IPython 4.0.", stacklevel=2) | |
|
278 | warn("locate_profile has moved to the IPython.paths module since IPython 4.0.", DeprecationWarning, stacklevel=2) | |
|
282 | 279 | from IPython.paths import locate_profile |
|
283 | 280 | return locate_profile(profile=profile) |
|
284 | 281 | |
|
285 | 282 | def expand_path(s): |
|
286 | 283 | """Expand $VARS and ~names in a string, like a shell |
|
287 | 284 | |
|
288 | 285 | :Examples: |
|
289 | 286 | |
|
290 | 287 | In [2]: os.environ['FOO']='test' |
|
291 | 288 | |
|
292 | 289 | In [3]: expand_path('variable FOO is $FOO') |
|
293 | 290 | Out[3]: 'variable FOO is test' |
|
294 | 291 | """ |
|
295 | 292 | # This is a pretty subtle hack. When expand user is given a UNC path |
|
296 | 293 | # on Windows (\\server\share$\%username%), os.path.expandvars, removes |
|
297 | 294 | # the $ to get (\\server\share\%username%). I think it considered $ |
|
298 | 295 | # alone an empty var. But, we need the $ to remains there (it indicates |
|
299 | 296 | # a hidden share). |
|
300 | 297 | if os.name=='nt': |
|
301 | 298 | s = s.replace('$\\', 'IPYTHON_TEMP') |
|
302 | 299 | s = os.path.expandvars(os.path.expanduser(s)) |
|
303 | 300 | if os.name=='nt': |
|
304 | 301 | s = s.replace('IPYTHON_TEMP', '$\\') |
|
305 | 302 | return s |
|
306 | 303 | |
|
307 | 304 | |
|
308 | 305 | def unescape_glob(string): |
|
309 | 306 | """Unescape glob pattern in `string`.""" |
|
310 | 307 | def unescape(s): |
|
311 | 308 | for pattern in '*[]!?': |
|
312 | 309 | s = s.replace(r'\{0}'.format(pattern), pattern) |
|
313 | 310 | return s |
|
314 | 311 | return '\\'.join(map(unescape, string.split('\\\\'))) |
|
315 | 312 | |
|
316 | 313 | |
|
317 | 314 | def shellglob(args): |
|
318 | 315 | """ |
|
319 | 316 | Do glob expansion for each element in `args` and return a flattened list. |
|
320 | 317 | |
|
321 | 318 | Unmatched glob pattern will remain as-is in the returned list. |
|
322 | 319 | |
|
323 | 320 | """ |
|
324 | 321 | expanded = [] |
|
325 | 322 | # Do not unescape backslash in Windows as it is interpreted as |
|
326 | 323 | # path separator: |
|
327 | 324 | unescape = unescape_glob if sys.platform != 'win32' else lambda x: x |
|
328 | 325 | for a in args: |
|
329 | 326 | expanded.extend(glob.glob(a) or [unescape(a)]) |
|
330 | 327 | return expanded |
|
331 | 328 | |
|
332 | 329 | |
|
333 | 330 | def target_outdated(target,deps): |
|
334 | 331 | """Determine whether a target is out of date. |
|
335 | 332 | |
|
336 | 333 | target_outdated(target,deps) -> 1/0 |
|
337 | 334 | |
|
338 | 335 | deps: list of filenames which MUST exist. |
|
339 | 336 | target: single filename which may or may not exist. |
|
340 | 337 | |
|
341 | 338 | If target doesn't exist or is older than any file listed in deps, return |
|
342 | 339 | true, otherwise return false. |
|
343 | 340 | """ |
|
344 | 341 | try: |
|
345 | 342 | target_time = os.path.getmtime(target) |
|
346 | 343 | except os.error: |
|
347 | 344 | return 1 |
|
348 | 345 | for dep in deps: |
|
349 | 346 | dep_time = os.path.getmtime(dep) |
|
350 | 347 | if dep_time > target_time: |
|
351 | 348 | #print "For target",target,"Dep failed:",dep # dbg |
|
352 | 349 | #print "times (dep,tar):",dep_time,target_time # dbg |
|
353 | 350 | return 1 |
|
354 | 351 | return 0 |
|
355 | 352 | |
|
356 | 353 | |
|
357 | 354 | def target_update(target,deps,cmd): |
|
358 | 355 | """Update a target with a given command given a list of dependencies. |
|
359 | 356 | |
|
360 | 357 | target_update(target,deps,cmd) -> runs cmd if target is outdated. |
|
361 | 358 | |
|
362 | 359 | This is just a wrapper around target_outdated() which calls the given |
|
363 | 360 | command if target is outdated.""" |
|
364 | 361 | |
|
365 | 362 | if target_outdated(target,deps): |
|
366 | 363 | system(cmd) |
|
367 | 364 | |
|
368 | 365 | |
|
369 | 366 | ENOLINK = 1998 |
|
370 | 367 | |
|
371 | 368 | def link(src, dst): |
|
372 | 369 | """Hard links ``src`` to ``dst``, returning 0 or errno. |
|
373 | 370 | |
|
374 | 371 | Note that the special errno ``ENOLINK`` will be returned if ``os.link`` isn't |
|
375 | 372 | supported by the operating system. |
|
376 | 373 | """ |
|
377 | 374 | |
|
378 | 375 | if not hasattr(os, "link"): |
|
379 | 376 | return ENOLINK |
|
380 | 377 | link_errno = 0 |
|
381 | 378 | try: |
|
382 | 379 | os.link(src, dst) |
|
383 | 380 | except OSError as e: |
|
384 | 381 | link_errno = e.errno |
|
385 | 382 | return link_errno |
|
386 | 383 | |
|
387 | 384 | |
|
388 | 385 | def link_or_copy(src, dst): |
|
389 | 386 | """Attempts to hardlink ``src`` to ``dst``, copying if the link fails. |
|
390 | 387 | |
|
391 | 388 | Attempts to maintain the semantics of ``shutil.copy``. |
|
392 | 389 | |
|
393 | 390 | Because ``os.link`` does not overwrite files, a unique temporary file |
|
394 | 391 | will be used if the target already exists, then that file will be moved |
|
395 | 392 | into place. |
|
396 | 393 | """ |
|
397 | 394 | |
|
398 | 395 | if os.path.isdir(dst): |
|
399 | 396 | dst = os.path.join(dst, os.path.basename(src)) |
|
400 | 397 | |
|
401 | 398 | link_errno = link(src, dst) |
|
402 | 399 | if link_errno == errno.EEXIST: |
|
403 | 400 | if os.stat(src).st_ino == os.stat(dst).st_ino: |
|
404 | 401 | # dst is already a hard link to the correct file, so we don't need |
|
405 | 402 | # to do anything else. If we try to link and rename the file |
|
406 | 403 | # anyway, we get duplicate files - see http://bugs.python.org/issue21876 |
|
407 | 404 | return |
|
408 | 405 | |
|
409 | 406 | new_dst = dst + "-temp-%04X" %(random.randint(1, 16**4), ) |
|
410 | 407 | try: |
|
411 | 408 | link_or_copy(src, new_dst) |
|
412 | 409 | except: |
|
413 | 410 | try: |
|
414 | 411 | os.remove(new_dst) |
|
415 | 412 | except OSError: |
|
416 | 413 | pass |
|
417 | 414 | raise |
|
418 | 415 | os.rename(new_dst, dst) |
|
419 | 416 | elif link_errno != 0: |
|
420 | 417 | # Either link isn't supported, or the filesystem doesn't support |
|
421 | 418 | # linking, or 'src' and 'dst' are on different filesystems. |
|
422 | 419 | shutil.copy(src, dst) |
|
423 | 420 | |
|
424 | 421 | def ensure_dir_exists(path, mode=0o755): |
|
425 | 422 | """ensure that a directory exists |
|
426 | 423 | |
|
427 | 424 | If it doesn't exist, try to create it and protect against a race condition |
|
428 | 425 | if another process is doing the same. |
|
429 | 426 | |
|
430 | 427 | The default permissions are 755, which differ from os.makedirs default of 777. |
|
431 | 428 | """ |
|
432 | 429 | if not os.path.exists(path): |
|
433 | 430 | try: |
|
434 | 431 | os.makedirs(path, mode=mode) |
|
435 | 432 | except OSError as e: |
|
436 | 433 | if e.errno != errno.EEXIST: |
|
437 | 434 | raise |
|
438 | 435 | elif not os.path.isdir(path): |
|
439 | 436 | raise IOError("%r exists but is not a directory" % path) |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: file was removed | |
The requested commit or file is too big and content was truncated. Show full diff |
General Comments 0
You need to be logged in to leave comments.
Login now