##// END OF EJS Templates
Merge pull request #1 from ipython/master...
Kousik Mitra -
r25329:875db0e2 merge
parent child Browse files
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
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 # encoding: utf-8
1 # encoding: utf-8
2 """sys.excepthook for IPython itself, leaves a detailed report on disk.
2 """sys.excepthook for IPython itself, leaves a detailed report on disk.
3
3
4 Authors:
4 Authors:
5
5
6 * Fernando Perez
6 * Fernando Perez
7 * Brian E. Granger
7 * Brian E. Granger
8 """
8 """
9
9
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
11 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
12 # Copyright (C) 2008-2011 The IPython Development Team
12 # Copyright (C) 2008-2011 The IPython Development Team
13 #
13 #
14 # Distributed under the terms of the BSD License. The full license is in
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
15 # the file COPYING, distributed as part of this software.
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19 # Imports
19 # Imports
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 import os
22 import os
23 import sys
23 import sys
24 import traceback
24 import traceback
25 from pprint import pformat
25 from pprint import pformat
26
26
27 from IPython.core import ultratb
27 from IPython.core import ultratb
28 from IPython.core.release import author_email
28 from IPython.core.release import author_email
29 from IPython.utils.sysinfo import sys_info
29 from IPython.utils.sysinfo import sys_info
30 from IPython.utils.py3compat import input
30 from IPython.utils.py3compat import input
31
31
32 from IPython.core.release import __version__ as version
33
32 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
33 # Code
35 # Code
34 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
35
37
36 # Template for the user message.
38 # Template for the user message.
37 _default_message_template = """\
39 _default_message_template = """\
38 Oops, {app_name} crashed. We do our best to make it stable, but...
40 Oops, {app_name} crashed. We do our best to make it stable, but...
39
41
40 A crash report was automatically generated with the following information:
42 A crash report was automatically generated with the following information:
41 - A verbatim copy of the crash traceback.
43 - A verbatim copy of the crash traceback.
42 - A copy of your input history during this session.
44 - A copy of your input history during this session.
43 - Data on your current {app_name} configuration.
45 - Data on your current {app_name} configuration.
44
46
45 It was left in the file named:
47 It was left in the file named:
46 \t'{crash_report_fname}'
48 \t'{crash_report_fname}'
47 If you can email this file to the developers, the information in it will help
49 If you can email this file to the developers, the information in it will help
48 them in understanding and correcting the problem.
50 them in understanding and correcting the problem.
49
51
50 You can mail it to: {contact_name} at {contact_email}
52 You can mail it to: {contact_name} at {contact_email}
51 with the subject '{app_name} Crash Report'.
53 with the subject '{app_name} Crash Report'.
52
54
53 If you want to do it now, the following command will work (under Unix):
55 If you want to do it now, the following command will work (under Unix):
54 mail -s '{app_name} Crash Report' {contact_email} < {crash_report_fname}
56 mail -s '{app_name} Crash Report' {contact_email} < {crash_report_fname}
55
57
56 In your email, please also include information about:
58 In your email, please also include information about:
57 - The operating system under which the crash happened: Linux, macOS, Windows,
59 - The operating system under which the crash happened: Linux, macOS, Windows,
58 other, and which exact version (for example: Ubuntu 16.04.3, macOS 10.13.2,
60 other, and which exact version (for example: Ubuntu 16.04.3, macOS 10.13.2,
59 Windows 10 Pro), and whether it is 32-bit or 64-bit;
61 Windows 10 Pro), and whether it is 32-bit or 64-bit;
60 - How {app_name} was installed: using pip or conda, from GitHub, as part of
62 - How {app_name} was installed: using pip or conda, from GitHub, as part of
61 a Docker container, or other, providing more detail if possible;
63 a Docker container, or other, providing more detail if possible;
62 - How to reproduce the crash: what exact sequence of instructions can one
64 - How to reproduce the crash: what exact sequence of instructions can one
63 input to get the same crash? Ideally, find a minimal yet complete sequence
65 input to get the same crash? Ideally, find a minimal yet complete sequence
64 of instructions that yields the crash.
66 of instructions that yields the crash.
65
67
66 To ensure accurate tracking of this issue, please file a report about it at:
68 To ensure accurate tracking of this issue, please file a report about it at:
67 {bug_tracker}
69 {bug_tracker}
68 """
70 """
69
71
70 _lite_message_template = """
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 https://github.com/ipython/ipython/issues
74 https://github.com/ipython/ipython/issues
73 or send an email to the mailing list at {email}
75 or send an email to the mailing list at {email}
74
76
75 You can print a more detailed traceback right now with "%tb", or use "%debug"
77 You can print a more detailed traceback right now with "%tb", or use "%debug"
76 to interactively debug it.
78 to interactively debug it.
77
79
78 Extra-detailed tracebacks for bug-reporting purposes can be enabled via:
80 Extra-detailed tracebacks for bug-reporting purposes can be enabled via:
79 {config}Application.verbose_crash=True
81 {config}Application.verbose_crash=True
80 """
82 """
81
83
82
84
83 class CrashHandler(object):
85 class CrashHandler(object):
84 """Customizable crash handlers for IPython applications.
86 """Customizable crash handlers for IPython applications.
85
87
86 Instances of this class provide a :meth:`__call__` method which can be
88 Instances of this class provide a :meth:`__call__` method which can be
87 used as a ``sys.excepthook``. The :meth:`__call__` signature is::
89 used as a ``sys.excepthook``. The :meth:`__call__` signature is::
88
90
89 def __call__(self, etype, evalue, etb)
91 def __call__(self, etype, evalue, etb)
90 """
92 """
91
93
92 message_template = _default_message_template
94 message_template = _default_message_template
93 section_sep = '\n\n'+'*'*75+'\n\n'
95 section_sep = '\n\n'+'*'*75+'\n\n'
94
96
95 def __init__(self, app, contact_name=None, contact_email=None,
97 def __init__(self, app, contact_name=None, contact_email=None,
96 bug_tracker=None, show_crash_traceback=True, call_pdb=False):
98 bug_tracker=None, show_crash_traceback=True, call_pdb=False):
97 """Create a new crash handler
99 """Create a new crash handler
98
100
99 Parameters
101 Parameters
100 ----------
102 ----------
101 app : Application
103 app : Application
102 A running :class:`Application` instance, which will be queried at
104 A running :class:`Application` instance, which will be queried at
103 crash time for internal information.
105 crash time for internal information.
104
106
105 contact_name : str
107 contact_name : str
106 A string with the name of the person to contact.
108 A string with the name of the person to contact.
107
109
108 contact_email : str
110 contact_email : str
109 A string with the email address of the contact.
111 A string with the email address of the contact.
110
112
111 bug_tracker : str
113 bug_tracker : str
112 A string with the URL for your project's bug tracker.
114 A string with the URL for your project's bug tracker.
113
115
114 show_crash_traceback : bool
116 show_crash_traceback : bool
115 If false, don't print the crash traceback on stderr, only generate
117 If false, don't print the crash traceback on stderr, only generate
116 the on-disk report
118 the on-disk report
117
119
118 Non-argument instance attributes:
120 Non-argument instance attributes:
119
121
120 These instances contain some non-argument attributes which allow for
122 These instances contain some non-argument attributes which allow for
121 further customization of the crash handler's behavior. Please see the
123 further customization of the crash handler's behavior. Please see the
122 source for further details.
124 source for further details.
123 """
125 """
124 self.crash_report_fname = "Crash_report_%s.txt" % app.name
126 self.crash_report_fname = "Crash_report_%s.txt" % app.name
125 self.app = app
127 self.app = app
126 self.call_pdb = call_pdb
128 self.call_pdb = call_pdb
127 #self.call_pdb = True # dbg
129 #self.call_pdb = True # dbg
128 self.show_crash_traceback = show_crash_traceback
130 self.show_crash_traceback = show_crash_traceback
129 self.info = dict(app_name = app.name,
131 self.info = dict(app_name = app.name,
130 contact_name = contact_name,
132 contact_name = contact_name,
131 contact_email = contact_email,
133 contact_email = contact_email,
132 bug_tracker = bug_tracker,
134 bug_tracker = bug_tracker,
133 crash_report_fname = self.crash_report_fname)
135 crash_report_fname = self.crash_report_fname)
134
136
135
137
136 def __call__(self, etype, evalue, etb):
138 def __call__(self, etype, evalue, etb):
137 """Handle an exception, call for compatible with sys.excepthook"""
139 """Handle an exception, call for compatible with sys.excepthook"""
138
140
139 # do not allow the crash handler to be called twice without reinstalling it
141 # do not allow the crash handler to be called twice without reinstalling it
140 # this prevents unlikely errors in the crash handling from entering an
142 # this prevents unlikely errors in the crash handling from entering an
141 # infinite loop.
143 # infinite loop.
142 sys.excepthook = sys.__excepthook__
144 sys.excepthook = sys.__excepthook__
143
145
144 # Report tracebacks shouldn't use color in general (safer for users)
146 # Report tracebacks shouldn't use color in general (safer for users)
145 color_scheme = 'NoColor'
147 color_scheme = 'NoColor'
146
148
147 # Use this ONLY for developer debugging (keep commented out for release)
149 # Use this ONLY for developer debugging (keep commented out for release)
148 #color_scheme = 'Linux' # dbg
150 #color_scheme = 'Linux' # dbg
149 try:
151 try:
150 rptdir = self.app.ipython_dir
152 rptdir = self.app.ipython_dir
151 except:
153 except:
152 rptdir = os.getcwd()
154 rptdir = os.getcwd()
153 if rptdir is None or not os.path.isdir(rptdir):
155 if rptdir is None or not os.path.isdir(rptdir):
154 rptdir = os.getcwd()
156 rptdir = os.getcwd()
155 report_name = os.path.join(rptdir,self.crash_report_fname)
157 report_name = os.path.join(rptdir,self.crash_report_fname)
156 # write the report filename into the instance dict so it can get
158 # write the report filename into the instance dict so it can get
157 # properly expanded out in the user message template
159 # properly expanded out in the user message template
158 self.crash_report_fname = report_name
160 self.crash_report_fname = report_name
159 self.info['crash_report_fname'] = report_name
161 self.info['crash_report_fname'] = report_name
160 TBhandler = ultratb.VerboseTB(
162 TBhandler = ultratb.VerboseTB(
161 color_scheme=color_scheme,
163 color_scheme=color_scheme,
162 long_header=1,
164 long_header=1,
163 call_pdb=self.call_pdb,
165 call_pdb=self.call_pdb,
164 )
166 )
165 if self.call_pdb:
167 if self.call_pdb:
166 TBhandler(etype,evalue,etb)
168 TBhandler(etype,evalue,etb)
167 return
169 return
168 else:
170 else:
169 traceback = TBhandler.text(etype,evalue,etb,context=31)
171 traceback = TBhandler.text(etype,evalue,etb,context=31)
170
172
171 # print traceback to screen
173 # print traceback to screen
172 if self.show_crash_traceback:
174 if self.show_crash_traceback:
173 print(traceback, file=sys.stderr)
175 print(traceback, file=sys.stderr)
174
176
175 # and generate a complete report on disk
177 # and generate a complete report on disk
176 try:
178 try:
177 report = open(report_name,'w')
179 report = open(report_name,'w')
178 except:
180 except:
179 print('Could not create crash report on disk.', file=sys.stderr)
181 print('Could not create crash report on disk.', file=sys.stderr)
180 return
182 return
181
183
182 with report:
184 with report:
183 # Inform user on stderr of what happened
185 # Inform user on stderr of what happened
184 print('\n'+'*'*70+'\n', file=sys.stderr)
186 print('\n'+'*'*70+'\n', file=sys.stderr)
185 print(self.message_template.format(**self.info), file=sys.stderr)
187 print(self.message_template.format(**self.info), file=sys.stderr)
186
188
187 # Construct report on disk
189 # Construct report on disk
188 report.write(self.make_report(traceback))
190 report.write(self.make_report(traceback))
189
191
190 input("Hit <Enter> to quit (your terminal may close):")
192 input("Hit <Enter> to quit (your terminal may close):")
191
193
192 def make_report(self,traceback):
194 def make_report(self,traceback):
193 """Return a string containing a crash report."""
195 """Return a string containing a crash report."""
194
196
195 sec_sep = self.section_sep
197 sec_sep = self.section_sep
196
198
197 report = ['*'*75+'\n\n'+'IPython post-mortem report\n\n']
199 report = ['*'*75+'\n\n'+'IPython post-mortem report\n\n']
198 rpt_add = report.append
200 rpt_add = report.append
199 rpt_add(sys_info())
201 rpt_add(sys_info())
200
202
201 try:
203 try:
202 config = pformat(self.app.config)
204 config = pformat(self.app.config)
203 rpt_add(sec_sep)
205 rpt_add(sec_sep)
204 rpt_add('Application name: %s\n\n' % self.app_name)
206 rpt_add('Application name: %s\n\n' % self.app_name)
205 rpt_add('Current user configuration structure:\n\n')
207 rpt_add('Current user configuration structure:\n\n')
206 rpt_add(config)
208 rpt_add(config)
207 except:
209 except:
208 pass
210 pass
209 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
211 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
210
212
211 return ''.join(report)
213 return ''.join(report)
212
214
213
215
214 def crash_handler_lite(etype, evalue, tb):
216 def crash_handler_lite(etype, evalue, tb):
215 """a light excepthook, adding a small message to the usual traceback"""
217 """a light excepthook, adding a small message to the usual traceback"""
216 traceback.print_exception(etype, evalue, tb)
218 traceback.print_exception(etype, evalue, tb)
217
219
218 from IPython.core.interactiveshell import InteractiveShell
220 from IPython.core.interactiveshell import InteractiveShell
219 if InteractiveShell.initialized():
221 if InteractiveShell.initialized():
220 # we are in a Shell environment, give %magic example
222 # we are in a Shell environment, give %magic example
221 config = "%config "
223 config = "%config "
222 else:
224 else:
223 # we are not in a shell, show generic config
225 # we are not in a shell, show generic config
224 config = "c."
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 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Displayhook for IPython.
2 """Displayhook for IPython.
3
3
4 This defines a callable class that IPython uses for `sys.displayhook`.
4 This defines a callable class that IPython uses for `sys.displayhook`.
5 """
5 """
6
6
7 # Copyright (c) IPython Development Team.
7 # Copyright (c) IPython Development Team.
8 # Distributed under the terms of the Modified BSD License.
8 # Distributed under the terms of the Modified BSD License.
9
9
10 import builtins as builtin_mod
10 import builtins as builtin_mod
11 import sys
11 import sys
12 import io as _io
12 import io as _io
13 import tokenize
13 import tokenize
14
14
15 from traitlets.config.configurable import Configurable
15 from traitlets.config.configurable import Configurable
16 from traitlets import Instance, Float
16 from traitlets import Instance, Float
17 from warnings import warn
17 from warnings import warn
18
18
19 # TODO: Move the various attributes (cache_size, [others now moved]). Some
19 # TODO: Move the various attributes (cache_size, [others now moved]). Some
20 # of these are also attributes of InteractiveShell. They should be on ONE object
20 # of these are also attributes of InteractiveShell. They should be on ONE object
21 # only and the other objects should ask that one object for their values.
21 # only and the other objects should ask that one object for their values.
22
22
23 class DisplayHook(Configurable):
23 class DisplayHook(Configurable):
24 """The custom IPython displayhook to replace sys.displayhook.
24 """The custom IPython displayhook to replace sys.displayhook.
25
25
26 This class does many things, but the basic idea is that it is a callable
26 This class does many things, but the basic idea is that it is a callable
27 that gets called anytime user code returns a value.
27 that gets called anytime user code returns a value.
28 """
28 """
29
29
30 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
30 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
31 allow_none=True)
31 allow_none=True)
32 exec_result = Instance('IPython.core.interactiveshell.ExecutionResult',
32 exec_result = Instance('IPython.core.interactiveshell.ExecutionResult',
33 allow_none=True)
33 allow_none=True)
34 cull_fraction = Float(0.2)
34 cull_fraction = Float(0.2)
35
35
36 def __init__(self, shell=None, cache_size=1000, **kwargs):
36 def __init__(self, shell=None, cache_size=1000, **kwargs):
37 super(DisplayHook, self).__init__(shell=shell, **kwargs)
37 super(DisplayHook, self).__init__(shell=shell, **kwargs)
38 cache_size_min = 3
38 cache_size_min = 3
39 if cache_size <= 0:
39 if cache_size <= 0:
40 self.do_full_cache = 0
40 self.do_full_cache = 0
41 cache_size = 0
41 cache_size = 0
42 elif cache_size < cache_size_min:
42 elif cache_size < cache_size_min:
43 self.do_full_cache = 0
43 self.do_full_cache = 0
44 cache_size = 0
44 cache_size = 0
45 warn('caching was disabled (min value for cache size is %s).' %
45 warn('caching was disabled (min value for cache size is %s).' %
46 cache_size_min,stacklevel=3)
46 cache_size_min,stacklevel=3)
47 else:
47 else:
48 self.do_full_cache = 1
48 self.do_full_cache = 1
49
49
50 self.cache_size = cache_size
50 self.cache_size = cache_size
51
51
52 # we need a reference to the user-level namespace
52 # we need a reference to the user-level namespace
53 self.shell = shell
53 self.shell = shell
54
54
55 self._,self.__,self.___ = '','',''
55 self._,self.__,self.___ = '','',''
56
56
57 # these are deliberately global:
57 # these are deliberately global:
58 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
58 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
59 self.shell.user_ns.update(to_user_ns)
59 self.shell.user_ns.update(to_user_ns)
60
60
61 @property
61 @property
62 def prompt_count(self):
62 def prompt_count(self):
63 return self.shell.execution_count
63 return self.shell.execution_count
64
64
65 #-------------------------------------------------------------------------
65 #-------------------------------------------------------------------------
66 # Methods used in __call__. Override these methods to modify the behavior
66 # Methods used in __call__. Override these methods to modify the behavior
67 # of the displayhook.
67 # of the displayhook.
68 #-------------------------------------------------------------------------
68 #-------------------------------------------------------------------------
69
69
70 def check_for_underscore(self):
70 def check_for_underscore(self):
71 """Check if the user has set the '_' variable by hand."""
71 """Check if the user has set the '_' variable by hand."""
72 # If something injected a '_' variable in __builtin__, delete
72 # If something injected a '_' variable in __builtin__, delete
73 # ipython's automatic one so we don't clobber that. gettext() in
73 # ipython's automatic one so we don't clobber that. gettext() in
74 # particular uses _, so we need to stay away from it.
74 # particular uses _, so we need to stay away from it.
75 if '_' in builtin_mod.__dict__:
75 if '_' in builtin_mod.__dict__:
76 try:
76 try:
77 user_value = self.shell.user_ns['_']
77 user_value = self.shell.user_ns['_']
78 if user_value is not self._:
78 if user_value is not self._:
79 return
79 return
80 del self.shell.user_ns['_']
80 del self.shell.user_ns['_']
81 except KeyError:
81 except KeyError:
82 pass
82 pass
83
83
84 def quiet(self):
84 def quiet(self):
85 """Should we silence the display hook because of ';'?"""
85 """Should we silence the display hook because of ';'?"""
86 # do not print output if input ends in ';'
86 # do not print output if input ends in ';'
87
87
88 try:
88 try:
89 cell = self.shell.history_manager.input_hist_parsed[-1]
89 cell = self.shell.history_manager.input_hist_parsed[-1]
90 except IndexError:
90 except IndexError:
91 # some uses of ipshellembed may fail here
91 # some uses of ipshellembed may fail here
92 return False
92 return False
93
93
94 sio = _io.StringIO(cell)
94 sio = _io.StringIO(cell)
95 tokens = list(tokenize.generate_tokens(sio.readline))
95 tokens = list(tokenize.generate_tokens(sio.readline))
96
96
97 for token in reversed(tokens):
97 for token in reversed(tokens):
98 if token[0] in (tokenize.ENDMARKER, tokenize.NL, tokenize.NEWLINE, tokenize.COMMENT):
98 if token[0] in (tokenize.ENDMARKER, tokenize.NL, tokenize.NEWLINE, tokenize.COMMENT):
99 continue
99 continue
100 if (token[0] == tokenize.OP) and (token[1] == ';'):
100 if (token[0] == tokenize.OP) and (token[1] == ';'):
101 return True
101 return True
102 else:
102 else:
103 return False
103 return False
104
104
105 def start_displayhook(self):
105 def start_displayhook(self):
106 """Start the displayhook, initializing resources."""
106 """Start the displayhook, initializing resources."""
107 pass
107 pass
108
108
109 def write_output_prompt(self):
109 def write_output_prompt(self):
110 """Write the output prompt.
110 """Write the output prompt.
111
111
112 The default implementation simply writes the prompt to
112 The default implementation simply writes the prompt to
113 ``sys.stdout``.
113 ``sys.stdout``.
114 """
114 """
115 # Use write, not print which adds an extra space.
115 # Use write, not print which adds an extra space.
116 sys.stdout.write(self.shell.separate_out)
116 sys.stdout.write(self.shell.separate_out)
117 outprompt = 'Out[{}]: '.format(self.shell.execution_count)
117 outprompt = 'Out[{}]: '.format(self.shell.execution_count)
118 if self.do_full_cache:
118 if self.do_full_cache:
119 sys.stdout.write(outprompt)
119 sys.stdout.write(outprompt)
120
120
121 def compute_format_data(self, result):
121 def compute_format_data(self, result):
122 """Compute format data of the object to be displayed.
122 """Compute format data of the object to be displayed.
123
123
124 The format data is a generalization of the :func:`repr` of an object.
124 The format data is a generalization of the :func:`repr` of an object.
125 In the default implementation the format data is a :class:`dict` of
125 In the default implementation the format data is a :class:`dict` of
126 key value pair where the keys are valid MIME types and the values
126 key value pair where the keys are valid MIME types and the values
127 are JSON'able data structure containing the raw data for that MIME
127 are JSON'able data structure containing the raw data for that MIME
128 type. It is up to frontends to determine pick a MIME to to use and
128 type. It is up to frontends to determine pick a MIME to to use and
129 display that data in an appropriate manner.
129 display that data in an appropriate manner.
130
130
131 This method only computes the format data for the object and should
131 This method only computes the format data for the object and should
132 NOT actually print or write that to a stream.
132 NOT actually print or write that to a stream.
133
133
134 Parameters
134 Parameters
135 ----------
135 ----------
136 result : object
136 result : object
137 The Python object passed to the display hook, whose format will be
137 The Python object passed to the display hook, whose format will be
138 computed.
138 computed.
139
139
140 Returns
140 Returns
141 -------
141 -------
142 (format_dict, md_dict) : dict
142 (format_dict, md_dict) : dict
143 format_dict is a :class:`dict` whose keys are valid MIME types and values are
143 format_dict is a :class:`dict` whose keys are valid MIME types and values are
144 JSON'able raw data for that MIME type. It is recommended that
144 JSON'able raw data for that MIME type. It is recommended that
145 all return values of this should always include the "text/plain"
145 all return values of this should always include the "text/plain"
146 MIME type representation of the object.
146 MIME type representation of the object.
147 md_dict is a :class:`dict` with the same MIME type keys
147 md_dict is a :class:`dict` with the same MIME type keys
148 of metadata associated with each output.
148 of metadata associated with each output.
149
149
150 """
150 """
151 return self.shell.display_formatter.format(result)
151 return self.shell.display_formatter.format(result)
152
152
153 # This can be set to True by the write_output_prompt method in a subclass
153 # This can be set to True by the write_output_prompt method in a subclass
154 prompt_end_newline = False
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 """Write the format data dict to the frontend.
157 """Write the format data dict to the frontend.
158
158
159 This default version of this method simply writes the plain text
159 This default version of this method simply writes the plain text
160 representation of the object to ``sys.stdout``. Subclasses should
160 representation of the object to ``sys.stdout``. Subclasses should
161 override this method to send the entire `format_dict` to the
161 override this method to send the entire `format_dict` to the
162 frontends.
162 frontends.
163
163
164 Parameters
164 Parameters
165 ----------
165 ----------
166 format_dict : dict
166 format_dict : dict
167 The format dict for the object passed to `sys.displayhook`.
167 The format dict for the object passed to `sys.displayhook`.
168 md_dict : dict (optional)
168 md_dict : dict (optional)
169 The metadata dict to be associated with the display data.
169 The metadata dict to be associated with the display data.
170 """
170 """
171 if 'text/plain' not in format_dict:
171 if 'text/plain' not in format_dict:
172 # nothing to do
172 # nothing to do
173 return
173 return
174 # We want to print because we want to always make sure we have a
174 # We want to print because we want to always make sure we have a
175 # newline, even if all the prompt separators are ''. This is the
175 # newline, even if all the prompt separators are ''. This is the
176 # standard IPython behavior.
176 # standard IPython behavior.
177 result_repr = format_dict['text/plain']
177 result_repr = format_dict['text/plain']
178 if '\n' in result_repr:
178 if '\n' in result_repr:
179 # So that multi-line strings line up with the left column of
179 # So that multi-line strings line up with the left column of
180 # the screen, instead of having the output prompt mess up
180 # the screen, instead of having the output prompt mess up
181 # their first line.
181 # their first line.
182 # We use the prompt template instead of the expanded prompt
182 # We use the prompt template instead of the expanded prompt
183 # because the expansion may add ANSI escapes that will interfere
183 # because the expansion may add ANSI escapes that will interfere
184 # with our ability to determine whether or not we should add
184 # with our ability to determine whether or not we should add
185 # a newline.
185 # a newline.
186 if not self.prompt_end_newline:
186 if not self.prompt_end_newline:
187 # But avoid extraneous empty lines.
187 # But avoid extraneous empty lines.
188 result_repr = '\n' + result_repr
188 result_repr = '\n' + result_repr
189
189
190 try:
190 try:
191 print(result_repr)
191 print(result_repr)
192 except UnicodeEncodeError:
192 except UnicodeEncodeError:
193 # If a character is not supported by the terminal encoding replace
193 # If a character is not supported by the terminal encoding replace
194 # it with its \u or \x representation
194 # it with its \u or \x representation
195 print(result_repr.encode(sys.stdout.encoding,'backslashreplace').decode(sys.stdout.encoding))
195 print(result_repr.encode(sys.stdout.encoding,'backslashreplace').decode(sys.stdout.encoding))
196
196
197 def update_user_ns(self, result):
197 def update_user_ns(self, result):
198 """Update user_ns with various things like _, __, _1, etc."""
198 """Update user_ns with various things like _, __, _1, etc."""
199
199
200 # Avoid recursive reference when displaying _oh/Out
200 # Avoid recursive reference when displaying _oh/Out
201 if self.cache_size and result is not self.shell.user_ns['_oh']:
201 if self.cache_size and result is not self.shell.user_ns['_oh']:
202 if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
202 if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
203 self.cull_cache()
203 self.cull_cache()
204
204
205 # Don't overwrite '_' and friends if '_' is in __builtin__
205 # Don't overwrite '_' and friends if '_' is in __builtin__
206 # (otherwise we cause buggy behavior for things like gettext). and
206 # (otherwise we cause buggy behavior for things like gettext). and
207 # do not overwrite _, __ or ___ if one of these has been assigned
207 # do not overwrite _, __ or ___ if one of these has been assigned
208 # by the user.
208 # by the user.
209 update_unders = True
209 update_unders = True
210 for unders in ['_'*i for i in range(1,4)]:
210 for unders in ['_'*i for i in range(1,4)]:
211 if not unders in self.shell.user_ns:
211 if not unders in self.shell.user_ns:
212 continue
212 continue
213 if getattr(self, unders) is not self.shell.user_ns.get(unders):
213 if getattr(self, unders) is not self.shell.user_ns.get(unders):
214 update_unders = False
214 update_unders = False
215
215
216 self.___ = self.__
216 self.___ = self.__
217 self.__ = self._
217 self.__ = self._
218 self._ = result
218 self._ = result
219
219
220 if ('_' not in builtin_mod.__dict__) and (update_unders):
220 if ('_' not in builtin_mod.__dict__) and (update_unders):
221 self.shell.push({'_':self._,
221 self.shell.push({'_':self._,
222 '__':self.__,
222 '__':self.__,
223 '___':self.___}, interactive=False)
223 '___':self.___}, interactive=False)
224
224
225 # hackish access to top-level namespace to create _1,_2... dynamically
225 # hackish access to top-level namespace to create _1,_2... dynamically
226 to_main = {}
226 to_main = {}
227 if self.do_full_cache:
227 if self.do_full_cache:
228 new_result = '_%s' % self.prompt_count
228 new_result = '_%s' % self.prompt_count
229 to_main[new_result] = result
229 to_main[new_result] = result
230 self.shell.push(to_main, interactive=False)
230 self.shell.push(to_main, interactive=False)
231 self.shell.user_ns['_oh'][self.prompt_count] = result
231 self.shell.user_ns['_oh'][self.prompt_count] = result
232
232
233 def fill_exec_result(self, result):
233 def fill_exec_result(self, result):
234 if self.exec_result is not None:
234 if self.exec_result is not None:
235 self.exec_result.result = result
235 self.exec_result.result = result
236
236
237 def log_output(self, format_dict):
237 def log_output(self, format_dict):
238 """Log the output."""
238 """Log the output."""
239 if 'text/plain' not in format_dict:
239 if 'text/plain' not in format_dict:
240 # nothing to do
240 # nothing to do
241 return
241 return
242 if self.shell.logger.log_output:
242 if self.shell.logger.log_output:
243 self.shell.logger.log_write(format_dict['text/plain'], 'output')
243 self.shell.logger.log_write(format_dict['text/plain'], 'output')
244 self.shell.history_manager.output_hist_reprs[self.prompt_count] = \
244 self.shell.history_manager.output_hist_reprs[self.prompt_count] = \
245 format_dict['text/plain']
245 format_dict['text/plain']
246
246
247 def finish_displayhook(self):
247 def finish_displayhook(self):
248 """Finish up all displayhook activities."""
248 """Finish up all displayhook activities."""
249 sys.stdout.write(self.shell.separate_out2)
249 sys.stdout.write(self.shell.separate_out2)
250 sys.stdout.flush()
250 sys.stdout.flush()
251
251
252 def __call__(self, result=None):
252 def __call__(self, result=None):
253 """Printing with history cache management.
253 """Printing with history cache management.
254
254
255 This is invoked every time the interpreter needs to print, and is
255 This is invoked every time the interpreter needs to print, and is
256 activated by setting the variable sys.displayhook to it.
256 activated by setting the variable sys.displayhook to it.
257 """
257 """
258 self.check_for_underscore()
258 self.check_for_underscore()
259 if result is not None and not self.quiet():
259 if result is not None and not self.quiet():
260 self.start_displayhook()
260 self.start_displayhook()
261 self.write_output_prompt()
261 self.write_output_prompt()
262 format_dict, md_dict = self.compute_format_data(result)
262 format_dict, md_dict = self.compute_format_data(result)
263 self.update_user_ns(result)
263 self.update_user_ns(result)
264 self.fill_exec_result(result)
264 self.fill_exec_result(result)
265 if format_dict:
265 if format_dict:
266 self.write_format_data(format_dict, md_dict)
266 self.write_format_data(format_dict, md_dict)
267 self.log_output(format_dict)
267 self.log_output(format_dict)
268 self.finish_displayhook()
268 self.finish_displayhook()
269
269
270 def cull_cache(self):
270 def cull_cache(self):
271 """Output cache is full, cull the oldest entries"""
271 """Output cache is full, cull the oldest entries"""
272 oh = self.shell.user_ns.get('_oh', {})
272 oh = self.shell.user_ns.get('_oh', {})
273 sz = len(oh)
273 sz = len(oh)
274 cull_count = max(int(sz * self.cull_fraction), 2)
274 cull_count = max(int(sz * self.cull_fraction), 2)
275 warn('Output cache limit (currently {sz} entries) hit.\n'
275 warn('Output cache limit (currently {sz} entries) hit.\n'
276 'Flushing oldest {cull_count} entries.'.format(sz=sz, cull_count=cull_count))
276 'Flushing oldest {cull_count} entries.'.format(sz=sz, cull_count=cull_count))
277
277
278 for i, n in enumerate(sorted(oh)):
278 for i, n in enumerate(sorted(oh)):
279 if i >= cull_count:
279 if i >= cull_count:
280 break
280 break
281 self.shell.user_ns.pop('_%i' % n, None)
281 self.shell.user_ns.pop('_%i' % n, None)
282 oh.pop(n, None)
282 oh.pop(n, None)
283
283
284
284
285 def flush(self):
285 def flush(self):
286 if not self.do_full_cache:
286 if not self.do_full_cache:
287 raise ValueError("You shouldn't have reached the cache flush "
287 raise ValueError("You shouldn't have reached the cache flush "
288 "if full caching is not enabled!")
288 "if full caching is not enabled!")
289 # delete auto-generated vars from global namespace
289 # delete auto-generated vars from global namespace
290
290
291 for n in range(1,self.prompt_count + 1):
291 for n in range(1,self.prompt_count + 1):
292 key = '_'+repr(n)
292 key = '_'+repr(n)
293 try:
293 try:
294 del self.shell.user_ns[key]
294 del self.shell.user_ns[key]
295 except: pass
295 except: pass
296 # In some embedded circumstances, the user_ns doesn't have the
296 # In some embedded circumstances, the user_ns doesn't have the
297 # '_oh' key set up.
297 # '_oh' key set up.
298 oh = self.shell.user_ns.get('_oh', None)
298 oh = self.shell.user_ns.get('_oh', None)
299 if oh is not None:
299 if oh is not None:
300 oh.clear()
300 oh.clear()
301
301
302 # Release our own references to objects:
302 # Release our own references to objects:
303 self._, self.__, self.___ = '', '', ''
303 self._, self.__, self.___ = '', '', ''
304
304
305 if '_' not in builtin_mod.__dict__:
305 if '_' not in builtin_mod.__dict__:
306 self.shell.user_ns.update({'_':self._,'__':self.__,'___':self.___})
306 self.shell.user_ns.update({'_':self._,'__':self.__,'___':self.___})
307 import gc
307 import gc
308 # TODO: Is this really needed?
308 # TODO: Is this really needed?
309 # IronPython blocks here forever
309 # IronPython blocks here forever
310 if sys.platform != "cli":
310 if sys.platform != "cli":
311 gc.collect()
311 gc.collect()
312
312
313
313
314 class CapturingDisplayHook(object):
314 class CapturingDisplayHook(object):
315 def __init__(self, shell, outputs=None):
315 def __init__(self, shell, outputs=None):
316 self.shell = shell
316 self.shell = shell
317 if outputs is None:
317 if outputs is None:
318 outputs = []
318 outputs = []
319 self.outputs = outputs
319 self.outputs = outputs
320
320
321 def __call__(self, result=None):
321 def __call__(self, result=None):
322 if result is None:
322 if result is None:
323 return
323 return
324 format_dict, md_dict = self.shell.display_formatter.format(result)
324 format_dict, md_dict = self.shell.display_formatter.format(result)
325 self.outputs.append({ 'data': format_dict, 'metadata': md_dict })
325 self.outputs.append({ 'data': format_dict, 'metadata': md_dict })
@@ -1,125 +1,138 b''
1 """An interface for publishing rich data to frontends.
1 """An interface for publishing rich data to frontends.
2
2
3 There are two components of the display system:
3 There are two components of the display system:
4
4
5 * Display formatters, which take a Python object and compute the
5 * Display formatters, which take a Python object and compute the
6 representation of the object in various formats (text, HTML, SVG, etc.).
6 representation of the object in various formats (text, HTML, SVG, etc.).
7 * The display publisher that is used to send the representation data to the
7 * The display publisher that is used to send the representation data to the
8 various frontends.
8 various frontends.
9
9
10 This module defines the logic display publishing. The display publisher uses
10 This module defines the logic display publishing. The display publisher uses
11 the ``display_data`` message type that is defined in the IPython messaging
11 the ``display_data`` message type that is defined in the IPython messaging
12 spec.
12 spec.
13 """
13 """
14
14
15 # Copyright (c) IPython Development Team.
15 # Copyright (c) IPython Development Team.
16 # Distributed under the terms of the Modified BSD License.
16 # Distributed under the terms of the Modified BSD License.
17
17
18
18
19 import sys
19 import sys
20
20
21 from traitlets.config.configurable import Configurable
21 from traitlets.config.configurable import Configurable
22 from traitlets import List
22 from traitlets import List, Dict
23
23
24 # This used to be defined here - it is imported for backwards compatibility
24 # This used to be defined here - it is imported for backwards compatibility
25 from .display import publish_display_data
25 from .display import publish_display_data
26
26
27 #-----------------------------------------------------------------------------
27 #-----------------------------------------------------------------------------
28 # Main payload class
28 # Main payload class
29 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
30
30
31
31 class DisplayPublisher(Configurable):
32 class DisplayPublisher(Configurable):
32 """A traited class that publishes display data to frontends.
33 """A traited class that publishes display data to frontends.
33
34
34 Instances of this class are created by the main IPython object and should
35 Instances of this class are created by the main IPython object and should
35 be accessed there.
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 def _validate_data(self, data, metadata=None):
43 def _validate_data(self, data, metadata=None):
39 """Validate the display data.
44 """Validate the display data.
40
45
41 Parameters
46 Parameters
42 ----------
47 ----------
43 data : dict
48 data : dict
44 The formata data dictionary.
49 The formata data dictionary.
45 metadata : dict
50 metadata : dict
46 Any metadata for the data.
51 Any metadata for the data.
47 """
52 """
48
53
49 if not isinstance(data, dict):
54 if not isinstance(data, dict):
50 raise TypeError('data must be a dict, got: %r' % data)
55 raise TypeError('data must be a dict, got: %r' % data)
51 if metadata is not None:
56 if metadata is not None:
52 if not isinstance(metadata, dict):
57 if not isinstance(metadata, dict):
53 raise TypeError('metadata must be a dict, got: %r' % data)
58 raise TypeError('metadata must be a dict, got: %r' % data)
54
59
55 # use * to indicate transient, update are keyword-only
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 """Publish data and metadata to all frontends.
62 """Publish data and metadata to all frontends.
58
63
59 See the ``display_data`` message in the messaging documentation for
64 See the ``display_data`` message in the messaging documentation for
60 more details about this message type.
65 more details about this message type.
61
66
62 The following MIME types are currently implemented:
67 The following MIME types are currently implemented:
63
68
64 * text/plain
69 * text/plain
65 * text/html
70 * text/html
66 * text/markdown
71 * text/markdown
67 * text/latex
72 * text/latex
68 * application/json
73 * application/json
69 * application/javascript
74 * application/javascript
70 * image/png
75 * image/png
71 * image/jpeg
76 * image/jpeg
72 * image/svg+xml
77 * image/svg+xml
73
78
74 Parameters
79 Parameters
75 ----------
80 ----------
76 data : dict
81 data : dict
77 A dictionary having keys that are valid MIME types (like
82 A dictionary having keys that are valid MIME types (like
78 'text/plain' or 'image/svg+xml') and values that are the data for
83 'text/plain' or 'image/svg+xml') and values that are the data for
79 that MIME type. The data itself must be a JSON'able data
84 that MIME type. The data itself must be a JSON'able data
80 structure. Minimally all data should have the 'text/plain' data,
85 structure. Minimally all data should have the 'text/plain' data,
81 which can be displayed by all frontends. If more than the plain
86 which can be displayed by all frontends. If more than the plain
82 text is given, it is up to the frontend to decide which
87 text is given, it is up to the frontend to decide which
83 representation to use.
88 representation to use.
84 metadata : dict
89 metadata : dict
85 A dictionary for metadata related to the data. This can contain
90 A dictionary for metadata related to the data. This can contain
86 arbitrary key, value pairs that frontends can use to interpret
91 arbitrary key, value pairs that frontends can use to interpret
87 the data. Metadata specific to each mime-type can be specified
92 the data. Metadata specific to each mime-type can be specified
88 in the metadata dict with the same mime-type keys as
93 in the metadata dict with the same mime-type keys as
89 the data itself.
94 the data itself.
90 source : str, deprecated
95 source : str, deprecated
91 Unused.
96 Unused.
92 transient: dict, keyword-only
97 transient: dict, keyword-only
93 A dictionary for transient data.
98 A dictionary for transient data.
94 Data in this dictionary should not be persisted as part of saving this output.
99 Data in this dictionary should not be persisted as part of saving this output.
95 Examples include 'display_id'.
100 Examples include 'display_id'.
96 update: bool, keyword-only, default: False
101 update: bool, keyword-only, default: False
97 If True, only update existing outputs with the same display_id,
102 If True, only update existing outputs with the same display_id,
98 rather than creating a new output.
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 if 'text/plain' in data:
115 if 'text/plain' in data:
103 print(data['text/plain'])
116 print(data['text/plain'])
104
117
105 def clear_output(self, wait=False):
118 def clear_output(self, wait=False):
106 """Clear the output of the cell receiving output."""
119 """Clear the output of the cell receiving output."""
107 print('\033[2K\r', end='')
120 print('\033[2K\r', end='')
108 sys.stdout.flush()
121 sys.stdout.flush()
109 print('\033[2K\r', end='')
122 print('\033[2K\r', end='')
110 sys.stderr.flush()
123 sys.stderr.flush()
111
124
112
125
113 class CapturingDisplayPublisher(DisplayPublisher):
126 class CapturingDisplayPublisher(DisplayPublisher):
114 """A DisplayPublisher that stores"""
127 """A DisplayPublisher that stores"""
115 outputs = List()
128 outputs = List()
116
129
117 def publish(self, data, metadata=None, source=None, *, transient=None, update=False):
130 def publish(self, data, metadata=None, source=None, *, transient=None, update=False):
118 self.outputs.append({'data':data, 'metadata':metadata,
131 self.outputs.append({'data':data, 'metadata':metadata,
119 'transient':transient, 'update':update})
132 'transient':transient, 'update':update})
120
133
121 def clear_output(self, wait=False):
134 def clear_output(self, wait=False):
122 super(CapturingDisplayPublisher, self).clear_output(wait)
135 super(CapturingDisplayPublisher, self).clear_output(wait)
123
136
124 # empty the list, *do not* reassign a new list
137 # empty the list, *do not* reassign a new list
125 self.outputs.clear()
138 self.outputs.clear()
@@ -1,3701 +1,3701 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Main IPython class."""
2 """Main IPython class."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2011 The IPython Development Team
7 # Copyright (C) 2008-2011 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13
13
14 import abc
14 import abc
15 import ast
15 import ast
16 import asyncio
16 import asyncio
17 import atexit
17 import atexit
18 import builtins as builtin_mod
18 import builtins as builtin_mod
19 import functools
19 import functools
20 import inspect
20 import inspect
21 import os
21 import os
22 import re
22 import re
23 import runpy
23 import runpy
24 import sys
24 import sys
25 import tempfile
25 import tempfile
26 import traceback
26 import traceback
27 import types
27 import types
28 import subprocess
28 import subprocess
29 import warnings
29 import warnings
30 from io import open as io_open
30 from io import open as io_open
31
31
32 from pickleshare import PickleShareDB
32 from pickleshare import PickleShareDB
33
33
34 from traitlets.config.configurable import SingletonConfigurable
34 from traitlets.config.configurable import SingletonConfigurable
35 from traitlets.utils.importstring import import_item
35 from traitlets.utils.importstring import import_item
36 from IPython.core import oinspect
36 from IPython.core import oinspect
37 from IPython.core import magic
37 from IPython.core import magic
38 from IPython.core import page
38 from IPython.core import page
39 from IPython.core import prefilter
39 from IPython.core import prefilter
40 from IPython.core import ultratb
40 from IPython.core import ultratb
41 from IPython.core.alias import Alias, AliasManager
41 from IPython.core.alias import Alias, AliasManager
42 from IPython.core.autocall import ExitAutocall
42 from IPython.core.autocall import ExitAutocall
43 from IPython.core.builtin_trap import BuiltinTrap
43 from IPython.core.builtin_trap import BuiltinTrap
44 from IPython.core.events import EventManager, available_events
44 from IPython.core.events import EventManager, available_events
45 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
45 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
46 from IPython.core.debugger import Pdb
46 from IPython.core.debugger import Pdb
47 from IPython.core.display_trap import DisplayTrap
47 from IPython.core.display_trap import DisplayTrap
48 from IPython.core.displayhook import DisplayHook
48 from IPython.core.displayhook import DisplayHook
49 from IPython.core.displaypub import DisplayPublisher
49 from IPython.core.displaypub import DisplayPublisher
50 from IPython.core.error import InputRejected, UsageError
50 from IPython.core.error import InputRejected, UsageError
51 from IPython.core.extensions import ExtensionManager
51 from IPython.core.extensions import ExtensionManager
52 from IPython.core.formatters import DisplayFormatter
52 from IPython.core.formatters import DisplayFormatter
53 from IPython.core.history import HistoryManager
53 from IPython.core.history import HistoryManager
54 from IPython.core.inputtransformer2 import ESC_MAGIC, ESC_MAGIC2
54 from IPython.core.inputtransformer2 import ESC_MAGIC, ESC_MAGIC2
55 from IPython.core.logger import Logger
55 from IPython.core.logger import Logger
56 from IPython.core.macro import Macro
56 from IPython.core.macro import Macro
57 from IPython.core.payload import PayloadManager
57 from IPython.core.payload import PayloadManager
58 from IPython.core.prefilter import PrefilterManager
58 from IPython.core.prefilter import PrefilterManager
59 from IPython.core.profiledir import ProfileDir
59 from IPython.core.profiledir import ProfileDir
60 from IPython.core.usage import default_banner
60 from IPython.core.usage import default_banner
61 from IPython.display import display
61 from IPython.display import display
62 from IPython.testing.skipdoctest import skip_doctest
62 from IPython.testing.skipdoctest import skip_doctest
63 from IPython.utils import PyColorize
63 from IPython.utils import PyColorize
64 from IPython.utils import io
64 from IPython.utils import io
65 from IPython.utils import py3compat
65 from IPython.utils import py3compat
66 from IPython.utils import openpy
66 from IPython.utils import openpy
67 from IPython.utils.decorators import undoc
67 from IPython.utils.decorators import undoc
68 from IPython.utils.io import ask_yes_no
68 from IPython.utils.io import ask_yes_no
69 from IPython.utils.ipstruct import Struct
69 from IPython.utils.ipstruct import Struct
70 from IPython.paths import get_ipython_dir
70 from IPython.paths import get_ipython_dir
71 from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
71 from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
72 from IPython.utils.process import system, getoutput
72 from IPython.utils.process import system, getoutput
73 from IPython.utils.strdispatch import StrDispatch
73 from IPython.utils.strdispatch import StrDispatch
74 from IPython.utils.syspathcontext import prepended_to_syspath
74 from IPython.utils.syspathcontext import prepended_to_syspath
75 from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
75 from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
76 from IPython.utils.tempdir import TemporaryDirectory
76 from IPython.utils.tempdir import TemporaryDirectory
77 from traitlets import (
77 from traitlets import (
78 Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
78 Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
79 observe, default, validate, Any
79 observe, default, validate, Any
80 )
80 )
81 from warnings import warn
81 from warnings import warn
82 from logging import error
82 from logging import error
83 import IPython.core.hooks
83 import IPython.core.hooks
84
84
85 from typing import List as ListType, Tuple
85 from typing import List as ListType, Tuple
86 from ast import AST
86 from ast import AST
87
87
88 # NoOpContext is deprecated, but ipykernel imports it from here.
88 # NoOpContext is deprecated, but ipykernel imports it from here.
89 # See https://github.com/ipython/ipykernel/issues/157
89 # See https://github.com/ipython/ipykernel/issues/157
90 from IPython.utils.contexts import NoOpContext
90 from IPython.utils.contexts import NoOpContext
91
91
92 try:
92 try:
93 import docrepr.sphinxify as sphx
93 import docrepr.sphinxify as sphx
94
94
95 def sphinxify(doc):
95 def sphinxify(doc):
96 with TemporaryDirectory() as dirname:
96 with TemporaryDirectory() as dirname:
97 return {
97 return {
98 'text/html': sphx.sphinxify(doc, dirname),
98 'text/html': sphx.sphinxify(doc, dirname),
99 'text/plain': doc
99 'text/plain': doc
100 }
100 }
101 except ImportError:
101 except ImportError:
102 sphinxify = None
102 sphinxify = None
103
103
104
104
105 class ProvisionalWarning(DeprecationWarning):
105 class ProvisionalWarning(DeprecationWarning):
106 """
106 """
107 Warning class for unstable features
107 Warning class for unstable features
108 """
108 """
109 pass
109 pass
110
110
111 if sys.version_info > (3,8):
111 if sys.version_info > (3,8):
112 from ast import Module
112 from ast import Module
113 else :
113 else :
114 # mock the new API, ignore second argument
114 # mock the new API, ignore second argument
115 # see https://github.com/ipython/ipython/issues/11590
115 # see https://github.com/ipython/ipython/issues/11590
116 from ast import Module as OriginalModule
116 from ast import Module as OriginalModule
117 Module = lambda nodelist, type_ignores: OriginalModule(nodelist)
117 Module = lambda nodelist, type_ignores: OriginalModule(nodelist)
118
118
119 if sys.version_info > (3,6):
119 if sys.version_info > (3,6):
120 _assign_nodes = (ast.AugAssign, ast.AnnAssign, ast.Assign)
120 _assign_nodes = (ast.AugAssign, ast.AnnAssign, ast.Assign)
121 _single_targets_nodes = (ast.AugAssign, ast.AnnAssign)
121 _single_targets_nodes = (ast.AugAssign, ast.AnnAssign)
122 else:
122 else:
123 _assign_nodes = (ast.AugAssign, ast.Assign )
123 _assign_nodes = (ast.AugAssign, ast.Assign )
124 _single_targets_nodes = (ast.AugAssign, )
124 _single_targets_nodes = (ast.AugAssign, )
125
125
126 #-----------------------------------------------------------------------------
126 #-----------------------------------------------------------------------------
127 # Await Helpers
127 # Await Helpers
128 #-----------------------------------------------------------------------------
128 #-----------------------------------------------------------------------------
129
129
130 def removed_co_newlocals(function:types.FunctionType) -> types.FunctionType:
130 def removed_co_newlocals(function:types.FunctionType) -> types.FunctionType:
131 """Return a function that do not create a new local scope.
131 """Return a function that do not create a new local scope.
132
132
133 Given a function, create a clone of this function where the co_newlocal flag
133 Given a function, create a clone of this function where the co_newlocal flag
134 has been removed, making this function code actually run in the sourounding
134 has been removed, making this function code actually run in the sourounding
135 scope.
135 scope.
136
136
137 We need this in order to run asynchronous code in user level namespace.
137 We need this in order to run asynchronous code in user level namespace.
138 """
138 """
139 from types import CodeType, FunctionType
139 from types import CodeType, FunctionType
140 CO_NEWLOCALS = 0x0002
140 CO_NEWLOCALS = 0x0002
141 code = function.__code__
141 code = function.__code__
142 new_co_flags = code.co_flags & ~CO_NEWLOCALS
142 new_co_flags = code.co_flags & ~CO_NEWLOCALS
143 if sys.version_info > (3, 8, 0, 'alpha', 3):
143 if sys.version_info > (3, 8, 0, 'alpha', 3):
144 new_code = code.replace(co_flags=new_co_flags)
144 new_code = code.replace(co_flags=new_co_flags)
145 else:
145 else:
146 new_code = CodeType(
146 new_code = CodeType(
147 code.co_argcount,
147 code.co_argcount,
148 code.co_kwonlyargcount,
148 code.co_kwonlyargcount,
149 code.co_nlocals,
149 code.co_nlocals,
150 code.co_stacksize,
150 code.co_stacksize,
151 new_co_flags,
151 new_co_flags,
152 code.co_code,
152 code.co_code,
153 code.co_consts,
153 code.co_consts,
154 code.co_names,
154 code.co_names,
155 code.co_varnames,
155 code.co_varnames,
156 code.co_filename,
156 code.co_filename,
157 code.co_name,
157 code.co_name,
158 code.co_firstlineno,
158 code.co_firstlineno,
159 code.co_lnotab,
159 code.co_lnotab,
160 code.co_freevars,
160 code.co_freevars,
161 code.co_cellvars
161 code.co_cellvars
162 )
162 )
163 return FunctionType(new_code, globals(), function.__name__, function.__defaults__)
163 return FunctionType(new_code, globals(), function.__name__, function.__defaults__)
164
164
165
165
166 # we still need to run things using the asyncio eventloop, but there is no
166 # we still need to run things using the asyncio eventloop, but there is no
167 # async integration
167 # async integration
168 from .async_helpers import (_asyncio_runner, _asyncify, _pseudo_sync_runner)
168 from .async_helpers import (_asyncio_runner, _asyncify, _pseudo_sync_runner)
169 from .async_helpers import _curio_runner, _trio_runner, _should_be_async
169 from .async_helpers import _curio_runner, _trio_runner, _should_be_async
170
170
171
171
172 def _ast_asyncify(cell:str, wrapper_name:str) -> ast.Module:
172 def _ast_asyncify(cell:str, wrapper_name:str) -> ast.Module:
173 """
173 """
174 Parse a cell with top-level await and modify the AST to be able to run it later.
174 Parse a cell with top-level await and modify the AST to be able to run it later.
175
175
176 Parameter
176 Parameter
177 ---------
177 ---------
178
178
179 cell: str
179 cell: str
180 The code cell to asyncronify
180 The code cell to asyncronify
181 wrapper_name: str
181 wrapper_name: str
182 The name of the function to be used to wrap the passed `cell`. It is
182 The name of the function to be used to wrap the passed `cell`. It is
183 advised to **not** use a python identifier in order to not pollute the
183 advised to **not** use a python identifier in order to not pollute the
184 global namespace in which the function will be ran.
184 global namespace in which the function will be ran.
185
185
186 Return
186 Return
187 ------
187 ------
188
188
189 A module object AST containing **one** function named `wrapper_name`.
189 A module object AST containing **one** function named `wrapper_name`.
190
190
191 The given code is wrapped in a async-def function, parsed into an AST, and
191 The given code is wrapped in a async-def function, parsed into an AST, and
192 the resulting function definition AST is modified to return the last
192 the resulting function definition AST is modified to return the last
193 expression.
193 expression.
194
194
195 The last expression or await node is moved into a return statement at the
195 The last expression or await node is moved into a return statement at the
196 end of the function, and removed from its original location. If the last
196 end of the function, and removed from its original location. If the last
197 node is not Expr or Await nothing is done.
197 node is not Expr or Await nothing is done.
198
198
199 The function `__code__` will need to be later modified (by
199 The function `__code__` will need to be later modified (by
200 ``removed_co_newlocals``) in a subsequent step to not create new `locals()`
200 ``removed_co_newlocals``) in a subsequent step to not create new `locals()`
201 meaning that the local and global scope are the same, ie as if the body of
201 meaning that the local and global scope are the same, ie as if the body of
202 the function was at module level.
202 the function was at module level.
203
203
204 Lastly a call to `locals()` is made just before the last expression of the
204 Lastly a call to `locals()` is made just before the last expression of the
205 function, or just after the last assignment or statement to make sure the
205 function, or just after the last assignment or statement to make sure the
206 global dict is updated as python function work with a local fast cache which
206 global dict is updated as python function work with a local fast cache which
207 is updated only on `local()` calls.
207 is updated only on `local()` calls.
208 """
208 """
209
209
210 from ast import Expr, Await, Return
210 from ast import Expr, Await, Return
211 if sys.version_info >= (3,8):
211 if sys.version_info >= (3,8):
212 return ast.parse(cell)
212 return ast.parse(cell)
213 tree = ast.parse(_asyncify(cell))
213 tree = ast.parse(_asyncify(cell))
214
214
215 function_def = tree.body[0]
215 function_def = tree.body[0]
216 function_def.name = wrapper_name
216 function_def.name = wrapper_name
217 try_block = function_def.body[0]
217 try_block = function_def.body[0]
218 lastexpr = try_block.body[-1]
218 lastexpr = try_block.body[-1]
219 if isinstance(lastexpr, (Expr, Await)):
219 if isinstance(lastexpr, (Expr, Await)):
220 try_block.body[-1] = Return(lastexpr.value)
220 try_block.body[-1] = Return(lastexpr.value)
221 ast.fix_missing_locations(tree)
221 ast.fix_missing_locations(tree)
222 return tree
222 return tree
223 #-----------------------------------------------------------------------------
223 #-----------------------------------------------------------------------------
224 # Globals
224 # Globals
225 #-----------------------------------------------------------------------------
225 #-----------------------------------------------------------------------------
226
226
227 # compiled regexps for autoindent management
227 # compiled regexps for autoindent management
228 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
228 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
229
229
230 #-----------------------------------------------------------------------------
230 #-----------------------------------------------------------------------------
231 # Utilities
231 # Utilities
232 #-----------------------------------------------------------------------------
232 #-----------------------------------------------------------------------------
233
233
234 @undoc
234 @undoc
235 def softspace(file, newvalue):
235 def softspace(file, newvalue):
236 """Copied from code.py, to remove the dependency"""
236 """Copied from code.py, to remove the dependency"""
237
237
238 oldvalue = 0
238 oldvalue = 0
239 try:
239 try:
240 oldvalue = file.softspace
240 oldvalue = file.softspace
241 except AttributeError:
241 except AttributeError:
242 pass
242 pass
243 try:
243 try:
244 file.softspace = newvalue
244 file.softspace = newvalue
245 except (AttributeError, TypeError):
245 except (AttributeError, TypeError):
246 # "attribute-less object" or "read-only attributes"
246 # "attribute-less object" or "read-only attributes"
247 pass
247 pass
248 return oldvalue
248 return oldvalue
249
249
250 @undoc
250 @undoc
251 def no_op(*a, **kw):
251 def no_op(*a, **kw):
252 pass
252 pass
253
253
254
254
255 class SpaceInInput(Exception): pass
255 class SpaceInInput(Exception): pass
256
256
257
257
258 def get_default_colors():
258 def get_default_colors():
259 "DEPRECATED"
259 "DEPRECATED"
260 warn('get_default_color is deprecated since IPython 5.0, and returns `Neutral` on all platforms.',
260 warn('get_default_color is deprecated since IPython 5.0, and returns `Neutral` on all platforms.',
261 DeprecationWarning, stacklevel=2)
261 DeprecationWarning, stacklevel=2)
262 return 'Neutral'
262 return 'Neutral'
263
263
264
264
265 class SeparateUnicode(Unicode):
265 class SeparateUnicode(Unicode):
266 r"""A Unicode subclass to validate separate_in, separate_out, etc.
266 r"""A Unicode subclass to validate separate_in, separate_out, etc.
267
267
268 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
268 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
269 """
269 """
270
270
271 def validate(self, obj, value):
271 def validate(self, obj, value):
272 if value == '0': value = ''
272 if value == '0': value = ''
273 value = value.replace('\\n','\n')
273 value = value.replace('\\n','\n')
274 return super(SeparateUnicode, self).validate(obj, value)
274 return super(SeparateUnicode, self).validate(obj, value)
275
275
276
276
277 @undoc
277 @undoc
278 class DummyMod(object):
278 class DummyMod(object):
279 """A dummy module used for IPython's interactive module when
279 """A dummy module used for IPython's interactive module when
280 a namespace must be assigned to the module's __dict__."""
280 a namespace must be assigned to the module's __dict__."""
281 __spec__ = None
281 __spec__ = None
282
282
283
283
284 class ExecutionInfo(object):
284 class ExecutionInfo(object):
285 """The arguments used for a call to :meth:`InteractiveShell.run_cell`
285 """The arguments used for a call to :meth:`InteractiveShell.run_cell`
286
286
287 Stores information about what is going to happen.
287 Stores information about what is going to happen.
288 """
288 """
289 raw_cell = None
289 raw_cell = None
290 store_history = False
290 store_history = False
291 silent = False
291 silent = False
292 shell_futures = True
292 shell_futures = True
293
293
294 def __init__(self, raw_cell, store_history, silent, shell_futures):
294 def __init__(self, raw_cell, store_history, silent, shell_futures):
295 self.raw_cell = raw_cell
295 self.raw_cell = raw_cell
296 self.store_history = store_history
296 self.store_history = store_history
297 self.silent = silent
297 self.silent = silent
298 self.shell_futures = shell_futures
298 self.shell_futures = shell_futures
299
299
300 def __repr__(self):
300 def __repr__(self):
301 name = self.__class__.__qualname__
301 name = self.__class__.__qualname__
302 raw_cell = ((self.raw_cell[:50] + '..')
302 raw_cell = ((self.raw_cell[:50] + '..')
303 if len(self.raw_cell) > 50 else self.raw_cell)
303 if len(self.raw_cell) > 50 else self.raw_cell)
304 return '<%s object at %x, raw_cell="%s" store_history=%s silent=%s shell_futures=%s>' %\
304 return '<%s object at %x, raw_cell="%s" store_history=%s silent=%s shell_futures=%s>' %\
305 (name, id(self), raw_cell, self.store_history, self.silent, self.shell_futures)
305 (name, id(self), raw_cell, self.store_history, self.silent, self.shell_futures)
306
306
307
307
308 class ExecutionResult(object):
308 class ExecutionResult(object):
309 """The result of a call to :meth:`InteractiveShell.run_cell`
309 """The result of a call to :meth:`InteractiveShell.run_cell`
310
310
311 Stores information about what took place.
311 Stores information about what took place.
312 """
312 """
313 execution_count = None
313 execution_count = None
314 error_before_exec = None
314 error_before_exec = None
315 error_in_exec = None
315 error_in_exec = None
316 info = None
316 info = None
317 result = None
317 result = None
318
318
319 def __init__(self, info):
319 def __init__(self, info):
320 self.info = info
320 self.info = info
321
321
322 @property
322 @property
323 def success(self):
323 def success(self):
324 return (self.error_before_exec is None) and (self.error_in_exec is None)
324 return (self.error_before_exec is None) and (self.error_in_exec is None)
325
325
326 def raise_error(self):
326 def raise_error(self):
327 """Reraises error if `success` is `False`, otherwise does nothing"""
327 """Reraises error if `success` is `False`, otherwise does nothing"""
328 if self.error_before_exec is not None:
328 if self.error_before_exec is not None:
329 raise self.error_before_exec
329 raise self.error_before_exec
330 if self.error_in_exec is not None:
330 if self.error_in_exec is not None:
331 raise self.error_in_exec
331 raise self.error_in_exec
332
332
333 def __repr__(self):
333 def __repr__(self):
334 name = self.__class__.__qualname__
334 name = self.__class__.__qualname__
335 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s info=%s result=%s>' %\
335 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s info=%s result=%s>' %\
336 (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.info), repr(self.result))
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 class InteractiveShell(SingletonConfigurable):
339 class InteractiveShell(SingletonConfigurable):
340 """An enhanced, interactive shell for Python."""
340 """An enhanced, interactive shell for Python."""
341
341
342 _instance = None
342 _instance = None
343
343
344 ast_transformers = List([], help=
344 ast_transformers = List([], help=
345 """
345 """
346 A list of ast.NodeTransformer subclass instances, which will be applied
346 A list of ast.NodeTransformer subclass instances, which will be applied
347 to user input before code is run.
347 to user input before code is run.
348 """
348 """
349 ).tag(config=True)
349 ).tag(config=True)
350
350
351 autocall = Enum((0,1,2), default_value=0, help=
351 autocall = Enum((0,1,2), default_value=0, help=
352 """
352 """
353 Make IPython automatically call any callable object even if you didn't
353 Make IPython automatically call any callable object even if you didn't
354 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
354 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
355 automatically. The value can be '0' to disable the feature, '1' for
355 automatically. The value can be '0' to disable the feature, '1' for
356 'smart' autocall, where it is not applied if there are no more
356 'smart' autocall, where it is not applied if there are no more
357 arguments on the line, and '2' for 'full' autocall, where all callable
357 arguments on the line, and '2' for 'full' autocall, where all callable
358 objects are automatically called (even if no arguments are present).
358 objects are automatically called (even if no arguments are present).
359 """
359 """
360 ).tag(config=True)
360 ).tag(config=True)
361
361
362 autoindent = Bool(True, help=
362 autoindent = Bool(True, help=
363 """
363 """
364 Autoindent IPython code entered interactively.
364 Autoindent IPython code entered interactively.
365 """
365 """
366 ).tag(config=True)
366 ).tag(config=True)
367
367
368 autoawait = Bool(True, help=
368 autoawait = Bool(True, help=
369 """
369 """
370 Automatically run await statement in the top level repl.
370 Automatically run await statement in the top level repl.
371 """
371 """
372 ).tag(config=True)
372 ).tag(config=True)
373
373
374 loop_runner_map ={
374 loop_runner_map ={
375 'asyncio':(_asyncio_runner, True),
375 'asyncio':(_asyncio_runner, True),
376 'curio':(_curio_runner, True),
376 'curio':(_curio_runner, True),
377 'trio':(_trio_runner, True),
377 'trio':(_trio_runner, True),
378 'sync': (_pseudo_sync_runner, False)
378 'sync': (_pseudo_sync_runner, False)
379 }
379 }
380
380
381 loop_runner = Any(default_value="IPython.core.interactiveshell._asyncio_runner",
381 loop_runner = Any(default_value="IPython.core.interactiveshell._asyncio_runner",
382 allow_none=True,
382 allow_none=True,
383 help="""Select the loop runner that will be used to execute top-level asynchronous code"""
383 help="""Select the loop runner that will be used to execute top-level asynchronous code"""
384 ).tag(config=True)
384 ).tag(config=True)
385
385
386 @default('loop_runner')
386 @default('loop_runner')
387 def _default_loop_runner(self):
387 def _default_loop_runner(self):
388 return import_item("IPython.core.interactiveshell._asyncio_runner")
388 return import_item("IPython.core.interactiveshell._asyncio_runner")
389
389
390 @validate('loop_runner')
390 @validate('loop_runner')
391 def _import_runner(self, proposal):
391 def _import_runner(self, proposal):
392 if isinstance(proposal.value, str):
392 if isinstance(proposal.value, str):
393 if proposal.value in self.loop_runner_map:
393 if proposal.value in self.loop_runner_map:
394 runner, autoawait = self.loop_runner_map[proposal.value]
394 runner, autoawait = self.loop_runner_map[proposal.value]
395 self.autoawait = autoawait
395 self.autoawait = autoawait
396 return runner
396 return runner
397 runner = import_item(proposal.value)
397 runner = import_item(proposal.value)
398 if not callable(runner):
398 if not callable(runner):
399 raise ValueError('loop_runner must be callable')
399 raise ValueError('loop_runner must be callable')
400 return runner
400 return runner
401 if not callable(proposal.value):
401 if not callable(proposal.value):
402 raise ValueError('loop_runner must be callable')
402 raise ValueError('loop_runner must be callable')
403 return proposal.value
403 return proposal.value
404
404
405 automagic = Bool(True, help=
405 automagic = Bool(True, help=
406 """
406 """
407 Enable magic commands to be called without the leading %.
407 Enable magic commands to be called without the leading %.
408 """
408 """
409 ).tag(config=True)
409 ).tag(config=True)
410
410
411 banner1 = Unicode(default_banner,
411 banner1 = Unicode(default_banner,
412 help="""The part of the banner to be printed before the profile"""
412 help="""The part of the banner to be printed before the profile"""
413 ).tag(config=True)
413 ).tag(config=True)
414 banner2 = Unicode('',
414 banner2 = Unicode('',
415 help="""The part of the banner to be printed after the profile"""
415 help="""The part of the banner to be printed after the profile"""
416 ).tag(config=True)
416 ).tag(config=True)
417
417
418 cache_size = Integer(1000, help=
418 cache_size = Integer(1000, help=
419 """
419 """
420 Set the size of the output cache. The default is 1000, you can
420 Set the size of the output cache. The default is 1000, you can
421 change it permanently in your config file. Setting it to 0 completely
421 change it permanently in your config file. Setting it to 0 completely
422 disables the caching system, and the minimum value accepted is 3 (if
422 disables the caching system, and the minimum value accepted is 3 (if
423 you provide a value less than 3, it is reset to 0 and a warning is
423 you provide a value less than 3, it is reset to 0 and a warning is
424 issued). This limit is defined because otherwise you'll spend more
424 issued). This limit is defined because otherwise you'll spend more
425 time re-flushing a too small cache than working
425 time re-flushing a too small cache than working
426 """
426 """
427 ).tag(config=True)
427 ).tag(config=True)
428 color_info = Bool(True, help=
428 color_info = Bool(True, help=
429 """
429 """
430 Use colors for displaying information about objects. Because this
430 Use colors for displaying information about objects. Because this
431 information is passed through a pager (like 'less'), and some pagers
431 information is passed through a pager (like 'less'), and some pagers
432 get confused with color codes, this capability can be turned off.
432 get confused with color codes, this capability can be turned off.
433 """
433 """
434 ).tag(config=True)
434 ).tag(config=True)
435 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
435 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
436 default_value='Neutral',
436 default_value='Neutral',
437 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
437 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
438 ).tag(config=True)
438 ).tag(config=True)
439 debug = Bool(False).tag(config=True)
439 debug = Bool(False).tag(config=True)
440 disable_failing_post_execute = Bool(False,
440 disable_failing_post_execute = Bool(False,
441 help="Don't call post-execute functions that have failed in the past."
441 help="Don't call post-execute functions that have failed in the past."
442 ).tag(config=True)
442 ).tag(config=True)
443 display_formatter = Instance(DisplayFormatter, allow_none=True)
443 display_formatter = Instance(DisplayFormatter, allow_none=True)
444 displayhook_class = Type(DisplayHook)
444 displayhook_class = Type(DisplayHook)
445 display_pub_class = Type(DisplayPublisher)
445 display_pub_class = Type(DisplayPublisher)
446
446
447 sphinxify_docstring = Bool(False, help=
447 sphinxify_docstring = Bool(False, help=
448 """
448 """
449 Enables rich html representation of docstrings. (This requires the
449 Enables rich html representation of docstrings. (This requires the
450 docrepr module).
450 docrepr module).
451 """).tag(config=True)
451 """).tag(config=True)
452
452
453 @observe("sphinxify_docstring")
453 @observe("sphinxify_docstring")
454 def _sphinxify_docstring_changed(self, change):
454 def _sphinxify_docstring_changed(self, change):
455 if change['new']:
455 if change['new']:
456 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
456 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
457
457
458 enable_html_pager = Bool(False, help=
458 enable_html_pager = Bool(False, help=
459 """
459 """
460 (Provisional API) enables html representation in mime bundles sent
460 (Provisional API) enables html representation in mime bundles sent
461 to pagers.
461 to pagers.
462 """).tag(config=True)
462 """).tag(config=True)
463
463
464 @observe("enable_html_pager")
464 @observe("enable_html_pager")
465 def _enable_html_pager_changed(self, change):
465 def _enable_html_pager_changed(self, change):
466 if change['new']:
466 if change['new']:
467 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
467 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
468
468
469 data_pub_class = None
469 data_pub_class = None
470
470
471 exit_now = Bool(False)
471 exit_now = Bool(False)
472 exiter = Instance(ExitAutocall)
472 exiter = Instance(ExitAutocall)
473 @default('exiter')
473 @default('exiter')
474 def _exiter_default(self):
474 def _exiter_default(self):
475 return ExitAutocall(self)
475 return ExitAutocall(self)
476 # Monotonically increasing execution counter
476 # Monotonically increasing execution counter
477 execution_count = Integer(1)
477 execution_count = Integer(1)
478 filename = Unicode("<ipython console>")
478 filename = Unicode("<ipython console>")
479 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
479 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
480
480
481 # Used to transform cells before running them, and check whether code is complete
481 # Used to transform cells before running them, and check whether code is complete
482 input_transformer_manager = Instance('IPython.core.inputtransformer2.TransformerManager',
482 input_transformer_manager = Instance('IPython.core.inputtransformer2.TransformerManager',
483 ())
483 ())
484
484
485 @property
485 @property
486 def input_transformers_cleanup(self):
486 def input_transformers_cleanup(self):
487 return self.input_transformer_manager.cleanup_transforms
487 return self.input_transformer_manager.cleanup_transforms
488
488
489 input_transformers_post = List([],
489 input_transformers_post = List([],
490 help="A list of string input transformers, to be applied after IPython's "
490 help="A list of string input transformers, to be applied after IPython's "
491 "own input transformations."
491 "own input transformations."
492 )
492 )
493
493
494 @property
494 @property
495 def input_splitter(self):
495 def input_splitter(self):
496 """Make this available for backward compatibility (pre-7.0 release) with existing code.
496 """Make this available for backward compatibility (pre-7.0 release) with existing code.
497
497
498 For example, ipykernel ipykernel currently uses
498 For example, ipykernel ipykernel currently uses
499 `shell.input_splitter.check_complete`
499 `shell.input_splitter.check_complete`
500 """
500 """
501 from warnings import warn
501 from warnings import warn
502 warn("`input_splitter` is deprecated since IPython 7.0, prefer `input_transformer_manager`.",
502 warn("`input_splitter` is deprecated since IPython 7.0, prefer `input_transformer_manager`.",
503 DeprecationWarning, stacklevel=2
503 DeprecationWarning, stacklevel=2
504 )
504 )
505 return self.input_transformer_manager
505 return self.input_transformer_manager
506
506
507 logstart = Bool(False, help=
507 logstart = Bool(False, help=
508 """
508 """
509 Start logging to the default log file in overwrite mode.
509 Start logging to the default log file in overwrite mode.
510 Use `logappend` to specify a log file to **append** logs to.
510 Use `logappend` to specify a log file to **append** logs to.
511 """
511 """
512 ).tag(config=True)
512 ).tag(config=True)
513 logfile = Unicode('', help=
513 logfile = Unicode('', help=
514 """
514 """
515 The name of the logfile to use.
515 The name of the logfile to use.
516 """
516 """
517 ).tag(config=True)
517 ).tag(config=True)
518 logappend = Unicode('', help=
518 logappend = Unicode('', help=
519 """
519 """
520 Start logging to the given file in append mode.
520 Start logging to the given file in append mode.
521 Use `logfile` to specify a log file to **overwrite** logs to.
521 Use `logfile` to specify a log file to **overwrite** logs to.
522 """
522 """
523 ).tag(config=True)
523 ).tag(config=True)
524 object_info_string_level = Enum((0,1,2), default_value=0,
524 object_info_string_level = Enum((0,1,2), default_value=0,
525 ).tag(config=True)
525 ).tag(config=True)
526 pdb = Bool(False, help=
526 pdb = Bool(False, help=
527 """
527 """
528 Automatically call the pdb debugger after every exception.
528 Automatically call the pdb debugger after every exception.
529 """
529 """
530 ).tag(config=True)
530 ).tag(config=True)
531 display_page = Bool(False,
531 display_page = Bool(False,
532 help="""If True, anything that would be passed to the pager
532 help="""If True, anything that would be passed to the pager
533 will be displayed as regular output instead."""
533 will be displayed as regular output instead."""
534 ).tag(config=True)
534 ).tag(config=True)
535
535
536 # deprecated prompt traits:
536 # deprecated prompt traits:
537
537
538 prompt_in1 = Unicode('In [\\#]: ',
538 prompt_in1 = Unicode('In [\\#]: ',
539 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
539 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
540 ).tag(config=True)
540 ).tag(config=True)
541 prompt_in2 = Unicode(' .\\D.: ',
541 prompt_in2 = Unicode(' .\\D.: ',
542 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
542 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
543 ).tag(config=True)
543 ).tag(config=True)
544 prompt_out = Unicode('Out[\\#]: ',
544 prompt_out = Unicode('Out[\\#]: ',
545 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
545 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
546 ).tag(config=True)
546 ).tag(config=True)
547 prompts_pad_left = Bool(True,
547 prompts_pad_left = Bool(True,
548 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
548 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
549 ).tag(config=True)
549 ).tag(config=True)
550
550
551 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
551 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
552 def _prompt_trait_changed(self, change):
552 def _prompt_trait_changed(self, change):
553 name = change['name']
553 name = change['name']
554 warn("InteractiveShell.{name} is deprecated since IPython 4.0"
554 warn("InteractiveShell.{name} is deprecated since IPython 4.0"
555 " and ignored since 5.0, set TerminalInteractiveShell.prompts"
555 " and ignored since 5.0, set TerminalInteractiveShell.prompts"
556 " object directly.".format(name=name))
556 " object directly.".format(name=name))
557
557
558 # protect against weird cases where self.config may not exist:
558 # protect against weird cases where self.config may not exist:
559
559
560 show_rewritten_input = Bool(True,
560 show_rewritten_input = Bool(True,
561 help="Show rewritten input, e.g. for autocall."
561 help="Show rewritten input, e.g. for autocall."
562 ).tag(config=True)
562 ).tag(config=True)
563
563
564 quiet = Bool(False).tag(config=True)
564 quiet = Bool(False).tag(config=True)
565
565
566 history_length = Integer(10000,
566 history_length = Integer(10000,
567 help='Total length of command history'
567 help='Total length of command history'
568 ).tag(config=True)
568 ).tag(config=True)
569
569
570 history_load_length = Integer(1000, help=
570 history_load_length = Integer(1000, help=
571 """
571 """
572 The number of saved history entries to be loaded
572 The number of saved history entries to be loaded
573 into the history buffer at startup.
573 into the history buffer at startup.
574 """
574 """
575 ).tag(config=True)
575 ).tag(config=True)
576
576
577 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none', 'last_expr_or_assign'],
577 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none', 'last_expr_or_assign'],
578 default_value='last_expr',
578 default_value='last_expr',
579 help="""
579 help="""
580 'all', 'last', 'last_expr' or 'none', 'last_expr_or_assign' specifying
580 'all', 'last', 'last_expr' or 'none', 'last_expr_or_assign' specifying
581 which nodes should be run interactively (displaying output from expressions).
581 which nodes should be run interactively (displaying output from expressions).
582 """
582 """
583 ).tag(config=True)
583 ).tag(config=True)
584
584
585 # TODO: this part of prompt management should be moved to the frontends.
585 # TODO: this part of prompt management should be moved to the frontends.
586 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
586 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
587 separate_in = SeparateUnicode('\n').tag(config=True)
587 separate_in = SeparateUnicode('\n').tag(config=True)
588 separate_out = SeparateUnicode('').tag(config=True)
588 separate_out = SeparateUnicode('').tag(config=True)
589 separate_out2 = SeparateUnicode('').tag(config=True)
589 separate_out2 = SeparateUnicode('').tag(config=True)
590 wildcards_case_sensitive = Bool(True).tag(config=True)
590 wildcards_case_sensitive = Bool(True).tag(config=True)
591 xmode = CaselessStrEnum(('Context', 'Plain', 'Verbose', 'Minimal'),
591 xmode = CaselessStrEnum(('Context', 'Plain', 'Verbose', 'Minimal'),
592 default_value='Context',
592 default_value='Context',
593 help="Switch modes for the IPython exception handlers."
593 help="Switch modes for the IPython exception handlers."
594 ).tag(config=True)
594 ).tag(config=True)
595
595
596 # Subcomponents of InteractiveShell
596 # Subcomponents of InteractiveShell
597 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
597 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
598 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
598 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
599 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
599 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
600 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
600 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
601 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
601 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
602 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
602 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
603 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
603 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
604 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
604 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
605
605
606 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
606 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
607 @property
607 @property
608 def profile(self):
608 def profile(self):
609 if self.profile_dir is not None:
609 if self.profile_dir is not None:
610 name = os.path.basename(self.profile_dir.location)
610 name = os.path.basename(self.profile_dir.location)
611 return name.replace('profile_','')
611 return name.replace('profile_','')
612
612
613
613
614 # Private interface
614 # Private interface
615 _post_execute = Dict()
615 _post_execute = Dict()
616
616
617 # Tracks any GUI loop loaded for pylab
617 # Tracks any GUI loop loaded for pylab
618 pylab_gui_select = None
618 pylab_gui_select = None
619
619
620 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
620 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
621
621
622 last_execution_result = Instance('IPython.core.interactiveshell.ExecutionResult', help='Result of executing the last command', allow_none=True)
622 last_execution_result = Instance('IPython.core.interactiveshell.ExecutionResult', help='Result of executing the last command', allow_none=True)
623
623
624 def __init__(self, ipython_dir=None, profile_dir=None,
624 def __init__(self, ipython_dir=None, profile_dir=None,
625 user_module=None, user_ns=None,
625 user_module=None, user_ns=None,
626 custom_exceptions=((), None), **kwargs):
626 custom_exceptions=((), None), **kwargs):
627
627
628 # This is where traits with a config_key argument are updated
628 # This is where traits with a config_key argument are updated
629 # from the values on config.
629 # from the values on config.
630 super(InteractiveShell, self).__init__(**kwargs)
630 super(InteractiveShell, self).__init__(**kwargs)
631 if 'PromptManager' in self.config:
631 if 'PromptManager' in self.config:
632 warn('As of IPython 5.0 `PromptManager` config will have no effect'
632 warn('As of IPython 5.0 `PromptManager` config will have no effect'
633 ' and has been replaced by TerminalInteractiveShell.prompts_class')
633 ' and has been replaced by TerminalInteractiveShell.prompts_class')
634 self.configurables = [self]
634 self.configurables = [self]
635
635
636 # These are relatively independent and stateless
636 # These are relatively independent and stateless
637 self.init_ipython_dir(ipython_dir)
637 self.init_ipython_dir(ipython_dir)
638 self.init_profile_dir(profile_dir)
638 self.init_profile_dir(profile_dir)
639 self.init_instance_attrs()
639 self.init_instance_attrs()
640 self.init_environment()
640 self.init_environment()
641
641
642 # Check if we're in a virtualenv, and set up sys.path.
642 # Check if we're in a virtualenv, and set up sys.path.
643 self.init_virtualenv()
643 self.init_virtualenv()
644
644
645 # Create namespaces (user_ns, user_global_ns, etc.)
645 # Create namespaces (user_ns, user_global_ns, etc.)
646 self.init_create_namespaces(user_module, user_ns)
646 self.init_create_namespaces(user_module, user_ns)
647 # This has to be done after init_create_namespaces because it uses
647 # This has to be done after init_create_namespaces because it uses
648 # something in self.user_ns, but before init_sys_modules, which
648 # something in self.user_ns, but before init_sys_modules, which
649 # is the first thing to modify sys.
649 # is the first thing to modify sys.
650 # TODO: When we override sys.stdout and sys.stderr before this class
650 # TODO: When we override sys.stdout and sys.stderr before this class
651 # is created, we are saving the overridden ones here. Not sure if this
651 # is created, we are saving the overridden ones here. Not sure if this
652 # is what we want to do.
652 # is what we want to do.
653 self.save_sys_module_state()
653 self.save_sys_module_state()
654 self.init_sys_modules()
654 self.init_sys_modules()
655
655
656 # While we're trying to have each part of the code directly access what
656 # While we're trying to have each part of the code directly access what
657 # it needs without keeping redundant references to objects, we have too
657 # it needs without keeping redundant references to objects, we have too
658 # much legacy code that expects ip.db to exist.
658 # much legacy code that expects ip.db to exist.
659 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
659 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
660
660
661 self.init_history()
661 self.init_history()
662 self.init_encoding()
662 self.init_encoding()
663 self.init_prefilter()
663 self.init_prefilter()
664
664
665 self.init_syntax_highlighting()
665 self.init_syntax_highlighting()
666 self.init_hooks()
666 self.init_hooks()
667 self.init_events()
667 self.init_events()
668 self.init_pushd_popd_magic()
668 self.init_pushd_popd_magic()
669 self.init_user_ns()
669 self.init_user_ns()
670 self.init_logger()
670 self.init_logger()
671 self.init_builtins()
671 self.init_builtins()
672
672
673 # The following was in post_config_initialization
673 # The following was in post_config_initialization
674 self.init_inspector()
674 self.init_inspector()
675 self.raw_input_original = input
675 self.raw_input_original = input
676 self.init_completer()
676 self.init_completer()
677 # TODO: init_io() needs to happen before init_traceback handlers
677 # TODO: init_io() needs to happen before init_traceback handlers
678 # because the traceback handlers hardcode the stdout/stderr streams.
678 # because the traceback handlers hardcode the stdout/stderr streams.
679 # This logic in in debugger.Pdb and should eventually be changed.
679 # This logic in in debugger.Pdb and should eventually be changed.
680 self.init_io()
680 self.init_io()
681 self.init_traceback_handlers(custom_exceptions)
681 self.init_traceback_handlers(custom_exceptions)
682 self.init_prompts()
682 self.init_prompts()
683 self.init_display_formatter()
683 self.init_display_formatter()
684 self.init_display_pub()
684 self.init_display_pub()
685 self.init_data_pub()
685 self.init_data_pub()
686 self.init_displayhook()
686 self.init_displayhook()
687 self.init_magics()
687 self.init_magics()
688 self.init_alias()
688 self.init_alias()
689 self.init_logstart()
689 self.init_logstart()
690 self.init_pdb()
690 self.init_pdb()
691 self.init_extension_manager()
691 self.init_extension_manager()
692 self.init_payload()
692 self.init_payload()
693 self.init_deprecation_warnings()
693 self.init_deprecation_warnings()
694 self.hooks.late_startup_hook()
694 self.hooks.late_startup_hook()
695 self.events.trigger('shell_initialized', self)
695 self.events.trigger('shell_initialized', self)
696 atexit.register(self.atexit_operations)
696 atexit.register(self.atexit_operations)
697
697
698 def get_ipython(self):
698 def get_ipython(self):
699 """Return the currently running IPython instance."""
699 """Return the currently running IPython instance."""
700 return self
700 return self
701
701
702 #-------------------------------------------------------------------------
702 #-------------------------------------------------------------------------
703 # Trait changed handlers
703 # Trait changed handlers
704 #-------------------------------------------------------------------------
704 #-------------------------------------------------------------------------
705 @observe('ipython_dir')
705 @observe('ipython_dir')
706 def _ipython_dir_changed(self, change):
706 def _ipython_dir_changed(self, change):
707 ensure_dir_exists(change['new'])
707 ensure_dir_exists(change['new'])
708
708
709 def set_autoindent(self,value=None):
709 def set_autoindent(self,value=None):
710 """Set the autoindent flag.
710 """Set the autoindent flag.
711
711
712 If called with no arguments, it acts as a toggle."""
712 If called with no arguments, it acts as a toggle."""
713 if value is None:
713 if value is None:
714 self.autoindent = not self.autoindent
714 self.autoindent = not self.autoindent
715 else:
715 else:
716 self.autoindent = value
716 self.autoindent = value
717
717
718 #-------------------------------------------------------------------------
718 #-------------------------------------------------------------------------
719 # init_* methods called by __init__
719 # init_* methods called by __init__
720 #-------------------------------------------------------------------------
720 #-------------------------------------------------------------------------
721
721
722 def init_ipython_dir(self, ipython_dir):
722 def init_ipython_dir(self, ipython_dir):
723 if ipython_dir is not None:
723 if ipython_dir is not None:
724 self.ipython_dir = ipython_dir
724 self.ipython_dir = ipython_dir
725 return
725 return
726
726
727 self.ipython_dir = get_ipython_dir()
727 self.ipython_dir = get_ipython_dir()
728
728
729 def init_profile_dir(self, profile_dir):
729 def init_profile_dir(self, profile_dir):
730 if profile_dir is not None:
730 if profile_dir is not None:
731 self.profile_dir = profile_dir
731 self.profile_dir = profile_dir
732 return
732 return
733 self.profile_dir =\
733 self.profile_dir =\
734 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
734 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
735
735
736 def init_instance_attrs(self):
736 def init_instance_attrs(self):
737 self.more = False
737 self.more = False
738
738
739 # command compiler
739 # command compiler
740 self.compile = CachingCompiler()
740 self.compile = CachingCompiler()
741
741
742 # Make an empty namespace, which extension writers can rely on both
742 # Make an empty namespace, which extension writers can rely on both
743 # existing and NEVER being used by ipython itself. This gives them a
743 # existing and NEVER being used by ipython itself. This gives them a
744 # convenient location for storing additional information and state
744 # convenient location for storing additional information and state
745 # their extensions may require, without fear of collisions with other
745 # their extensions may require, without fear of collisions with other
746 # ipython names that may develop later.
746 # ipython names that may develop later.
747 self.meta = Struct()
747 self.meta = Struct()
748
748
749 # Temporary files used for various purposes. Deleted at exit.
749 # Temporary files used for various purposes. Deleted at exit.
750 self.tempfiles = []
750 self.tempfiles = []
751 self.tempdirs = []
751 self.tempdirs = []
752
752
753 # keep track of where we started running (mainly for crash post-mortem)
753 # keep track of where we started running (mainly for crash post-mortem)
754 # This is not being used anywhere currently.
754 # This is not being used anywhere currently.
755 self.starting_dir = os.getcwd()
755 self.starting_dir = os.getcwd()
756
756
757 # Indentation management
757 # Indentation management
758 self.indent_current_nsp = 0
758 self.indent_current_nsp = 0
759
759
760 # Dict to track post-execution functions that have been registered
760 # Dict to track post-execution functions that have been registered
761 self._post_execute = {}
761 self._post_execute = {}
762
762
763 def init_environment(self):
763 def init_environment(self):
764 """Any changes we need to make to the user's environment."""
764 """Any changes we need to make to the user's environment."""
765 pass
765 pass
766
766
767 def init_encoding(self):
767 def init_encoding(self):
768 # Get system encoding at startup time. Certain terminals (like Emacs
768 # Get system encoding at startup time. Certain terminals (like Emacs
769 # under Win32 have it set to None, and we need to have a known valid
769 # under Win32 have it set to None, and we need to have a known valid
770 # encoding to use in the raw_input() method
770 # encoding to use in the raw_input() method
771 try:
771 try:
772 self.stdin_encoding = sys.stdin.encoding or 'ascii'
772 self.stdin_encoding = sys.stdin.encoding or 'ascii'
773 except AttributeError:
773 except AttributeError:
774 self.stdin_encoding = 'ascii'
774 self.stdin_encoding = 'ascii'
775
775
776
776
777 @observe('colors')
777 @observe('colors')
778 def init_syntax_highlighting(self, changes=None):
778 def init_syntax_highlighting(self, changes=None):
779 # Python source parser/formatter for syntax highlighting
779 # Python source parser/formatter for syntax highlighting
780 pyformat = PyColorize.Parser(style=self.colors, parent=self).format
780 pyformat = PyColorize.Parser(style=self.colors, parent=self).format
781 self.pycolorize = lambda src: pyformat(src,'str')
781 self.pycolorize = lambda src: pyformat(src,'str')
782
782
783 def refresh_style(self):
783 def refresh_style(self):
784 # No-op here, used in subclass
784 # No-op here, used in subclass
785 pass
785 pass
786
786
787 def init_pushd_popd_magic(self):
787 def init_pushd_popd_magic(self):
788 # for pushd/popd management
788 # for pushd/popd management
789 self.home_dir = get_home_dir()
789 self.home_dir = get_home_dir()
790
790
791 self.dir_stack = []
791 self.dir_stack = []
792
792
793 def init_logger(self):
793 def init_logger(self):
794 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
794 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
795 logmode='rotate')
795 logmode='rotate')
796
796
797 def init_logstart(self):
797 def init_logstart(self):
798 """Initialize logging in case it was requested at the command line.
798 """Initialize logging in case it was requested at the command line.
799 """
799 """
800 if self.logappend:
800 if self.logappend:
801 self.magic('logstart %s append' % self.logappend)
801 self.magic('logstart %s append' % self.logappend)
802 elif self.logfile:
802 elif self.logfile:
803 self.magic('logstart %s' % self.logfile)
803 self.magic('logstart %s' % self.logfile)
804 elif self.logstart:
804 elif self.logstart:
805 self.magic('logstart')
805 self.magic('logstart')
806
806
807 def init_deprecation_warnings(self):
807 def init_deprecation_warnings(self):
808 """
808 """
809 register default filter for deprecation warning.
809 register default filter for deprecation warning.
810
810
811 This will allow deprecation warning of function used interactively to show
811 This will allow deprecation warning of function used interactively to show
812 warning to users, and still hide deprecation warning from libraries import.
812 warning to users, and still hide deprecation warning from libraries import.
813 """
813 """
814 if sys.version_info < (3,7):
814 if sys.version_info < (3,7):
815 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
815 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
816
816
817
817
818 def init_builtins(self):
818 def init_builtins(self):
819 # A single, static flag that we set to True. Its presence indicates
819 # A single, static flag that we set to True. Its presence indicates
820 # that an IPython shell has been created, and we make no attempts at
820 # that an IPython shell has been created, and we make no attempts at
821 # removing on exit or representing the existence of more than one
821 # removing on exit or representing the existence of more than one
822 # IPython at a time.
822 # IPython at a time.
823 builtin_mod.__dict__['__IPYTHON__'] = True
823 builtin_mod.__dict__['__IPYTHON__'] = True
824 builtin_mod.__dict__['display'] = display
824 builtin_mod.__dict__['display'] = display
825
825
826 self.builtin_trap = BuiltinTrap(shell=self)
826 self.builtin_trap = BuiltinTrap(shell=self)
827
827
828 @observe('colors')
828 @observe('colors')
829 def init_inspector(self, changes=None):
829 def init_inspector(self, changes=None):
830 # Object inspector
830 # Object inspector
831 self.inspector = oinspect.Inspector(oinspect.InspectColors,
831 self.inspector = oinspect.Inspector(oinspect.InspectColors,
832 PyColorize.ANSICodeColors,
832 PyColorize.ANSICodeColors,
833 self.colors,
833 self.colors,
834 self.object_info_string_level)
834 self.object_info_string_level)
835
835
836 def init_io(self):
836 def init_io(self):
837 # This will just use sys.stdout and sys.stderr. If you want to
837 # This will just use sys.stdout and sys.stderr. If you want to
838 # override sys.stdout and sys.stderr themselves, you need to do that
838 # override sys.stdout and sys.stderr themselves, you need to do that
839 # *before* instantiating this class, because io holds onto
839 # *before* instantiating this class, because io holds onto
840 # references to the underlying streams.
840 # references to the underlying streams.
841 # io.std* are deprecated, but don't show our own deprecation warnings
841 # io.std* are deprecated, but don't show our own deprecation warnings
842 # during initialization of the deprecated API.
842 # during initialization of the deprecated API.
843 with warnings.catch_warnings():
843 with warnings.catch_warnings():
844 warnings.simplefilter('ignore', DeprecationWarning)
844 warnings.simplefilter('ignore', DeprecationWarning)
845 io.stdout = io.IOStream(sys.stdout)
845 io.stdout = io.IOStream(sys.stdout)
846 io.stderr = io.IOStream(sys.stderr)
846 io.stderr = io.IOStream(sys.stderr)
847
847
848 def init_prompts(self):
848 def init_prompts(self):
849 # Set system prompts, so that scripts can decide if they are running
849 # Set system prompts, so that scripts can decide if they are running
850 # interactively.
850 # interactively.
851 sys.ps1 = 'In : '
851 sys.ps1 = 'In : '
852 sys.ps2 = '...: '
852 sys.ps2 = '...: '
853 sys.ps3 = 'Out: '
853 sys.ps3 = 'Out: '
854
854
855 def init_display_formatter(self):
855 def init_display_formatter(self):
856 self.display_formatter = DisplayFormatter(parent=self)
856 self.display_formatter = DisplayFormatter(parent=self)
857 self.configurables.append(self.display_formatter)
857 self.configurables.append(self.display_formatter)
858
858
859 def init_display_pub(self):
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 self.configurables.append(self.display_pub)
861 self.configurables.append(self.display_pub)
862
862
863 def init_data_pub(self):
863 def init_data_pub(self):
864 if not self.data_pub_class:
864 if not self.data_pub_class:
865 self.data_pub = None
865 self.data_pub = None
866 return
866 return
867 self.data_pub = self.data_pub_class(parent=self)
867 self.data_pub = self.data_pub_class(parent=self)
868 self.configurables.append(self.data_pub)
868 self.configurables.append(self.data_pub)
869
869
870 def init_displayhook(self):
870 def init_displayhook(self):
871 # Initialize displayhook, set in/out prompts and printing system
871 # Initialize displayhook, set in/out prompts and printing system
872 self.displayhook = self.displayhook_class(
872 self.displayhook = self.displayhook_class(
873 parent=self,
873 parent=self,
874 shell=self,
874 shell=self,
875 cache_size=self.cache_size,
875 cache_size=self.cache_size,
876 )
876 )
877 self.configurables.append(self.displayhook)
877 self.configurables.append(self.displayhook)
878 # This is a context manager that installs/revmoes the displayhook at
878 # This is a context manager that installs/revmoes the displayhook at
879 # the appropriate time.
879 # the appropriate time.
880 self.display_trap = DisplayTrap(hook=self.displayhook)
880 self.display_trap = DisplayTrap(hook=self.displayhook)
881
881
882 def init_virtualenv(self):
882 def init_virtualenv(self):
883 """Add a virtualenv to sys.path so the user can import modules from it.
883 """Add a virtualenv to sys.path so the user can import modules from it.
884 This isn't perfect: it doesn't use the Python interpreter with which the
884 This isn't perfect: it doesn't use the Python interpreter with which the
885 virtualenv was built, and it ignores the --no-site-packages option. A
885 virtualenv was built, and it ignores the --no-site-packages option. A
886 warning will appear suggesting the user installs IPython in the
886 warning will appear suggesting the user installs IPython in the
887 virtualenv, but for many cases, it probably works well enough.
887 virtualenv, but for many cases, it probably works well enough.
888
888
889 Adapted from code snippets online.
889 Adapted from code snippets online.
890
890
891 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
891 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
892 """
892 """
893 if 'VIRTUAL_ENV' not in os.environ:
893 if 'VIRTUAL_ENV' not in os.environ:
894 # Not in a virtualenv
894 # Not in a virtualenv
895 return
895 return
896
896
897 p = os.path.normcase(sys.executable)
897 p = os.path.normcase(sys.executable)
898 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
898 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
899
899
900 # executable path should end like /bin/python or \\scripts\\python.exe
900 # executable path should end like /bin/python or \\scripts\\python.exe
901 p_exe_up2 = os.path.dirname(os.path.dirname(p))
901 p_exe_up2 = os.path.dirname(os.path.dirname(p))
902 if p_exe_up2 and os.path.exists(p_venv) and os.path.samefile(p_exe_up2, p_venv):
902 if p_exe_up2 and os.path.exists(p_venv) and os.path.samefile(p_exe_up2, p_venv):
903 # Our exe is inside the virtualenv, don't need to do anything.
903 # Our exe is inside the virtualenv, don't need to do anything.
904 return
904 return
905
905
906 # fallback venv detection:
906 # fallback venv detection:
907 # stdlib venv may symlink sys.executable, so we can't use realpath.
907 # stdlib venv may symlink sys.executable, so we can't use realpath.
908 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
908 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
909 # So we just check every item in the symlink tree (generally <= 3)
909 # So we just check every item in the symlink tree (generally <= 3)
910 paths = [p]
910 paths = [p]
911 while os.path.islink(p):
911 while os.path.islink(p):
912 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
912 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
913 paths.append(p)
913 paths.append(p)
914
914
915 # In Cygwin paths like "c:\..." and '\cygdrive\c\...' are possible
915 # In Cygwin paths like "c:\..." and '\cygdrive\c\...' are possible
916 if p_venv.startswith('\\cygdrive'):
916 if p_venv.startswith('\\cygdrive'):
917 p_venv = p_venv[11:]
917 p_venv = p_venv[11:]
918 elif len(p_venv) >= 2 and p_venv[1] == ':':
918 elif len(p_venv) >= 2 and p_venv[1] == ':':
919 p_venv = p_venv[2:]
919 p_venv = p_venv[2:]
920
920
921 if any(p_venv in p for p in paths):
921 if any(p_venv in p for p in paths):
922 # Running properly in the virtualenv, don't need to do anything
922 # Running properly in the virtualenv, don't need to do anything
923 return
923 return
924
924
925 warn("Attempting to work in a virtualenv. If you encounter problems, please "
925 warn("Attempting to work in a virtualenv. If you encounter problems, please "
926 "install IPython inside the virtualenv.")
926 "install IPython inside the virtualenv.")
927 if sys.platform == "win32":
927 if sys.platform == "win32":
928 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
928 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
929 else:
929 else:
930 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
930 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
931 'python%d.%d' % sys.version_info[:2], 'site-packages')
931 'python%d.%d' % sys.version_info[:2], 'site-packages')
932
932
933 import site
933 import site
934 sys.path.insert(0, virtual_env)
934 sys.path.insert(0, virtual_env)
935 site.addsitedir(virtual_env)
935 site.addsitedir(virtual_env)
936
936
937 #-------------------------------------------------------------------------
937 #-------------------------------------------------------------------------
938 # Things related to injections into the sys module
938 # Things related to injections into the sys module
939 #-------------------------------------------------------------------------
939 #-------------------------------------------------------------------------
940
940
941 def save_sys_module_state(self):
941 def save_sys_module_state(self):
942 """Save the state of hooks in the sys module.
942 """Save the state of hooks in the sys module.
943
943
944 This has to be called after self.user_module is created.
944 This has to be called after self.user_module is created.
945 """
945 """
946 self._orig_sys_module_state = {'stdin': sys.stdin,
946 self._orig_sys_module_state = {'stdin': sys.stdin,
947 'stdout': sys.stdout,
947 'stdout': sys.stdout,
948 'stderr': sys.stderr,
948 'stderr': sys.stderr,
949 'excepthook': sys.excepthook}
949 'excepthook': sys.excepthook}
950 self._orig_sys_modules_main_name = self.user_module.__name__
950 self._orig_sys_modules_main_name = self.user_module.__name__
951 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
951 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
952
952
953 def restore_sys_module_state(self):
953 def restore_sys_module_state(self):
954 """Restore the state of the sys module."""
954 """Restore the state of the sys module."""
955 try:
955 try:
956 for k, v in self._orig_sys_module_state.items():
956 for k, v in self._orig_sys_module_state.items():
957 setattr(sys, k, v)
957 setattr(sys, k, v)
958 except AttributeError:
958 except AttributeError:
959 pass
959 pass
960 # Reset what what done in self.init_sys_modules
960 # Reset what what done in self.init_sys_modules
961 if self._orig_sys_modules_main_mod is not None:
961 if self._orig_sys_modules_main_mod is not None:
962 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
962 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
963
963
964 #-------------------------------------------------------------------------
964 #-------------------------------------------------------------------------
965 # Things related to the banner
965 # Things related to the banner
966 #-------------------------------------------------------------------------
966 #-------------------------------------------------------------------------
967
967
968 @property
968 @property
969 def banner(self):
969 def banner(self):
970 banner = self.banner1
970 banner = self.banner1
971 if self.profile and self.profile != 'default':
971 if self.profile and self.profile != 'default':
972 banner += '\nIPython profile: %s\n' % self.profile
972 banner += '\nIPython profile: %s\n' % self.profile
973 if self.banner2:
973 if self.banner2:
974 banner += '\n' + self.banner2
974 banner += '\n' + self.banner2
975 return banner
975 return banner
976
976
977 def show_banner(self, banner=None):
977 def show_banner(self, banner=None):
978 if banner is None:
978 if banner is None:
979 banner = self.banner
979 banner = self.banner
980 sys.stdout.write(banner)
980 sys.stdout.write(banner)
981
981
982 #-------------------------------------------------------------------------
982 #-------------------------------------------------------------------------
983 # Things related to hooks
983 # Things related to hooks
984 #-------------------------------------------------------------------------
984 #-------------------------------------------------------------------------
985
985
986 def init_hooks(self):
986 def init_hooks(self):
987 # hooks holds pointers used for user-side customizations
987 # hooks holds pointers used for user-side customizations
988 self.hooks = Struct()
988 self.hooks = Struct()
989
989
990 self.strdispatchers = {}
990 self.strdispatchers = {}
991
991
992 # Set all default hooks, defined in the IPython.hooks module.
992 # Set all default hooks, defined in the IPython.hooks module.
993 hooks = IPython.core.hooks
993 hooks = IPython.core.hooks
994 for hook_name in hooks.__all__:
994 for hook_name in hooks.__all__:
995 # default hooks have priority 100, i.e. low; user hooks should have
995 # default hooks have priority 100, i.e. low; user hooks should have
996 # 0-100 priority
996 # 0-100 priority
997 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
997 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
998
998
999 if self.display_page:
999 if self.display_page:
1000 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
1000 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
1001
1001
1002 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
1002 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
1003 _warn_deprecated=True):
1003 _warn_deprecated=True):
1004 """set_hook(name,hook) -> sets an internal IPython hook.
1004 """set_hook(name,hook) -> sets an internal IPython hook.
1005
1005
1006 IPython exposes some of its internal API as user-modifiable hooks. By
1006 IPython exposes some of its internal API as user-modifiable hooks. By
1007 adding your function to one of these hooks, you can modify IPython's
1007 adding your function to one of these hooks, you can modify IPython's
1008 behavior to call at runtime your own routines."""
1008 behavior to call at runtime your own routines."""
1009
1009
1010 # At some point in the future, this should validate the hook before it
1010 # At some point in the future, this should validate the hook before it
1011 # accepts it. Probably at least check that the hook takes the number
1011 # accepts it. Probably at least check that the hook takes the number
1012 # of args it's supposed to.
1012 # of args it's supposed to.
1013
1013
1014 f = types.MethodType(hook,self)
1014 f = types.MethodType(hook,self)
1015
1015
1016 # check if the hook is for strdispatcher first
1016 # check if the hook is for strdispatcher first
1017 if str_key is not None:
1017 if str_key is not None:
1018 sdp = self.strdispatchers.get(name, StrDispatch())
1018 sdp = self.strdispatchers.get(name, StrDispatch())
1019 sdp.add_s(str_key, f, priority )
1019 sdp.add_s(str_key, f, priority )
1020 self.strdispatchers[name] = sdp
1020 self.strdispatchers[name] = sdp
1021 return
1021 return
1022 if re_key is not None:
1022 if re_key is not None:
1023 sdp = self.strdispatchers.get(name, StrDispatch())
1023 sdp = self.strdispatchers.get(name, StrDispatch())
1024 sdp.add_re(re.compile(re_key), f, priority )
1024 sdp.add_re(re.compile(re_key), f, priority )
1025 self.strdispatchers[name] = sdp
1025 self.strdispatchers[name] = sdp
1026 return
1026 return
1027
1027
1028 dp = getattr(self.hooks, name, None)
1028 dp = getattr(self.hooks, name, None)
1029 if name not in IPython.core.hooks.__all__:
1029 if name not in IPython.core.hooks.__all__:
1030 print("Warning! Hook '%s' is not one of %s" % \
1030 print("Warning! Hook '%s' is not one of %s" % \
1031 (name, IPython.core.hooks.__all__ ))
1031 (name, IPython.core.hooks.__all__ ))
1032
1032
1033 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
1033 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
1034 alternative = IPython.core.hooks.deprecated[name]
1034 alternative = IPython.core.hooks.deprecated[name]
1035 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative), stacklevel=2)
1035 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative), stacklevel=2)
1036
1036
1037 if not dp:
1037 if not dp:
1038 dp = IPython.core.hooks.CommandChainDispatcher()
1038 dp = IPython.core.hooks.CommandChainDispatcher()
1039
1039
1040 try:
1040 try:
1041 dp.add(f,priority)
1041 dp.add(f,priority)
1042 except AttributeError:
1042 except AttributeError:
1043 # it was not commandchain, plain old func - replace
1043 # it was not commandchain, plain old func - replace
1044 dp = f
1044 dp = f
1045
1045
1046 setattr(self.hooks,name, dp)
1046 setattr(self.hooks,name, dp)
1047
1047
1048 #-------------------------------------------------------------------------
1048 #-------------------------------------------------------------------------
1049 # Things related to events
1049 # Things related to events
1050 #-------------------------------------------------------------------------
1050 #-------------------------------------------------------------------------
1051
1051
1052 def init_events(self):
1052 def init_events(self):
1053 self.events = EventManager(self, available_events)
1053 self.events = EventManager(self, available_events)
1054
1054
1055 self.events.register("pre_execute", self._clear_warning_registry)
1055 self.events.register("pre_execute", self._clear_warning_registry)
1056
1056
1057 def register_post_execute(self, func):
1057 def register_post_execute(self, func):
1058 """DEPRECATED: Use ip.events.register('post_run_cell', func)
1058 """DEPRECATED: Use ip.events.register('post_run_cell', func)
1059
1059
1060 Register a function for calling after code execution.
1060 Register a function for calling after code execution.
1061 """
1061 """
1062 warn("ip.register_post_execute is deprecated, use "
1062 warn("ip.register_post_execute is deprecated, use "
1063 "ip.events.register('post_run_cell', func) instead.", stacklevel=2)
1063 "ip.events.register('post_run_cell', func) instead.", stacklevel=2)
1064 self.events.register('post_run_cell', func)
1064 self.events.register('post_run_cell', func)
1065
1065
1066 def _clear_warning_registry(self):
1066 def _clear_warning_registry(self):
1067 # clear the warning registry, so that different code blocks with
1067 # clear the warning registry, so that different code blocks with
1068 # overlapping line number ranges don't cause spurious suppression of
1068 # overlapping line number ranges don't cause spurious suppression of
1069 # warnings (see gh-6611 for details)
1069 # warnings (see gh-6611 for details)
1070 if "__warningregistry__" in self.user_global_ns:
1070 if "__warningregistry__" in self.user_global_ns:
1071 del self.user_global_ns["__warningregistry__"]
1071 del self.user_global_ns["__warningregistry__"]
1072
1072
1073 #-------------------------------------------------------------------------
1073 #-------------------------------------------------------------------------
1074 # Things related to the "main" module
1074 # Things related to the "main" module
1075 #-------------------------------------------------------------------------
1075 #-------------------------------------------------------------------------
1076
1076
1077 def new_main_mod(self, filename, modname):
1077 def new_main_mod(self, filename, modname):
1078 """Return a new 'main' module object for user code execution.
1078 """Return a new 'main' module object for user code execution.
1079
1079
1080 ``filename`` should be the path of the script which will be run in the
1080 ``filename`` should be the path of the script which will be run in the
1081 module. Requests with the same filename will get the same module, with
1081 module. Requests with the same filename will get the same module, with
1082 its namespace cleared.
1082 its namespace cleared.
1083
1083
1084 ``modname`` should be the module name - normally either '__main__' or
1084 ``modname`` should be the module name - normally either '__main__' or
1085 the basename of the file without the extension.
1085 the basename of the file without the extension.
1086
1086
1087 When scripts are executed via %run, we must keep a reference to their
1087 When scripts are executed via %run, we must keep a reference to their
1088 __main__ module around so that Python doesn't
1088 __main__ module around so that Python doesn't
1089 clear it, rendering references to module globals useless.
1089 clear it, rendering references to module globals useless.
1090
1090
1091 This method keeps said reference in a private dict, keyed by the
1091 This method keeps said reference in a private dict, keyed by the
1092 absolute path of the script. This way, for multiple executions of the
1092 absolute path of the script. This way, for multiple executions of the
1093 same script we only keep one copy of the namespace (the last one),
1093 same script we only keep one copy of the namespace (the last one),
1094 thus preventing memory leaks from old references while allowing the
1094 thus preventing memory leaks from old references while allowing the
1095 objects from the last execution to be accessible.
1095 objects from the last execution to be accessible.
1096 """
1096 """
1097 filename = os.path.abspath(filename)
1097 filename = os.path.abspath(filename)
1098 try:
1098 try:
1099 main_mod = self._main_mod_cache[filename]
1099 main_mod = self._main_mod_cache[filename]
1100 except KeyError:
1100 except KeyError:
1101 main_mod = self._main_mod_cache[filename] = types.ModuleType(
1101 main_mod = self._main_mod_cache[filename] = types.ModuleType(
1102 modname,
1102 modname,
1103 doc="Module created for script run in IPython")
1103 doc="Module created for script run in IPython")
1104 else:
1104 else:
1105 main_mod.__dict__.clear()
1105 main_mod.__dict__.clear()
1106 main_mod.__name__ = modname
1106 main_mod.__name__ = modname
1107
1107
1108 main_mod.__file__ = filename
1108 main_mod.__file__ = filename
1109 # It seems pydoc (and perhaps others) needs any module instance to
1109 # It seems pydoc (and perhaps others) needs any module instance to
1110 # implement a __nonzero__ method
1110 # implement a __nonzero__ method
1111 main_mod.__nonzero__ = lambda : True
1111 main_mod.__nonzero__ = lambda : True
1112
1112
1113 return main_mod
1113 return main_mod
1114
1114
1115 def clear_main_mod_cache(self):
1115 def clear_main_mod_cache(self):
1116 """Clear the cache of main modules.
1116 """Clear the cache of main modules.
1117
1117
1118 Mainly for use by utilities like %reset.
1118 Mainly for use by utilities like %reset.
1119
1119
1120 Examples
1120 Examples
1121 --------
1121 --------
1122
1122
1123 In [15]: import IPython
1123 In [15]: import IPython
1124
1124
1125 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
1125 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
1126
1126
1127 In [17]: len(_ip._main_mod_cache) > 0
1127 In [17]: len(_ip._main_mod_cache) > 0
1128 Out[17]: True
1128 Out[17]: True
1129
1129
1130 In [18]: _ip.clear_main_mod_cache()
1130 In [18]: _ip.clear_main_mod_cache()
1131
1131
1132 In [19]: len(_ip._main_mod_cache) == 0
1132 In [19]: len(_ip._main_mod_cache) == 0
1133 Out[19]: True
1133 Out[19]: True
1134 """
1134 """
1135 self._main_mod_cache.clear()
1135 self._main_mod_cache.clear()
1136
1136
1137 #-------------------------------------------------------------------------
1137 #-------------------------------------------------------------------------
1138 # Things related to debugging
1138 # Things related to debugging
1139 #-------------------------------------------------------------------------
1139 #-------------------------------------------------------------------------
1140
1140
1141 def init_pdb(self):
1141 def init_pdb(self):
1142 # Set calling of pdb on exceptions
1142 # Set calling of pdb on exceptions
1143 # self.call_pdb is a property
1143 # self.call_pdb is a property
1144 self.call_pdb = self.pdb
1144 self.call_pdb = self.pdb
1145
1145
1146 def _get_call_pdb(self):
1146 def _get_call_pdb(self):
1147 return self._call_pdb
1147 return self._call_pdb
1148
1148
1149 def _set_call_pdb(self,val):
1149 def _set_call_pdb(self,val):
1150
1150
1151 if val not in (0,1,False,True):
1151 if val not in (0,1,False,True):
1152 raise ValueError('new call_pdb value must be boolean')
1152 raise ValueError('new call_pdb value must be boolean')
1153
1153
1154 # store value in instance
1154 # store value in instance
1155 self._call_pdb = val
1155 self._call_pdb = val
1156
1156
1157 # notify the actual exception handlers
1157 # notify the actual exception handlers
1158 self.InteractiveTB.call_pdb = val
1158 self.InteractiveTB.call_pdb = val
1159
1159
1160 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
1160 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
1161 'Control auto-activation of pdb at exceptions')
1161 'Control auto-activation of pdb at exceptions')
1162
1162
1163 def debugger(self,force=False):
1163 def debugger(self,force=False):
1164 """Call the pdb debugger.
1164 """Call the pdb debugger.
1165
1165
1166 Keywords:
1166 Keywords:
1167
1167
1168 - force(False): by default, this routine checks the instance call_pdb
1168 - force(False): by default, this routine checks the instance call_pdb
1169 flag and does not actually invoke the debugger if the flag is false.
1169 flag and does not actually invoke the debugger if the flag is false.
1170 The 'force' option forces the debugger to activate even if the flag
1170 The 'force' option forces the debugger to activate even if the flag
1171 is false.
1171 is false.
1172 """
1172 """
1173
1173
1174 if not (force or self.call_pdb):
1174 if not (force or self.call_pdb):
1175 return
1175 return
1176
1176
1177 if not hasattr(sys,'last_traceback'):
1177 if not hasattr(sys,'last_traceback'):
1178 error('No traceback has been produced, nothing to debug.')
1178 error('No traceback has been produced, nothing to debug.')
1179 return
1179 return
1180
1180
1181 self.InteractiveTB.debugger(force=True)
1181 self.InteractiveTB.debugger(force=True)
1182
1182
1183 #-------------------------------------------------------------------------
1183 #-------------------------------------------------------------------------
1184 # Things related to IPython's various namespaces
1184 # Things related to IPython's various namespaces
1185 #-------------------------------------------------------------------------
1185 #-------------------------------------------------------------------------
1186 default_user_namespaces = True
1186 default_user_namespaces = True
1187
1187
1188 def init_create_namespaces(self, user_module=None, user_ns=None):
1188 def init_create_namespaces(self, user_module=None, user_ns=None):
1189 # Create the namespace where the user will operate. user_ns is
1189 # Create the namespace where the user will operate. user_ns is
1190 # normally the only one used, and it is passed to the exec calls as
1190 # normally the only one used, and it is passed to the exec calls as
1191 # the locals argument. But we do carry a user_global_ns namespace
1191 # the locals argument. But we do carry a user_global_ns namespace
1192 # given as the exec 'globals' argument, This is useful in embedding
1192 # given as the exec 'globals' argument, This is useful in embedding
1193 # situations where the ipython shell opens in a context where the
1193 # situations where the ipython shell opens in a context where the
1194 # distinction between locals and globals is meaningful. For
1194 # distinction between locals and globals is meaningful. For
1195 # non-embedded contexts, it is just the same object as the user_ns dict.
1195 # non-embedded contexts, it is just the same object as the user_ns dict.
1196
1196
1197 # FIXME. For some strange reason, __builtins__ is showing up at user
1197 # FIXME. For some strange reason, __builtins__ is showing up at user
1198 # level as a dict instead of a module. This is a manual fix, but I
1198 # level as a dict instead of a module. This is a manual fix, but I
1199 # should really track down where the problem is coming from. Alex
1199 # should really track down where the problem is coming from. Alex
1200 # Schmolck reported this problem first.
1200 # Schmolck reported this problem first.
1201
1201
1202 # A useful post by Alex Martelli on this topic:
1202 # A useful post by Alex Martelli on this topic:
1203 # Re: inconsistent value from __builtins__
1203 # Re: inconsistent value from __builtins__
1204 # Von: Alex Martelli <aleaxit@yahoo.com>
1204 # Von: Alex Martelli <aleaxit@yahoo.com>
1205 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1205 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1206 # Gruppen: comp.lang.python
1206 # Gruppen: comp.lang.python
1207
1207
1208 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1208 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1209 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1209 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1210 # > <type 'dict'>
1210 # > <type 'dict'>
1211 # > >>> print type(__builtins__)
1211 # > >>> print type(__builtins__)
1212 # > <type 'module'>
1212 # > <type 'module'>
1213 # > Is this difference in return value intentional?
1213 # > Is this difference in return value intentional?
1214
1214
1215 # Well, it's documented that '__builtins__' can be either a dictionary
1215 # Well, it's documented that '__builtins__' can be either a dictionary
1216 # or a module, and it's been that way for a long time. Whether it's
1216 # or a module, and it's been that way for a long time. Whether it's
1217 # intentional (or sensible), I don't know. In any case, the idea is
1217 # intentional (or sensible), I don't know. In any case, the idea is
1218 # that if you need to access the built-in namespace directly, you
1218 # that if you need to access the built-in namespace directly, you
1219 # should start with "import __builtin__" (note, no 's') which will
1219 # should start with "import __builtin__" (note, no 's') which will
1220 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1220 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1221
1221
1222 # These routines return a properly built module and dict as needed by
1222 # These routines return a properly built module and dict as needed by
1223 # the rest of the code, and can also be used by extension writers to
1223 # the rest of the code, and can also be used by extension writers to
1224 # generate properly initialized namespaces.
1224 # generate properly initialized namespaces.
1225 if (user_ns is not None) or (user_module is not None):
1225 if (user_ns is not None) or (user_module is not None):
1226 self.default_user_namespaces = False
1226 self.default_user_namespaces = False
1227 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1227 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1228
1228
1229 # A record of hidden variables we have added to the user namespace, so
1229 # A record of hidden variables we have added to the user namespace, so
1230 # we can list later only variables defined in actual interactive use.
1230 # we can list later only variables defined in actual interactive use.
1231 self.user_ns_hidden = {}
1231 self.user_ns_hidden = {}
1232
1232
1233 # Now that FakeModule produces a real module, we've run into a nasty
1233 # Now that FakeModule produces a real module, we've run into a nasty
1234 # problem: after script execution (via %run), the module where the user
1234 # problem: after script execution (via %run), the module where the user
1235 # code ran is deleted. Now that this object is a true module (needed
1235 # code ran is deleted. Now that this object is a true module (needed
1236 # so doctest and other tools work correctly), the Python module
1236 # so doctest and other tools work correctly), the Python module
1237 # teardown mechanism runs over it, and sets to None every variable
1237 # teardown mechanism runs over it, and sets to None every variable
1238 # present in that module. Top-level references to objects from the
1238 # present in that module. Top-level references to objects from the
1239 # script survive, because the user_ns is updated with them. However,
1239 # script survive, because the user_ns is updated with them. However,
1240 # calling functions defined in the script that use other things from
1240 # calling functions defined in the script that use other things from
1241 # the script will fail, because the function's closure had references
1241 # the script will fail, because the function's closure had references
1242 # to the original objects, which are now all None. So we must protect
1242 # to the original objects, which are now all None. So we must protect
1243 # these modules from deletion by keeping a cache.
1243 # these modules from deletion by keeping a cache.
1244 #
1244 #
1245 # To avoid keeping stale modules around (we only need the one from the
1245 # To avoid keeping stale modules around (we only need the one from the
1246 # last run), we use a dict keyed with the full path to the script, so
1246 # last run), we use a dict keyed with the full path to the script, so
1247 # only the last version of the module is held in the cache. Note,
1247 # only the last version of the module is held in the cache. Note,
1248 # however, that we must cache the module *namespace contents* (their
1248 # however, that we must cache the module *namespace contents* (their
1249 # __dict__). Because if we try to cache the actual modules, old ones
1249 # __dict__). Because if we try to cache the actual modules, old ones
1250 # (uncached) could be destroyed while still holding references (such as
1250 # (uncached) could be destroyed while still holding references (such as
1251 # those held by GUI objects that tend to be long-lived)>
1251 # those held by GUI objects that tend to be long-lived)>
1252 #
1252 #
1253 # The %reset command will flush this cache. See the cache_main_mod()
1253 # The %reset command will flush this cache. See the cache_main_mod()
1254 # and clear_main_mod_cache() methods for details on use.
1254 # and clear_main_mod_cache() methods for details on use.
1255
1255
1256 # This is the cache used for 'main' namespaces
1256 # This is the cache used for 'main' namespaces
1257 self._main_mod_cache = {}
1257 self._main_mod_cache = {}
1258
1258
1259 # A table holding all the namespaces IPython deals with, so that
1259 # A table holding all the namespaces IPython deals with, so that
1260 # introspection facilities can search easily.
1260 # introspection facilities can search easily.
1261 self.ns_table = {'user_global':self.user_module.__dict__,
1261 self.ns_table = {'user_global':self.user_module.__dict__,
1262 'user_local':self.user_ns,
1262 'user_local':self.user_ns,
1263 'builtin':builtin_mod.__dict__
1263 'builtin':builtin_mod.__dict__
1264 }
1264 }
1265
1265
1266 @property
1266 @property
1267 def user_global_ns(self):
1267 def user_global_ns(self):
1268 return self.user_module.__dict__
1268 return self.user_module.__dict__
1269
1269
1270 def prepare_user_module(self, user_module=None, user_ns=None):
1270 def prepare_user_module(self, user_module=None, user_ns=None):
1271 """Prepare the module and namespace in which user code will be run.
1271 """Prepare the module and namespace in which user code will be run.
1272
1272
1273 When IPython is started normally, both parameters are None: a new module
1273 When IPython is started normally, both parameters are None: a new module
1274 is created automatically, and its __dict__ used as the namespace.
1274 is created automatically, and its __dict__ used as the namespace.
1275
1275
1276 If only user_module is provided, its __dict__ is used as the namespace.
1276 If only user_module is provided, its __dict__ is used as the namespace.
1277 If only user_ns is provided, a dummy module is created, and user_ns
1277 If only user_ns is provided, a dummy module is created, and user_ns
1278 becomes the global namespace. If both are provided (as they may be
1278 becomes the global namespace. If both are provided (as they may be
1279 when embedding), user_ns is the local namespace, and user_module
1279 when embedding), user_ns is the local namespace, and user_module
1280 provides the global namespace.
1280 provides the global namespace.
1281
1281
1282 Parameters
1282 Parameters
1283 ----------
1283 ----------
1284 user_module : module, optional
1284 user_module : module, optional
1285 The current user module in which IPython is being run. If None,
1285 The current user module in which IPython is being run. If None,
1286 a clean module will be created.
1286 a clean module will be created.
1287 user_ns : dict, optional
1287 user_ns : dict, optional
1288 A namespace in which to run interactive commands.
1288 A namespace in which to run interactive commands.
1289
1289
1290 Returns
1290 Returns
1291 -------
1291 -------
1292 A tuple of user_module and user_ns, each properly initialised.
1292 A tuple of user_module and user_ns, each properly initialised.
1293 """
1293 """
1294 if user_module is None and user_ns is not None:
1294 if user_module is None and user_ns is not None:
1295 user_ns.setdefault("__name__", "__main__")
1295 user_ns.setdefault("__name__", "__main__")
1296 user_module = DummyMod()
1296 user_module = DummyMod()
1297 user_module.__dict__ = user_ns
1297 user_module.__dict__ = user_ns
1298
1298
1299 if user_module is None:
1299 if user_module is None:
1300 user_module = types.ModuleType("__main__",
1300 user_module = types.ModuleType("__main__",
1301 doc="Automatically created module for IPython interactive environment")
1301 doc="Automatically created module for IPython interactive environment")
1302
1302
1303 # We must ensure that __builtin__ (without the final 's') is always
1303 # We must ensure that __builtin__ (without the final 's') is always
1304 # available and pointing to the __builtin__ *module*. For more details:
1304 # available and pointing to the __builtin__ *module*. For more details:
1305 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1305 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1306 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1306 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1307 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1307 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1308
1308
1309 if user_ns is None:
1309 if user_ns is None:
1310 user_ns = user_module.__dict__
1310 user_ns = user_module.__dict__
1311
1311
1312 return user_module, user_ns
1312 return user_module, user_ns
1313
1313
1314 def init_sys_modules(self):
1314 def init_sys_modules(self):
1315 # We need to insert into sys.modules something that looks like a
1315 # We need to insert into sys.modules something that looks like a
1316 # module but which accesses the IPython namespace, for shelve and
1316 # module but which accesses the IPython namespace, for shelve and
1317 # pickle to work interactively. Normally they rely on getting
1317 # pickle to work interactively. Normally they rely on getting
1318 # everything out of __main__, but for embedding purposes each IPython
1318 # everything out of __main__, but for embedding purposes each IPython
1319 # instance has its own private namespace, so we can't go shoving
1319 # instance has its own private namespace, so we can't go shoving
1320 # everything into __main__.
1320 # everything into __main__.
1321
1321
1322 # note, however, that we should only do this for non-embedded
1322 # note, however, that we should only do this for non-embedded
1323 # ipythons, which really mimic the __main__.__dict__ with their own
1323 # ipythons, which really mimic the __main__.__dict__ with their own
1324 # namespace. Embedded instances, on the other hand, should not do
1324 # namespace. Embedded instances, on the other hand, should not do
1325 # this because they need to manage the user local/global namespaces
1325 # this because they need to manage the user local/global namespaces
1326 # only, but they live within a 'normal' __main__ (meaning, they
1326 # only, but they live within a 'normal' __main__ (meaning, they
1327 # shouldn't overtake the execution environment of the script they're
1327 # shouldn't overtake the execution environment of the script they're
1328 # embedded in).
1328 # embedded in).
1329
1329
1330 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1330 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1331 main_name = self.user_module.__name__
1331 main_name = self.user_module.__name__
1332 sys.modules[main_name] = self.user_module
1332 sys.modules[main_name] = self.user_module
1333
1333
1334 def init_user_ns(self):
1334 def init_user_ns(self):
1335 """Initialize all user-visible namespaces to their minimum defaults.
1335 """Initialize all user-visible namespaces to their minimum defaults.
1336
1336
1337 Certain history lists are also initialized here, as they effectively
1337 Certain history lists are also initialized here, as they effectively
1338 act as user namespaces.
1338 act as user namespaces.
1339
1339
1340 Notes
1340 Notes
1341 -----
1341 -----
1342 All data structures here are only filled in, they are NOT reset by this
1342 All data structures here are only filled in, they are NOT reset by this
1343 method. If they were not empty before, data will simply be added to
1343 method. If they were not empty before, data will simply be added to
1344 them.
1344 them.
1345 """
1345 """
1346 # This function works in two parts: first we put a few things in
1346 # This function works in two parts: first we put a few things in
1347 # user_ns, and we sync that contents into user_ns_hidden so that these
1347 # user_ns, and we sync that contents into user_ns_hidden so that these
1348 # initial variables aren't shown by %who. After the sync, we add the
1348 # initial variables aren't shown by %who. After the sync, we add the
1349 # rest of what we *do* want the user to see with %who even on a new
1349 # rest of what we *do* want the user to see with %who even on a new
1350 # session (probably nothing, so they really only see their own stuff)
1350 # session (probably nothing, so they really only see their own stuff)
1351
1351
1352 # The user dict must *always* have a __builtin__ reference to the
1352 # The user dict must *always* have a __builtin__ reference to the
1353 # Python standard __builtin__ namespace, which must be imported.
1353 # Python standard __builtin__ namespace, which must be imported.
1354 # This is so that certain operations in prompt evaluation can be
1354 # This is so that certain operations in prompt evaluation can be
1355 # reliably executed with builtins. Note that we can NOT use
1355 # reliably executed with builtins. Note that we can NOT use
1356 # __builtins__ (note the 's'), because that can either be a dict or a
1356 # __builtins__ (note the 's'), because that can either be a dict or a
1357 # module, and can even mutate at runtime, depending on the context
1357 # module, and can even mutate at runtime, depending on the context
1358 # (Python makes no guarantees on it). In contrast, __builtin__ is
1358 # (Python makes no guarantees on it). In contrast, __builtin__ is
1359 # always a module object, though it must be explicitly imported.
1359 # always a module object, though it must be explicitly imported.
1360
1360
1361 # For more details:
1361 # For more details:
1362 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1362 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1363 ns = {}
1363 ns = {}
1364
1364
1365 # make global variables for user access to the histories
1365 # make global variables for user access to the histories
1366 ns['_ih'] = self.history_manager.input_hist_parsed
1366 ns['_ih'] = self.history_manager.input_hist_parsed
1367 ns['_oh'] = self.history_manager.output_hist
1367 ns['_oh'] = self.history_manager.output_hist
1368 ns['_dh'] = self.history_manager.dir_hist
1368 ns['_dh'] = self.history_manager.dir_hist
1369
1369
1370 # user aliases to input and output histories. These shouldn't show up
1370 # user aliases to input and output histories. These shouldn't show up
1371 # in %who, as they can have very large reprs.
1371 # in %who, as they can have very large reprs.
1372 ns['In'] = self.history_manager.input_hist_parsed
1372 ns['In'] = self.history_manager.input_hist_parsed
1373 ns['Out'] = self.history_manager.output_hist
1373 ns['Out'] = self.history_manager.output_hist
1374
1374
1375 # Store myself as the public api!!!
1375 # Store myself as the public api!!!
1376 ns['get_ipython'] = self.get_ipython
1376 ns['get_ipython'] = self.get_ipython
1377
1377
1378 ns['exit'] = self.exiter
1378 ns['exit'] = self.exiter
1379 ns['quit'] = self.exiter
1379 ns['quit'] = self.exiter
1380
1380
1381 # Sync what we've added so far to user_ns_hidden so these aren't seen
1381 # Sync what we've added so far to user_ns_hidden so these aren't seen
1382 # by %who
1382 # by %who
1383 self.user_ns_hidden.update(ns)
1383 self.user_ns_hidden.update(ns)
1384
1384
1385 # Anything put into ns now would show up in %who. Think twice before
1385 # Anything put into ns now would show up in %who. Think twice before
1386 # putting anything here, as we really want %who to show the user their
1386 # putting anything here, as we really want %who to show the user their
1387 # stuff, not our variables.
1387 # stuff, not our variables.
1388
1388
1389 # Finally, update the real user's namespace
1389 # Finally, update the real user's namespace
1390 self.user_ns.update(ns)
1390 self.user_ns.update(ns)
1391
1391
1392 @property
1392 @property
1393 def all_ns_refs(self):
1393 def all_ns_refs(self):
1394 """Get a list of references to all the namespace dictionaries in which
1394 """Get a list of references to all the namespace dictionaries in which
1395 IPython might store a user-created object.
1395 IPython might store a user-created object.
1396
1396
1397 Note that this does not include the displayhook, which also caches
1397 Note that this does not include the displayhook, which also caches
1398 objects from the output."""
1398 objects from the output."""
1399 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1399 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1400 [m.__dict__ for m in self._main_mod_cache.values()]
1400 [m.__dict__ for m in self._main_mod_cache.values()]
1401
1401
1402 def reset(self, new_session=True):
1402 def reset(self, new_session=True):
1403 """Clear all internal namespaces, and attempt to release references to
1403 """Clear all internal namespaces, and attempt to release references to
1404 user objects.
1404 user objects.
1405
1405
1406 If new_session is True, a new history session will be opened.
1406 If new_session is True, a new history session will be opened.
1407 """
1407 """
1408 # Clear histories
1408 # Clear histories
1409 self.history_manager.reset(new_session)
1409 self.history_manager.reset(new_session)
1410 # Reset counter used to index all histories
1410 # Reset counter used to index all histories
1411 if new_session:
1411 if new_session:
1412 self.execution_count = 1
1412 self.execution_count = 1
1413
1413
1414 # Reset last execution result
1414 # Reset last execution result
1415 self.last_execution_succeeded = True
1415 self.last_execution_succeeded = True
1416 self.last_execution_result = None
1416 self.last_execution_result = None
1417
1417
1418 # Flush cached output items
1418 # Flush cached output items
1419 if self.displayhook.do_full_cache:
1419 if self.displayhook.do_full_cache:
1420 self.displayhook.flush()
1420 self.displayhook.flush()
1421
1421
1422 # The main execution namespaces must be cleared very carefully,
1422 # The main execution namespaces must be cleared very carefully,
1423 # skipping the deletion of the builtin-related keys, because doing so
1423 # skipping the deletion of the builtin-related keys, because doing so
1424 # would cause errors in many object's __del__ methods.
1424 # would cause errors in many object's __del__ methods.
1425 if self.user_ns is not self.user_global_ns:
1425 if self.user_ns is not self.user_global_ns:
1426 self.user_ns.clear()
1426 self.user_ns.clear()
1427 ns = self.user_global_ns
1427 ns = self.user_global_ns
1428 drop_keys = set(ns.keys())
1428 drop_keys = set(ns.keys())
1429 drop_keys.discard('__builtin__')
1429 drop_keys.discard('__builtin__')
1430 drop_keys.discard('__builtins__')
1430 drop_keys.discard('__builtins__')
1431 drop_keys.discard('__name__')
1431 drop_keys.discard('__name__')
1432 for k in drop_keys:
1432 for k in drop_keys:
1433 del ns[k]
1433 del ns[k]
1434
1434
1435 self.user_ns_hidden.clear()
1435 self.user_ns_hidden.clear()
1436
1436
1437 # Restore the user namespaces to minimal usability
1437 # Restore the user namespaces to minimal usability
1438 self.init_user_ns()
1438 self.init_user_ns()
1439
1439
1440 # Restore the default and user aliases
1440 # Restore the default and user aliases
1441 self.alias_manager.clear_aliases()
1441 self.alias_manager.clear_aliases()
1442 self.alias_manager.init_aliases()
1442 self.alias_manager.init_aliases()
1443
1443
1444 # Now define aliases that only make sense on the terminal, because they
1444 # Now define aliases that only make sense on the terminal, because they
1445 # need direct access to the console in a way that we can't emulate in
1445 # need direct access to the console in a way that we can't emulate in
1446 # GUI or web frontend
1446 # GUI or web frontend
1447 if os.name == 'posix':
1447 if os.name == 'posix':
1448 for cmd in ('clear', 'more', 'less', 'man'):
1448 for cmd in ('clear', 'more', 'less', 'man'):
1449 if cmd not in self.magics_manager.magics['line']:
1449 if cmd not in self.magics_manager.magics['line']:
1450 self.alias_manager.soft_define_alias(cmd, cmd)
1450 self.alias_manager.soft_define_alias(cmd, cmd)
1451
1451
1452 # Flush the private list of module references kept for script
1452 # Flush the private list of module references kept for script
1453 # execution protection
1453 # execution protection
1454 self.clear_main_mod_cache()
1454 self.clear_main_mod_cache()
1455
1455
1456 def del_var(self, varname, by_name=False):
1456 def del_var(self, varname, by_name=False):
1457 """Delete a variable from the various namespaces, so that, as
1457 """Delete a variable from the various namespaces, so that, as
1458 far as possible, we're not keeping any hidden references to it.
1458 far as possible, we're not keeping any hidden references to it.
1459
1459
1460 Parameters
1460 Parameters
1461 ----------
1461 ----------
1462 varname : str
1462 varname : str
1463 The name of the variable to delete.
1463 The name of the variable to delete.
1464 by_name : bool
1464 by_name : bool
1465 If True, delete variables with the given name in each
1465 If True, delete variables with the given name in each
1466 namespace. If False (default), find the variable in the user
1466 namespace. If False (default), find the variable in the user
1467 namespace, and delete references to it.
1467 namespace, and delete references to it.
1468 """
1468 """
1469 if varname in ('__builtin__', '__builtins__'):
1469 if varname in ('__builtin__', '__builtins__'):
1470 raise ValueError("Refusing to delete %s" % varname)
1470 raise ValueError("Refusing to delete %s" % varname)
1471
1471
1472 ns_refs = self.all_ns_refs
1472 ns_refs = self.all_ns_refs
1473
1473
1474 if by_name: # Delete by name
1474 if by_name: # Delete by name
1475 for ns in ns_refs:
1475 for ns in ns_refs:
1476 try:
1476 try:
1477 del ns[varname]
1477 del ns[varname]
1478 except KeyError:
1478 except KeyError:
1479 pass
1479 pass
1480 else: # Delete by object
1480 else: # Delete by object
1481 try:
1481 try:
1482 obj = self.user_ns[varname]
1482 obj = self.user_ns[varname]
1483 except KeyError:
1483 except KeyError:
1484 raise NameError("name '%s' is not defined" % varname)
1484 raise NameError("name '%s' is not defined" % varname)
1485 # Also check in output history
1485 # Also check in output history
1486 ns_refs.append(self.history_manager.output_hist)
1486 ns_refs.append(self.history_manager.output_hist)
1487 for ns in ns_refs:
1487 for ns in ns_refs:
1488 to_delete = [n for n, o in ns.items() if o is obj]
1488 to_delete = [n for n, o in ns.items() if o is obj]
1489 for name in to_delete:
1489 for name in to_delete:
1490 del ns[name]
1490 del ns[name]
1491
1491
1492 # Ensure it is removed from the last execution result
1492 # Ensure it is removed from the last execution result
1493 if self.last_execution_result.result is obj:
1493 if self.last_execution_result.result is obj:
1494 self.last_execution_result = None
1494 self.last_execution_result = None
1495
1495
1496 # displayhook keeps extra references, but not in a dictionary
1496 # displayhook keeps extra references, but not in a dictionary
1497 for name in ('_', '__', '___'):
1497 for name in ('_', '__', '___'):
1498 if getattr(self.displayhook, name) is obj:
1498 if getattr(self.displayhook, name) is obj:
1499 setattr(self.displayhook, name, None)
1499 setattr(self.displayhook, name, None)
1500
1500
1501 def reset_selective(self, regex=None):
1501 def reset_selective(self, regex=None):
1502 """Clear selective variables from internal namespaces based on a
1502 """Clear selective variables from internal namespaces based on a
1503 specified regular expression.
1503 specified regular expression.
1504
1504
1505 Parameters
1505 Parameters
1506 ----------
1506 ----------
1507 regex : string or compiled pattern, optional
1507 regex : string or compiled pattern, optional
1508 A regular expression pattern that will be used in searching
1508 A regular expression pattern that will be used in searching
1509 variable names in the users namespaces.
1509 variable names in the users namespaces.
1510 """
1510 """
1511 if regex is not None:
1511 if regex is not None:
1512 try:
1512 try:
1513 m = re.compile(regex)
1513 m = re.compile(regex)
1514 except TypeError:
1514 except TypeError:
1515 raise TypeError('regex must be a string or compiled pattern')
1515 raise TypeError('regex must be a string or compiled pattern')
1516 # Search for keys in each namespace that match the given regex
1516 # Search for keys in each namespace that match the given regex
1517 # If a match is found, delete the key/value pair.
1517 # If a match is found, delete the key/value pair.
1518 for ns in self.all_ns_refs:
1518 for ns in self.all_ns_refs:
1519 for var in ns:
1519 for var in ns:
1520 if m.search(var):
1520 if m.search(var):
1521 del ns[var]
1521 del ns[var]
1522
1522
1523 def push(self, variables, interactive=True):
1523 def push(self, variables, interactive=True):
1524 """Inject a group of variables into the IPython user namespace.
1524 """Inject a group of variables into the IPython user namespace.
1525
1525
1526 Parameters
1526 Parameters
1527 ----------
1527 ----------
1528 variables : dict, str or list/tuple of str
1528 variables : dict, str or list/tuple of str
1529 The variables to inject into the user's namespace. If a dict, a
1529 The variables to inject into the user's namespace. If a dict, a
1530 simple update is done. If a str, the string is assumed to have
1530 simple update is done. If a str, the string is assumed to have
1531 variable names separated by spaces. A list/tuple of str can also
1531 variable names separated by spaces. A list/tuple of str can also
1532 be used to give the variable names. If just the variable names are
1532 be used to give the variable names. If just the variable names are
1533 give (list/tuple/str) then the variable values looked up in the
1533 give (list/tuple/str) then the variable values looked up in the
1534 callers frame.
1534 callers frame.
1535 interactive : bool
1535 interactive : bool
1536 If True (default), the variables will be listed with the ``who``
1536 If True (default), the variables will be listed with the ``who``
1537 magic.
1537 magic.
1538 """
1538 """
1539 vdict = None
1539 vdict = None
1540
1540
1541 # We need a dict of name/value pairs to do namespace updates.
1541 # We need a dict of name/value pairs to do namespace updates.
1542 if isinstance(variables, dict):
1542 if isinstance(variables, dict):
1543 vdict = variables
1543 vdict = variables
1544 elif isinstance(variables, (str, list, tuple)):
1544 elif isinstance(variables, (str, list, tuple)):
1545 if isinstance(variables, str):
1545 if isinstance(variables, str):
1546 vlist = variables.split()
1546 vlist = variables.split()
1547 else:
1547 else:
1548 vlist = variables
1548 vlist = variables
1549 vdict = {}
1549 vdict = {}
1550 cf = sys._getframe(1)
1550 cf = sys._getframe(1)
1551 for name in vlist:
1551 for name in vlist:
1552 try:
1552 try:
1553 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1553 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1554 except:
1554 except:
1555 print('Could not get variable %s from %s' %
1555 print('Could not get variable %s from %s' %
1556 (name,cf.f_code.co_name))
1556 (name,cf.f_code.co_name))
1557 else:
1557 else:
1558 raise ValueError('variables must be a dict/str/list/tuple')
1558 raise ValueError('variables must be a dict/str/list/tuple')
1559
1559
1560 # Propagate variables to user namespace
1560 # Propagate variables to user namespace
1561 self.user_ns.update(vdict)
1561 self.user_ns.update(vdict)
1562
1562
1563 # And configure interactive visibility
1563 # And configure interactive visibility
1564 user_ns_hidden = self.user_ns_hidden
1564 user_ns_hidden = self.user_ns_hidden
1565 if interactive:
1565 if interactive:
1566 for name in vdict:
1566 for name in vdict:
1567 user_ns_hidden.pop(name, None)
1567 user_ns_hidden.pop(name, None)
1568 else:
1568 else:
1569 user_ns_hidden.update(vdict)
1569 user_ns_hidden.update(vdict)
1570
1570
1571 def drop_by_id(self, variables):
1571 def drop_by_id(self, variables):
1572 """Remove a dict of variables from the user namespace, if they are the
1572 """Remove a dict of variables from the user namespace, if they are the
1573 same as the values in the dictionary.
1573 same as the values in the dictionary.
1574
1574
1575 This is intended for use by extensions: variables that they've added can
1575 This is intended for use by extensions: variables that they've added can
1576 be taken back out if they are unloaded, without removing any that the
1576 be taken back out if they are unloaded, without removing any that the
1577 user has overwritten.
1577 user has overwritten.
1578
1578
1579 Parameters
1579 Parameters
1580 ----------
1580 ----------
1581 variables : dict
1581 variables : dict
1582 A dictionary mapping object names (as strings) to the objects.
1582 A dictionary mapping object names (as strings) to the objects.
1583 """
1583 """
1584 for name, obj in variables.items():
1584 for name, obj in variables.items():
1585 if name in self.user_ns and self.user_ns[name] is obj:
1585 if name in self.user_ns and self.user_ns[name] is obj:
1586 del self.user_ns[name]
1586 del self.user_ns[name]
1587 self.user_ns_hidden.pop(name, None)
1587 self.user_ns_hidden.pop(name, None)
1588
1588
1589 #-------------------------------------------------------------------------
1589 #-------------------------------------------------------------------------
1590 # Things related to object introspection
1590 # Things related to object introspection
1591 #-------------------------------------------------------------------------
1591 #-------------------------------------------------------------------------
1592
1592
1593 def _ofind(self, oname, namespaces=None):
1593 def _ofind(self, oname, namespaces=None):
1594 """Find an object in the available namespaces.
1594 """Find an object in the available namespaces.
1595
1595
1596 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1596 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1597
1597
1598 Has special code to detect magic functions.
1598 Has special code to detect magic functions.
1599 """
1599 """
1600 oname = oname.strip()
1600 oname = oname.strip()
1601 if not oname.startswith(ESC_MAGIC) and \
1601 if not oname.startswith(ESC_MAGIC) and \
1602 not oname.startswith(ESC_MAGIC2) and \
1602 not oname.startswith(ESC_MAGIC2) and \
1603 not all(a.isidentifier() for a in oname.split(".")):
1603 not all(a.isidentifier() for a in oname.split(".")):
1604 return {'found': False}
1604 return {'found': False}
1605
1605
1606 if namespaces is None:
1606 if namespaces is None:
1607 # Namespaces to search in:
1607 # Namespaces to search in:
1608 # Put them in a list. The order is important so that we
1608 # Put them in a list. The order is important so that we
1609 # find things in the same order that Python finds them.
1609 # find things in the same order that Python finds them.
1610 namespaces = [ ('Interactive', self.user_ns),
1610 namespaces = [ ('Interactive', self.user_ns),
1611 ('Interactive (global)', self.user_global_ns),
1611 ('Interactive (global)', self.user_global_ns),
1612 ('Python builtin', builtin_mod.__dict__),
1612 ('Python builtin', builtin_mod.__dict__),
1613 ]
1613 ]
1614
1614
1615 ismagic = False
1615 ismagic = False
1616 isalias = False
1616 isalias = False
1617 found = False
1617 found = False
1618 ospace = None
1618 ospace = None
1619 parent = None
1619 parent = None
1620 obj = None
1620 obj = None
1621
1621
1622
1622
1623 # Look for the given name by splitting it in parts. If the head is
1623 # Look for the given name by splitting it in parts. If the head is
1624 # found, then we look for all the remaining parts as members, and only
1624 # found, then we look for all the remaining parts as members, and only
1625 # declare success if we can find them all.
1625 # declare success if we can find them all.
1626 oname_parts = oname.split('.')
1626 oname_parts = oname.split('.')
1627 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1627 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1628 for nsname,ns in namespaces:
1628 for nsname,ns in namespaces:
1629 try:
1629 try:
1630 obj = ns[oname_head]
1630 obj = ns[oname_head]
1631 except KeyError:
1631 except KeyError:
1632 continue
1632 continue
1633 else:
1633 else:
1634 for idx, part in enumerate(oname_rest):
1634 for idx, part in enumerate(oname_rest):
1635 try:
1635 try:
1636 parent = obj
1636 parent = obj
1637 # The last part is looked up in a special way to avoid
1637 # The last part is looked up in a special way to avoid
1638 # descriptor invocation as it may raise or have side
1638 # descriptor invocation as it may raise or have side
1639 # effects.
1639 # effects.
1640 if idx == len(oname_rest) - 1:
1640 if idx == len(oname_rest) - 1:
1641 obj = self._getattr_property(obj, part)
1641 obj = self._getattr_property(obj, part)
1642 else:
1642 else:
1643 obj = getattr(obj, part)
1643 obj = getattr(obj, part)
1644 except:
1644 except:
1645 # Blanket except b/c some badly implemented objects
1645 # Blanket except b/c some badly implemented objects
1646 # allow __getattr__ to raise exceptions other than
1646 # allow __getattr__ to raise exceptions other than
1647 # AttributeError, which then crashes IPython.
1647 # AttributeError, which then crashes IPython.
1648 break
1648 break
1649 else:
1649 else:
1650 # If we finish the for loop (no break), we got all members
1650 # If we finish the for loop (no break), we got all members
1651 found = True
1651 found = True
1652 ospace = nsname
1652 ospace = nsname
1653 break # namespace loop
1653 break # namespace loop
1654
1654
1655 # Try to see if it's magic
1655 # Try to see if it's magic
1656 if not found:
1656 if not found:
1657 obj = None
1657 obj = None
1658 if oname.startswith(ESC_MAGIC2):
1658 if oname.startswith(ESC_MAGIC2):
1659 oname = oname.lstrip(ESC_MAGIC2)
1659 oname = oname.lstrip(ESC_MAGIC2)
1660 obj = self.find_cell_magic(oname)
1660 obj = self.find_cell_magic(oname)
1661 elif oname.startswith(ESC_MAGIC):
1661 elif oname.startswith(ESC_MAGIC):
1662 oname = oname.lstrip(ESC_MAGIC)
1662 oname = oname.lstrip(ESC_MAGIC)
1663 obj = self.find_line_magic(oname)
1663 obj = self.find_line_magic(oname)
1664 else:
1664 else:
1665 # search without prefix, so run? will find %run?
1665 # search without prefix, so run? will find %run?
1666 obj = self.find_line_magic(oname)
1666 obj = self.find_line_magic(oname)
1667 if obj is None:
1667 if obj is None:
1668 obj = self.find_cell_magic(oname)
1668 obj = self.find_cell_magic(oname)
1669 if obj is not None:
1669 if obj is not None:
1670 found = True
1670 found = True
1671 ospace = 'IPython internal'
1671 ospace = 'IPython internal'
1672 ismagic = True
1672 ismagic = True
1673 isalias = isinstance(obj, Alias)
1673 isalias = isinstance(obj, Alias)
1674
1674
1675 # Last try: special-case some literals like '', [], {}, etc:
1675 # Last try: special-case some literals like '', [], {}, etc:
1676 if not found and oname_head in ["''",'""','[]','{}','()']:
1676 if not found and oname_head in ["''",'""','[]','{}','()']:
1677 obj = eval(oname_head)
1677 obj = eval(oname_head)
1678 found = True
1678 found = True
1679 ospace = 'Interactive'
1679 ospace = 'Interactive'
1680
1680
1681 return {
1681 return {
1682 'obj':obj,
1682 'obj':obj,
1683 'found':found,
1683 'found':found,
1684 'parent':parent,
1684 'parent':parent,
1685 'ismagic':ismagic,
1685 'ismagic':ismagic,
1686 'isalias':isalias,
1686 'isalias':isalias,
1687 'namespace':ospace
1687 'namespace':ospace
1688 }
1688 }
1689
1689
1690 @staticmethod
1690 @staticmethod
1691 def _getattr_property(obj, attrname):
1691 def _getattr_property(obj, attrname):
1692 """Property-aware getattr to use in object finding.
1692 """Property-aware getattr to use in object finding.
1693
1693
1694 If attrname represents a property, return it unevaluated (in case it has
1694 If attrname represents a property, return it unevaluated (in case it has
1695 side effects or raises an error.
1695 side effects or raises an error.
1696
1696
1697 """
1697 """
1698 if not isinstance(obj, type):
1698 if not isinstance(obj, type):
1699 try:
1699 try:
1700 # `getattr(type(obj), attrname)` is not guaranteed to return
1700 # `getattr(type(obj), attrname)` is not guaranteed to return
1701 # `obj`, but does so for property:
1701 # `obj`, but does so for property:
1702 #
1702 #
1703 # property.__get__(self, None, cls) -> self
1703 # property.__get__(self, None, cls) -> self
1704 #
1704 #
1705 # The universal alternative is to traverse the mro manually
1705 # The universal alternative is to traverse the mro manually
1706 # searching for attrname in class dicts.
1706 # searching for attrname in class dicts.
1707 attr = getattr(type(obj), attrname)
1707 attr = getattr(type(obj), attrname)
1708 except AttributeError:
1708 except AttributeError:
1709 pass
1709 pass
1710 else:
1710 else:
1711 # This relies on the fact that data descriptors (with both
1711 # This relies on the fact that data descriptors (with both
1712 # __get__ & __set__ magic methods) take precedence over
1712 # __get__ & __set__ magic methods) take precedence over
1713 # instance-level attributes:
1713 # instance-level attributes:
1714 #
1714 #
1715 # class A(object):
1715 # class A(object):
1716 # @property
1716 # @property
1717 # def foobar(self): return 123
1717 # def foobar(self): return 123
1718 # a = A()
1718 # a = A()
1719 # a.__dict__['foobar'] = 345
1719 # a.__dict__['foobar'] = 345
1720 # a.foobar # == 123
1720 # a.foobar # == 123
1721 #
1721 #
1722 # So, a property may be returned right away.
1722 # So, a property may be returned right away.
1723 if isinstance(attr, property):
1723 if isinstance(attr, property):
1724 return attr
1724 return attr
1725
1725
1726 # Nothing helped, fall back.
1726 # Nothing helped, fall back.
1727 return getattr(obj, attrname)
1727 return getattr(obj, attrname)
1728
1728
1729 def _object_find(self, oname, namespaces=None):
1729 def _object_find(self, oname, namespaces=None):
1730 """Find an object and return a struct with info about it."""
1730 """Find an object and return a struct with info about it."""
1731 return Struct(self._ofind(oname, namespaces))
1731 return Struct(self._ofind(oname, namespaces))
1732
1732
1733 def _inspect(self, meth, oname, namespaces=None, **kw):
1733 def _inspect(self, meth, oname, namespaces=None, **kw):
1734 """Generic interface to the inspector system.
1734 """Generic interface to the inspector system.
1735
1735
1736 This function is meant to be called by pdef, pdoc & friends.
1736 This function is meant to be called by pdef, pdoc & friends.
1737 """
1737 """
1738 info = self._object_find(oname, namespaces)
1738 info = self._object_find(oname, namespaces)
1739 docformat = sphinxify if self.sphinxify_docstring else None
1739 docformat = sphinxify if self.sphinxify_docstring else None
1740 if info.found:
1740 if info.found:
1741 pmethod = getattr(self.inspector, meth)
1741 pmethod = getattr(self.inspector, meth)
1742 # TODO: only apply format_screen to the plain/text repr of the mime
1742 # TODO: only apply format_screen to the plain/text repr of the mime
1743 # bundle.
1743 # bundle.
1744 formatter = format_screen if info.ismagic else docformat
1744 formatter = format_screen if info.ismagic else docformat
1745 if meth == 'pdoc':
1745 if meth == 'pdoc':
1746 pmethod(info.obj, oname, formatter)
1746 pmethod(info.obj, oname, formatter)
1747 elif meth == 'pinfo':
1747 elif meth == 'pinfo':
1748 pmethod(info.obj, oname, formatter, info,
1748 pmethod(info.obj, oname, formatter, info,
1749 enable_html_pager=self.enable_html_pager, **kw)
1749 enable_html_pager=self.enable_html_pager, **kw)
1750 else:
1750 else:
1751 pmethod(info.obj, oname)
1751 pmethod(info.obj, oname)
1752 else:
1752 else:
1753 print('Object `%s` not found.' % oname)
1753 print('Object `%s` not found.' % oname)
1754 return 'not found' # so callers can take other action
1754 return 'not found' # so callers can take other action
1755
1755
1756 def object_inspect(self, oname, detail_level=0):
1756 def object_inspect(self, oname, detail_level=0):
1757 """Get object info about oname"""
1757 """Get object info about oname"""
1758 with self.builtin_trap:
1758 with self.builtin_trap:
1759 info = self._object_find(oname)
1759 info = self._object_find(oname)
1760 if info.found:
1760 if info.found:
1761 return self.inspector.info(info.obj, oname, info=info,
1761 return self.inspector.info(info.obj, oname, info=info,
1762 detail_level=detail_level
1762 detail_level=detail_level
1763 )
1763 )
1764 else:
1764 else:
1765 return oinspect.object_info(name=oname, found=False)
1765 return oinspect.object_info(name=oname, found=False)
1766
1766
1767 def object_inspect_text(self, oname, detail_level=0):
1767 def object_inspect_text(self, oname, detail_level=0):
1768 """Get object info as formatted text"""
1768 """Get object info as formatted text"""
1769 return self.object_inspect_mime(oname, detail_level)['text/plain']
1769 return self.object_inspect_mime(oname, detail_level)['text/plain']
1770
1770
1771 def object_inspect_mime(self, oname, detail_level=0):
1771 def object_inspect_mime(self, oname, detail_level=0):
1772 """Get object info as a mimebundle of formatted representations.
1772 """Get object info as a mimebundle of formatted representations.
1773
1773
1774 A mimebundle is a dictionary, keyed by mime-type.
1774 A mimebundle is a dictionary, keyed by mime-type.
1775 It must always have the key `'text/plain'`.
1775 It must always have the key `'text/plain'`.
1776 """
1776 """
1777 with self.builtin_trap:
1777 with self.builtin_trap:
1778 info = self._object_find(oname)
1778 info = self._object_find(oname)
1779 if info.found:
1779 if info.found:
1780 return self.inspector._get_info(info.obj, oname, info=info,
1780 return self.inspector._get_info(info.obj, oname, info=info,
1781 detail_level=detail_level
1781 detail_level=detail_level
1782 )
1782 )
1783 else:
1783 else:
1784 raise KeyError(oname)
1784 raise KeyError(oname)
1785
1785
1786 #-------------------------------------------------------------------------
1786 #-------------------------------------------------------------------------
1787 # Things related to history management
1787 # Things related to history management
1788 #-------------------------------------------------------------------------
1788 #-------------------------------------------------------------------------
1789
1789
1790 def init_history(self):
1790 def init_history(self):
1791 """Sets up the command history, and starts regular autosaves."""
1791 """Sets up the command history, and starts regular autosaves."""
1792 self.history_manager = HistoryManager(shell=self, parent=self)
1792 self.history_manager = HistoryManager(shell=self, parent=self)
1793 self.configurables.append(self.history_manager)
1793 self.configurables.append(self.history_manager)
1794
1794
1795 #-------------------------------------------------------------------------
1795 #-------------------------------------------------------------------------
1796 # Things related to exception handling and tracebacks (not debugging)
1796 # Things related to exception handling and tracebacks (not debugging)
1797 #-------------------------------------------------------------------------
1797 #-------------------------------------------------------------------------
1798
1798
1799 debugger_cls = Pdb
1799 debugger_cls = Pdb
1800
1800
1801 def init_traceback_handlers(self, custom_exceptions):
1801 def init_traceback_handlers(self, custom_exceptions):
1802 # Syntax error handler.
1802 # Syntax error handler.
1803 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self)
1803 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self)
1804
1804
1805 # The interactive one is initialized with an offset, meaning we always
1805 # The interactive one is initialized with an offset, meaning we always
1806 # want to remove the topmost item in the traceback, which is our own
1806 # want to remove the topmost item in the traceback, which is our own
1807 # internal code. Valid modes: ['Plain','Context','Verbose','Minimal']
1807 # internal code. Valid modes: ['Plain','Context','Verbose','Minimal']
1808 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1808 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1809 color_scheme='NoColor',
1809 color_scheme='NoColor',
1810 tb_offset = 1,
1810 tb_offset = 1,
1811 check_cache=check_linecache_ipython,
1811 check_cache=check_linecache_ipython,
1812 debugger_cls=self.debugger_cls, parent=self)
1812 debugger_cls=self.debugger_cls, parent=self)
1813
1813
1814 # The instance will store a pointer to the system-wide exception hook,
1814 # The instance will store a pointer to the system-wide exception hook,
1815 # so that runtime code (such as magics) can access it. This is because
1815 # so that runtime code (such as magics) can access it. This is because
1816 # during the read-eval loop, it may get temporarily overwritten.
1816 # during the read-eval loop, it may get temporarily overwritten.
1817 self.sys_excepthook = sys.excepthook
1817 self.sys_excepthook = sys.excepthook
1818
1818
1819 # and add any custom exception handlers the user may have specified
1819 # and add any custom exception handlers the user may have specified
1820 self.set_custom_exc(*custom_exceptions)
1820 self.set_custom_exc(*custom_exceptions)
1821
1821
1822 # Set the exception mode
1822 # Set the exception mode
1823 self.InteractiveTB.set_mode(mode=self.xmode)
1823 self.InteractiveTB.set_mode(mode=self.xmode)
1824
1824
1825 def set_custom_exc(self, exc_tuple, handler):
1825 def set_custom_exc(self, exc_tuple, handler):
1826 """set_custom_exc(exc_tuple, handler)
1826 """set_custom_exc(exc_tuple, handler)
1827
1827
1828 Set a custom exception handler, which will be called if any of the
1828 Set a custom exception handler, which will be called if any of the
1829 exceptions in exc_tuple occur in the mainloop (specifically, in the
1829 exceptions in exc_tuple occur in the mainloop (specifically, in the
1830 run_code() method).
1830 run_code() method).
1831
1831
1832 Parameters
1832 Parameters
1833 ----------
1833 ----------
1834
1834
1835 exc_tuple : tuple of exception classes
1835 exc_tuple : tuple of exception classes
1836 A *tuple* of exception classes, for which to call the defined
1836 A *tuple* of exception classes, for which to call the defined
1837 handler. It is very important that you use a tuple, and NOT A
1837 handler. It is very important that you use a tuple, and NOT A
1838 LIST here, because of the way Python's except statement works. If
1838 LIST here, because of the way Python's except statement works. If
1839 you only want to trap a single exception, use a singleton tuple::
1839 you only want to trap a single exception, use a singleton tuple::
1840
1840
1841 exc_tuple == (MyCustomException,)
1841 exc_tuple == (MyCustomException,)
1842
1842
1843 handler : callable
1843 handler : callable
1844 handler must have the following signature::
1844 handler must have the following signature::
1845
1845
1846 def my_handler(self, etype, value, tb, tb_offset=None):
1846 def my_handler(self, etype, value, tb, tb_offset=None):
1847 ...
1847 ...
1848 return structured_traceback
1848 return structured_traceback
1849
1849
1850 Your handler must return a structured traceback (a list of strings),
1850 Your handler must return a structured traceback (a list of strings),
1851 or None.
1851 or None.
1852
1852
1853 This will be made into an instance method (via types.MethodType)
1853 This will be made into an instance method (via types.MethodType)
1854 of IPython itself, and it will be called if any of the exceptions
1854 of IPython itself, and it will be called if any of the exceptions
1855 listed in the exc_tuple are caught. If the handler is None, an
1855 listed in the exc_tuple are caught. If the handler is None, an
1856 internal basic one is used, which just prints basic info.
1856 internal basic one is used, which just prints basic info.
1857
1857
1858 To protect IPython from crashes, if your handler ever raises an
1858 To protect IPython from crashes, if your handler ever raises an
1859 exception or returns an invalid result, it will be immediately
1859 exception or returns an invalid result, it will be immediately
1860 disabled.
1860 disabled.
1861
1861
1862 WARNING: by putting in your own exception handler into IPython's main
1862 WARNING: by putting in your own exception handler into IPython's main
1863 execution loop, you run a very good chance of nasty crashes. This
1863 execution loop, you run a very good chance of nasty crashes. This
1864 facility should only be used if you really know what you are doing."""
1864 facility should only be used if you really know what you are doing."""
1865 if not isinstance(exc_tuple, tuple):
1865 if not isinstance(exc_tuple, tuple):
1866 raise TypeError("The custom exceptions must be given as a tuple.")
1866 raise TypeError("The custom exceptions must be given as a tuple.")
1867
1867
1868 def dummy_handler(self, etype, value, tb, tb_offset=None):
1868 def dummy_handler(self, etype, value, tb, tb_offset=None):
1869 print('*** Simple custom exception handler ***')
1869 print('*** Simple custom exception handler ***')
1870 print('Exception type :', etype)
1870 print('Exception type :', etype)
1871 print('Exception value:', value)
1871 print('Exception value:', value)
1872 print('Traceback :', tb)
1872 print('Traceback :', tb)
1873
1873
1874 def validate_stb(stb):
1874 def validate_stb(stb):
1875 """validate structured traceback return type
1875 """validate structured traceback return type
1876
1876
1877 return type of CustomTB *should* be a list of strings, but allow
1877 return type of CustomTB *should* be a list of strings, but allow
1878 single strings or None, which are harmless.
1878 single strings or None, which are harmless.
1879
1879
1880 This function will *always* return a list of strings,
1880 This function will *always* return a list of strings,
1881 and will raise a TypeError if stb is inappropriate.
1881 and will raise a TypeError if stb is inappropriate.
1882 """
1882 """
1883 msg = "CustomTB must return list of strings, not %r" % stb
1883 msg = "CustomTB must return list of strings, not %r" % stb
1884 if stb is None:
1884 if stb is None:
1885 return []
1885 return []
1886 elif isinstance(stb, str):
1886 elif isinstance(stb, str):
1887 return [stb]
1887 return [stb]
1888 elif not isinstance(stb, list):
1888 elif not isinstance(stb, list):
1889 raise TypeError(msg)
1889 raise TypeError(msg)
1890 # it's a list
1890 # it's a list
1891 for line in stb:
1891 for line in stb:
1892 # check every element
1892 # check every element
1893 if not isinstance(line, str):
1893 if not isinstance(line, str):
1894 raise TypeError(msg)
1894 raise TypeError(msg)
1895 return stb
1895 return stb
1896
1896
1897 if handler is None:
1897 if handler is None:
1898 wrapped = dummy_handler
1898 wrapped = dummy_handler
1899 else:
1899 else:
1900 def wrapped(self,etype,value,tb,tb_offset=None):
1900 def wrapped(self,etype,value,tb,tb_offset=None):
1901 """wrap CustomTB handler, to protect IPython from user code
1901 """wrap CustomTB handler, to protect IPython from user code
1902
1902
1903 This makes it harder (but not impossible) for custom exception
1903 This makes it harder (but not impossible) for custom exception
1904 handlers to crash IPython.
1904 handlers to crash IPython.
1905 """
1905 """
1906 try:
1906 try:
1907 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1907 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1908 return validate_stb(stb)
1908 return validate_stb(stb)
1909 except:
1909 except:
1910 # clear custom handler immediately
1910 # clear custom handler immediately
1911 self.set_custom_exc((), None)
1911 self.set_custom_exc((), None)
1912 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1912 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1913 # show the exception in handler first
1913 # show the exception in handler first
1914 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1914 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1915 print(self.InteractiveTB.stb2text(stb))
1915 print(self.InteractiveTB.stb2text(stb))
1916 print("The original exception:")
1916 print("The original exception:")
1917 stb = self.InteractiveTB.structured_traceback(
1917 stb = self.InteractiveTB.structured_traceback(
1918 (etype,value,tb), tb_offset=tb_offset
1918 (etype,value,tb), tb_offset=tb_offset
1919 )
1919 )
1920 return stb
1920 return stb
1921
1921
1922 self.CustomTB = types.MethodType(wrapped,self)
1922 self.CustomTB = types.MethodType(wrapped,self)
1923 self.custom_exceptions = exc_tuple
1923 self.custom_exceptions = exc_tuple
1924
1924
1925 def excepthook(self, etype, value, tb):
1925 def excepthook(self, etype, value, tb):
1926 """One more defense for GUI apps that call sys.excepthook.
1926 """One more defense for GUI apps that call sys.excepthook.
1927
1927
1928 GUI frameworks like wxPython trap exceptions and call
1928 GUI frameworks like wxPython trap exceptions and call
1929 sys.excepthook themselves. I guess this is a feature that
1929 sys.excepthook themselves. I guess this is a feature that
1930 enables them to keep running after exceptions that would
1930 enables them to keep running after exceptions that would
1931 otherwise kill their mainloop. This is a bother for IPython
1931 otherwise kill their mainloop. This is a bother for IPython
1932 which excepts to catch all of the program exceptions with a try:
1932 which excepts to catch all of the program exceptions with a try:
1933 except: statement.
1933 except: statement.
1934
1934
1935 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1935 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1936 any app directly invokes sys.excepthook, it will look to the user like
1936 any app directly invokes sys.excepthook, it will look to the user like
1937 IPython crashed. In order to work around this, we can disable the
1937 IPython crashed. In order to work around this, we can disable the
1938 CrashHandler and replace it with this excepthook instead, which prints a
1938 CrashHandler and replace it with this excepthook instead, which prints a
1939 regular traceback using our InteractiveTB. In this fashion, apps which
1939 regular traceback using our InteractiveTB. In this fashion, apps which
1940 call sys.excepthook will generate a regular-looking exception from
1940 call sys.excepthook will generate a regular-looking exception from
1941 IPython, and the CrashHandler will only be triggered by real IPython
1941 IPython, and the CrashHandler will only be triggered by real IPython
1942 crashes.
1942 crashes.
1943
1943
1944 This hook should be used sparingly, only in places which are not likely
1944 This hook should be used sparingly, only in places which are not likely
1945 to be true IPython errors.
1945 to be true IPython errors.
1946 """
1946 """
1947 self.showtraceback((etype, value, tb), tb_offset=0)
1947 self.showtraceback((etype, value, tb), tb_offset=0)
1948
1948
1949 def _get_exc_info(self, exc_tuple=None):
1949 def _get_exc_info(self, exc_tuple=None):
1950 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1950 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1951
1951
1952 Ensures sys.last_type,value,traceback hold the exc_info we found,
1952 Ensures sys.last_type,value,traceback hold the exc_info we found,
1953 from whichever source.
1953 from whichever source.
1954
1954
1955 raises ValueError if none of these contain any information
1955 raises ValueError if none of these contain any information
1956 """
1956 """
1957 if exc_tuple is None:
1957 if exc_tuple is None:
1958 etype, value, tb = sys.exc_info()
1958 etype, value, tb = sys.exc_info()
1959 else:
1959 else:
1960 etype, value, tb = exc_tuple
1960 etype, value, tb = exc_tuple
1961
1961
1962 if etype is None:
1962 if etype is None:
1963 if hasattr(sys, 'last_type'):
1963 if hasattr(sys, 'last_type'):
1964 etype, value, tb = sys.last_type, sys.last_value, \
1964 etype, value, tb = sys.last_type, sys.last_value, \
1965 sys.last_traceback
1965 sys.last_traceback
1966
1966
1967 if etype is None:
1967 if etype is None:
1968 raise ValueError("No exception to find")
1968 raise ValueError("No exception to find")
1969
1969
1970 # Now store the exception info in sys.last_type etc.
1970 # Now store the exception info in sys.last_type etc.
1971 # WARNING: these variables are somewhat deprecated and not
1971 # WARNING: these variables are somewhat deprecated and not
1972 # necessarily safe to use in a threaded environment, but tools
1972 # necessarily safe to use in a threaded environment, but tools
1973 # like pdb depend on their existence, so let's set them. If we
1973 # like pdb depend on their existence, so let's set them. If we
1974 # find problems in the field, we'll need to revisit their use.
1974 # find problems in the field, we'll need to revisit their use.
1975 sys.last_type = etype
1975 sys.last_type = etype
1976 sys.last_value = value
1976 sys.last_value = value
1977 sys.last_traceback = tb
1977 sys.last_traceback = tb
1978
1978
1979 return etype, value, tb
1979 return etype, value, tb
1980
1980
1981 def show_usage_error(self, exc):
1981 def show_usage_error(self, exc):
1982 """Show a short message for UsageErrors
1982 """Show a short message for UsageErrors
1983
1983
1984 These are special exceptions that shouldn't show a traceback.
1984 These are special exceptions that shouldn't show a traceback.
1985 """
1985 """
1986 print("UsageError: %s" % exc, file=sys.stderr)
1986 print("UsageError: %s" % exc, file=sys.stderr)
1987
1987
1988 def get_exception_only(self, exc_tuple=None):
1988 def get_exception_only(self, exc_tuple=None):
1989 """
1989 """
1990 Return as a string (ending with a newline) the exception that
1990 Return as a string (ending with a newline) the exception that
1991 just occurred, without any traceback.
1991 just occurred, without any traceback.
1992 """
1992 """
1993 etype, value, tb = self._get_exc_info(exc_tuple)
1993 etype, value, tb = self._get_exc_info(exc_tuple)
1994 msg = traceback.format_exception_only(etype, value)
1994 msg = traceback.format_exception_only(etype, value)
1995 return ''.join(msg)
1995 return ''.join(msg)
1996
1996
1997 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1997 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1998 exception_only=False, running_compiled_code=False):
1998 exception_only=False, running_compiled_code=False):
1999 """Display the exception that just occurred.
1999 """Display the exception that just occurred.
2000
2000
2001 If nothing is known about the exception, this is the method which
2001 If nothing is known about the exception, this is the method which
2002 should be used throughout the code for presenting user tracebacks,
2002 should be used throughout the code for presenting user tracebacks,
2003 rather than directly invoking the InteractiveTB object.
2003 rather than directly invoking the InteractiveTB object.
2004
2004
2005 A specific showsyntaxerror() also exists, but this method can take
2005 A specific showsyntaxerror() also exists, but this method can take
2006 care of calling it if needed, so unless you are explicitly catching a
2006 care of calling it if needed, so unless you are explicitly catching a
2007 SyntaxError exception, don't try to analyze the stack manually and
2007 SyntaxError exception, don't try to analyze the stack manually and
2008 simply call this method."""
2008 simply call this method."""
2009
2009
2010 try:
2010 try:
2011 try:
2011 try:
2012 etype, value, tb = self._get_exc_info(exc_tuple)
2012 etype, value, tb = self._get_exc_info(exc_tuple)
2013 except ValueError:
2013 except ValueError:
2014 print('No traceback available to show.', file=sys.stderr)
2014 print('No traceback available to show.', file=sys.stderr)
2015 return
2015 return
2016
2016
2017 if issubclass(etype, SyntaxError):
2017 if issubclass(etype, SyntaxError):
2018 # Though this won't be called by syntax errors in the input
2018 # Though this won't be called by syntax errors in the input
2019 # line, there may be SyntaxError cases with imported code.
2019 # line, there may be SyntaxError cases with imported code.
2020 self.showsyntaxerror(filename, running_compiled_code)
2020 self.showsyntaxerror(filename, running_compiled_code)
2021 elif etype is UsageError:
2021 elif etype is UsageError:
2022 self.show_usage_error(value)
2022 self.show_usage_error(value)
2023 else:
2023 else:
2024 if exception_only:
2024 if exception_only:
2025 stb = ['An exception has occurred, use %tb to see '
2025 stb = ['An exception has occurred, use %tb to see '
2026 'the full traceback.\n']
2026 'the full traceback.\n']
2027 stb.extend(self.InteractiveTB.get_exception_only(etype,
2027 stb.extend(self.InteractiveTB.get_exception_only(etype,
2028 value))
2028 value))
2029 else:
2029 else:
2030 try:
2030 try:
2031 # Exception classes can customise their traceback - we
2031 # Exception classes can customise their traceback - we
2032 # use this in IPython.parallel for exceptions occurring
2032 # use this in IPython.parallel for exceptions occurring
2033 # in the engines. This should return a list of strings.
2033 # in the engines. This should return a list of strings.
2034 stb = value._render_traceback_()
2034 stb = value._render_traceback_()
2035 except Exception:
2035 except Exception:
2036 stb = self.InteractiveTB.structured_traceback(etype,
2036 stb = self.InteractiveTB.structured_traceback(etype,
2037 value, tb, tb_offset=tb_offset)
2037 value, tb, tb_offset=tb_offset)
2038
2038
2039 self._showtraceback(etype, value, stb)
2039 self._showtraceback(etype, value, stb)
2040 if self.call_pdb:
2040 if self.call_pdb:
2041 # drop into debugger
2041 # drop into debugger
2042 self.debugger(force=True)
2042 self.debugger(force=True)
2043 return
2043 return
2044
2044
2045 # Actually show the traceback
2045 # Actually show the traceback
2046 self._showtraceback(etype, value, stb)
2046 self._showtraceback(etype, value, stb)
2047
2047
2048 except KeyboardInterrupt:
2048 except KeyboardInterrupt:
2049 print('\n' + self.get_exception_only(), file=sys.stderr)
2049 print('\n' + self.get_exception_only(), file=sys.stderr)
2050
2050
2051 def _showtraceback(self, etype, evalue, stb):
2051 def _showtraceback(self, etype, evalue, stb):
2052 """Actually show a traceback.
2052 """Actually show a traceback.
2053
2053
2054 Subclasses may override this method to put the traceback on a different
2054 Subclasses may override this method to put the traceback on a different
2055 place, like a side channel.
2055 place, like a side channel.
2056 """
2056 """
2057 print(self.InteractiveTB.stb2text(stb))
2057 print(self.InteractiveTB.stb2text(stb))
2058
2058
2059 def showsyntaxerror(self, filename=None, running_compiled_code=False):
2059 def showsyntaxerror(self, filename=None, running_compiled_code=False):
2060 """Display the syntax error that just occurred.
2060 """Display the syntax error that just occurred.
2061
2061
2062 This doesn't display a stack trace because there isn't one.
2062 This doesn't display a stack trace because there isn't one.
2063
2063
2064 If a filename is given, it is stuffed in the exception instead
2064 If a filename is given, it is stuffed in the exception instead
2065 of what was there before (because Python's parser always uses
2065 of what was there before (because Python's parser always uses
2066 "<string>" when reading from a string).
2066 "<string>" when reading from a string).
2067
2067
2068 If the syntax error occurred when running a compiled code (i.e. running_compile_code=True),
2068 If the syntax error occurred when running a compiled code (i.e. running_compile_code=True),
2069 longer stack trace will be displayed.
2069 longer stack trace will be displayed.
2070 """
2070 """
2071 etype, value, last_traceback = self._get_exc_info()
2071 etype, value, last_traceback = self._get_exc_info()
2072
2072
2073 if filename and issubclass(etype, SyntaxError):
2073 if filename and issubclass(etype, SyntaxError):
2074 try:
2074 try:
2075 value.filename = filename
2075 value.filename = filename
2076 except:
2076 except:
2077 # Not the format we expect; leave it alone
2077 # Not the format we expect; leave it alone
2078 pass
2078 pass
2079
2079
2080 # If the error occurred when executing compiled code, we should provide full stacktrace.
2080 # If the error occurred when executing compiled code, we should provide full stacktrace.
2081 elist = traceback.extract_tb(last_traceback) if running_compiled_code else []
2081 elist = traceback.extract_tb(last_traceback) if running_compiled_code else []
2082 stb = self.SyntaxTB.structured_traceback(etype, value, elist)
2082 stb = self.SyntaxTB.structured_traceback(etype, value, elist)
2083 self._showtraceback(etype, value, stb)
2083 self._showtraceback(etype, value, stb)
2084
2084
2085 # This is overridden in TerminalInteractiveShell to show a message about
2085 # This is overridden in TerminalInteractiveShell to show a message about
2086 # the %paste magic.
2086 # the %paste magic.
2087 def showindentationerror(self):
2087 def showindentationerror(self):
2088 """Called by _run_cell when there's an IndentationError in code entered
2088 """Called by _run_cell when there's an IndentationError in code entered
2089 at the prompt.
2089 at the prompt.
2090
2090
2091 This is overridden in TerminalInteractiveShell to show a message about
2091 This is overridden in TerminalInteractiveShell to show a message about
2092 the %paste magic."""
2092 the %paste magic."""
2093 self.showsyntaxerror()
2093 self.showsyntaxerror()
2094
2094
2095 #-------------------------------------------------------------------------
2095 #-------------------------------------------------------------------------
2096 # Things related to readline
2096 # Things related to readline
2097 #-------------------------------------------------------------------------
2097 #-------------------------------------------------------------------------
2098
2098
2099 def init_readline(self):
2099 def init_readline(self):
2100 """DEPRECATED
2100 """DEPRECATED
2101
2101
2102 Moved to terminal subclass, here only to simplify the init logic."""
2102 Moved to terminal subclass, here only to simplify the init logic."""
2103 # Set a number of methods that depend on readline to be no-op
2103 # Set a number of methods that depend on readline to be no-op
2104 warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated',
2104 warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated',
2105 DeprecationWarning, stacklevel=2)
2105 DeprecationWarning, stacklevel=2)
2106 self.set_custom_completer = no_op
2106 self.set_custom_completer = no_op
2107
2107
2108 @skip_doctest
2108 @skip_doctest
2109 def set_next_input(self, s, replace=False):
2109 def set_next_input(self, s, replace=False):
2110 """ Sets the 'default' input string for the next command line.
2110 """ Sets the 'default' input string for the next command line.
2111
2111
2112 Example::
2112 Example::
2113
2113
2114 In [1]: _ip.set_next_input("Hello Word")
2114 In [1]: _ip.set_next_input("Hello Word")
2115 In [2]: Hello Word_ # cursor is here
2115 In [2]: Hello Word_ # cursor is here
2116 """
2116 """
2117 self.rl_next_input = s
2117 self.rl_next_input = s
2118
2118
2119 def _indent_current_str(self):
2119 def _indent_current_str(self):
2120 """return the current level of indentation as a string"""
2120 """return the current level of indentation as a string"""
2121 return self.input_splitter.get_indent_spaces() * ' '
2121 return self.input_splitter.get_indent_spaces() * ' '
2122
2122
2123 #-------------------------------------------------------------------------
2123 #-------------------------------------------------------------------------
2124 # Things related to text completion
2124 # Things related to text completion
2125 #-------------------------------------------------------------------------
2125 #-------------------------------------------------------------------------
2126
2126
2127 def init_completer(self):
2127 def init_completer(self):
2128 """Initialize the completion machinery.
2128 """Initialize the completion machinery.
2129
2129
2130 This creates completion machinery that can be used by client code,
2130 This creates completion machinery that can be used by client code,
2131 either interactively in-process (typically triggered by the readline
2131 either interactively in-process (typically triggered by the readline
2132 library), programmatically (such as in test suites) or out-of-process
2132 library), programmatically (such as in test suites) or out-of-process
2133 (typically over the network by remote frontends).
2133 (typically over the network by remote frontends).
2134 """
2134 """
2135 from IPython.core.completer import IPCompleter
2135 from IPython.core.completer import IPCompleter
2136 from IPython.core.completerlib import (module_completer,
2136 from IPython.core.completerlib import (module_completer,
2137 magic_run_completer, cd_completer, reset_completer)
2137 magic_run_completer, cd_completer, reset_completer)
2138
2138
2139 self.Completer = IPCompleter(shell=self,
2139 self.Completer = IPCompleter(shell=self,
2140 namespace=self.user_ns,
2140 namespace=self.user_ns,
2141 global_namespace=self.user_global_ns,
2141 global_namespace=self.user_global_ns,
2142 parent=self,
2142 parent=self,
2143 )
2143 )
2144 self.configurables.append(self.Completer)
2144 self.configurables.append(self.Completer)
2145
2145
2146 # Add custom completers to the basic ones built into IPCompleter
2146 # Add custom completers to the basic ones built into IPCompleter
2147 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
2147 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
2148 self.strdispatchers['complete_command'] = sdisp
2148 self.strdispatchers['complete_command'] = sdisp
2149 self.Completer.custom_completers = sdisp
2149 self.Completer.custom_completers = sdisp
2150
2150
2151 self.set_hook('complete_command', module_completer, str_key = 'import')
2151 self.set_hook('complete_command', module_completer, str_key = 'import')
2152 self.set_hook('complete_command', module_completer, str_key = 'from')
2152 self.set_hook('complete_command', module_completer, str_key = 'from')
2153 self.set_hook('complete_command', module_completer, str_key = '%aimport')
2153 self.set_hook('complete_command', module_completer, str_key = '%aimport')
2154 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
2154 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
2155 self.set_hook('complete_command', cd_completer, str_key = '%cd')
2155 self.set_hook('complete_command', cd_completer, str_key = '%cd')
2156 self.set_hook('complete_command', reset_completer, str_key = '%reset')
2156 self.set_hook('complete_command', reset_completer, str_key = '%reset')
2157
2157
2158 @skip_doctest
2158 @skip_doctest
2159 def complete(self, text, line=None, cursor_pos=None):
2159 def complete(self, text, line=None, cursor_pos=None):
2160 """Return the completed text and a list of completions.
2160 """Return the completed text and a list of completions.
2161
2161
2162 Parameters
2162 Parameters
2163 ----------
2163 ----------
2164
2164
2165 text : string
2165 text : string
2166 A string of text to be completed on. It can be given as empty and
2166 A string of text to be completed on. It can be given as empty and
2167 instead a line/position pair are given. In this case, the
2167 instead a line/position pair are given. In this case, the
2168 completer itself will split the line like readline does.
2168 completer itself will split the line like readline does.
2169
2169
2170 line : string, optional
2170 line : string, optional
2171 The complete line that text is part of.
2171 The complete line that text is part of.
2172
2172
2173 cursor_pos : int, optional
2173 cursor_pos : int, optional
2174 The position of the cursor on the input line.
2174 The position of the cursor on the input line.
2175
2175
2176 Returns
2176 Returns
2177 -------
2177 -------
2178 text : string
2178 text : string
2179 The actual text that was completed.
2179 The actual text that was completed.
2180
2180
2181 matches : list
2181 matches : list
2182 A sorted list with all possible completions.
2182 A sorted list with all possible completions.
2183
2183
2184 The optional arguments allow the completion to take more context into
2184 The optional arguments allow the completion to take more context into
2185 account, and are part of the low-level completion API.
2185 account, and are part of the low-level completion API.
2186
2186
2187 This is a wrapper around the completion mechanism, similar to what
2187 This is a wrapper around the completion mechanism, similar to what
2188 readline does at the command line when the TAB key is hit. By
2188 readline does at the command line when the TAB key is hit. By
2189 exposing it as a method, it can be used by other non-readline
2189 exposing it as a method, it can be used by other non-readline
2190 environments (such as GUIs) for text completion.
2190 environments (such as GUIs) for text completion.
2191
2191
2192 Simple usage example:
2192 Simple usage example:
2193
2193
2194 In [1]: x = 'hello'
2194 In [1]: x = 'hello'
2195
2195
2196 In [2]: _ip.complete('x.l')
2196 In [2]: _ip.complete('x.l')
2197 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
2197 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
2198 """
2198 """
2199
2199
2200 # Inject names into __builtin__ so we can complete on the added names.
2200 # Inject names into __builtin__ so we can complete on the added names.
2201 with self.builtin_trap:
2201 with self.builtin_trap:
2202 return self.Completer.complete(text, line, cursor_pos)
2202 return self.Completer.complete(text, line, cursor_pos)
2203
2203
2204 def set_custom_completer(self, completer, pos=0):
2204 def set_custom_completer(self, completer, pos=0):
2205 """Adds a new custom completer function.
2205 """Adds a new custom completer function.
2206
2206
2207 The position argument (defaults to 0) is the index in the completers
2207 The position argument (defaults to 0) is the index in the completers
2208 list where you want the completer to be inserted."""
2208 list where you want the completer to be inserted."""
2209
2209
2210 newcomp = types.MethodType(completer,self.Completer)
2210 newcomp = types.MethodType(completer,self.Completer)
2211 self.Completer.matchers.insert(pos,newcomp)
2211 self.Completer.matchers.insert(pos,newcomp)
2212
2212
2213 def set_completer_frame(self, frame=None):
2213 def set_completer_frame(self, frame=None):
2214 """Set the frame of the completer."""
2214 """Set the frame of the completer."""
2215 if frame:
2215 if frame:
2216 self.Completer.namespace = frame.f_locals
2216 self.Completer.namespace = frame.f_locals
2217 self.Completer.global_namespace = frame.f_globals
2217 self.Completer.global_namespace = frame.f_globals
2218 else:
2218 else:
2219 self.Completer.namespace = self.user_ns
2219 self.Completer.namespace = self.user_ns
2220 self.Completer.global_namespace = self.user_global_ns
2220 self.Completer.global_namespace = self.user_global_ns
2221
2221
2222 #-------------------------------------------------------------------------
2222 #-------------------------------------------------------------------------
2223 # Things related to magics
2223 # Things related to magics
2224 #-------------------------------------------------------------------------
2224 #-------------------------------------------------------------------------
2225
2225
2226 def init_magics(self):
2226 def init_magics(self):
2227 from IPython.core import magics as m
2227 from IPython.core import magics as m
2228 self.magics_manager = magic.MagicsManager(shell=self,
2228 self.magics_manager = magic.MagicsManager(shell=self,
2229 parent=self,
2229 parent=self,
2230 user_magics=m.UserMagics(self))
2230 user_magics=m.UserMagics(self))
2231 self.configurables.append(self.magics_manager)
2231 self.configurables.append(self.magics_manager)
2232
2232
2233 # Expose as public API from the magics manager
2233 # Expose as public API from the magics manager
2234 self.register_magics = self.magics_manager.register
2234 self.register_magics = self.magics_manager.register
2235
2235
2236 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2236 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2237 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
2237 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
2238 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2238 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2239 m.NamespaceMagics, m.OSMagics, m.PackagingMagics,
2239 m.NamespaceMagics, m.OSMagics, m.PackagingMagics,
2240 m.PylabMagics, m.ScriptMagics,
2240 m.PylabMagics, m.ScriptMagics,
2241 )
2241 )
2242 self.register_magics(m.AsyncMagics)
2242 self.register_magics(m.AsyncMagics)
2243
2243
2244 # Register Magic Aliases
2244 # Register Magic Aliases
2245 mman = self.magics_manager
2245 mman = self.magics_manager
2246 # FIXME: magic aliases should be defined by the Magics classes
2246 # FIXME: magic aliases should be defined by the Magics classes
2247 # or in MagicsManager, not here
2247 # or in MagicsManager, not here
2248 mman.register_alias('ed', 'edit')
2248 mman.register_alias('ed', 'edit')
2249 mman.register_alias('hist', 'history')
2249 mman.register_alias('hist', 'history')
2250 mman.register_alias('rep', 'recall')
2250 mman.register_alias('rep', 'recall')
2251 mman.register_alias('SVG', 'svg', 'cell')
2251 mman.register_alias('SVG', 'svg', 'cell')
2252 mman.register_alias('HTML', 'html', 'cell')
2252 mman.register_alias('HTML', 'html', 'cell')
2253 mman.register_alias('file', 'writefile', 'cell')
2253 mman.register_alias('file', 'writefile', 'cell')
2254
2254
2255 # FIXME: Move the color initialization to the DisplayHook, which
2255 # FIXME: Move the color initialization to the DisplayHook, which
2256 # should be split into a prompt manager and displayhook. We probably
2256 # should be split into a prompt manager and displayhook. We probably
2257 # even need a centralize colors management object.
2257 # even need a centralize colors management object.
2258 self.run_line_magic('colors', self.colors)
2258 self.run_line_magic('colors', self.colors)
2259
2259
2260 # Defined here so that it's included in the documentation
2260 # Defined here so that it's included in the documentation
2261 @functools.wraps(magic.MagicsManager.register_function)
2261 @functools.wraps(magic.MagicsManager.register_function)
2262 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2262 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2263 self.magics_manager.register_function(func,
2263 self.magics_manager.register_function(func,
2264 magic_kind=magic_kind, magic_name=magic_name)
2264 magic_kind=magic_kind, magic_name=magic_name)
2265
2265
2266 def run_line_magic(self, magic_name, line, _stack_depth=1):
2266 def run_line_magic(self, magic_name, line, _stack_depth=1):
2267 """Execute the given line magic.
2267 """Execute the given line magic.
2268
2268
2269 Parameters
2269 Parameters
2270 ----------
2270 ----------
2271 magic_name : str
2271 magic_name : str
2272 Name of the desired magic function, without '%' prefix.
2272 Name of the desired magic function, without '%' prefix.
2273
2273
2274 line : str
2274 line : str
2275 The rest of the input line as a single string.
2275 The rest of the input line as a single string.
2276
2276
2277 _stack_depth : int
2277 _stack_depth : int
2278 If run_line_magic() is called from magic() then _stack_depth=2.
2278 If run_line_magic() is called from magic() then _stack_depth=2.
2279 This is added to ensure backward compatibility for use of 'get_ipython().magic()'
2279 This is added to ensure backward compatibility for use of 'get_ipython().magic()'
2280 """
2280 """
2281 fn = self.find_line_magic(magic_name)
2281 fn = self.find_line_magic(magic_name)
2282 if fn is None:
2282 if fn is None:
2283 cm = self.find_cell_magic(magic_name)
2283 cm = self.find_cell_magic(magic_name)
2284 etpl = "Line magic function `%%%s` not found%s."
2284 etpl = "Line magic function `%%%s` not found%s."
2285 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2285 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2286 'did you mean that instead?)' % magic_name )
2286 'did you mean that instead?)' % magic_name )
2287 raise UsageError(etpl % (magic_name, extra))
2287 raise UsageError(etpl % (magic_name, extra))
2288 else:
2288 else:
2289 # Note: this is the distance in the stack to the user's frame.
2289 # Note: this is the distance in the stack to the user's frame.
2290 # This will need to be updated if the internal calling logic gets
2290 # This will need to be updated if the internal calling logic gets
2291 # refactored, or else we'll be expanding the wrong variables.
2291 # refactored, or else we'll be expanding the wrong variables.
2292
2292
2293 # Determine stack_depth depending on where run_line_magic() has been called
2293 # Determine stack_depth depending on where run_line_magic() has been called
2294 stack_depth = _stack_depth
2294 stack_depth = _stack_depth
2295 if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False):
2295 if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False):
2296 # magic has opted out of var_expand
2296 # magic has opted out of var_expand
2297 magic_arg_s = line
2297 magic_arg_s = line
2298 else:
2298 else:
2299 magic_arg_s = self.var_expand(line, stack_depth)
2299 magic_arg_s = self.var_expand(line, stack_depth)
2300 # Put magic args in a list so we can call with f(*a) syntax
2300 # Put magic args in a list so we can call with f(*a) syntax
2301 args = [magic_arg_s]
2301 args = [magic_arg_s]
2302 kwargs = {}
2302 kwargs = {}
2303 # Grab local namespace if we need it:
2303 # Grab local namespace if we need it:
2304 if getattr(fn, "needs_local_scope", False):
2304 if getattr(fn, "needs_local_scope", False):
2305 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2305 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2306 with self.builtin_trap:
2306 with self.builtin_trap:
2307 result = fn(*args, **kwargs)
2307 result = fn(*args, **kwargs)
2308 return result
2308 return result
2309
2309
2310 def run_cell_magic(self, magic_name, line, cell):
2310 def run_cell_magic(self, magic_name, line, cell):
2311 """Execute the given cell magic.
2311 """Execute the given cell magic.
2312
2312
2313 Parameters
2313 Parameters
2314 ----------
2314 ----------
2315 magic_name : str
2315 magic_name : str
2316 Name of the desired magic function, without '%' prefix.
2316 Name of the desired magic function, without '%' prefix.
2317
2317
2318 line : str
2318 line : str
2319 The rest of the first input line as a single string.
2319 The rest of the first input line as a single string.
2320
2320
2321 cell : str
2321 cell : str
2322 The body of the cell as a (possibly multiline) string.
2322 The body of the cell as a (possibly multiline) string.
2323 """
2323 """
2324 fn = self.find_cell_magic(magic_name)
2324 fn = self.find_cell_magic(magic_name)
2325 if fn is None:
2325 if fn is None:
2326 lm = self.find_line_magic(magic_name)
2326 lm = self.find_line_magic(magic_name)
2327 etpl = "Cell magic `%%{0}` not found{1}."
2327 etpl = "Cell magic `%%{0}` not found{1}."
2328 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2328 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2329 'did you mean that instead?)'.format(magic_name))
2329 'did you mean that instead?)'.format(magic_name))
2330 raise UsageError(etpl.format(magic_name, extra))
2330 raise UsageError(etpl.format(magic_name, extra))
2331 elif cell == '':
2331 elif cell == '':
2332 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2332 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2333 if self.find_line_magic(magic_name) is not None:
2333 if self.find_line_magic(magic_name) is not None:
2334 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2334 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2335 raise UsageError(message)
2335 raise UsageError(message)
2336 else:
2336 else:
2337 # Note: this is the distance in the stack to the user's frame.
2337 # Note: this is the distance in the stack to the user's frame.
2338 # This will need to be updated if the internal calling logic gets
2338 # This will need to be updated if the internal calling logic gets
2339 # refactored, or else we'll be expanding the wrong variables.
2339 # refactored, or else we'll be expanding the wrong variables.
2340 stack_depth = 2
2340 stack_depth = 2
2341 if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False):
2341 if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False):
2342 # magic has opted out of var_expand
2342 # magic has opted out of var_expand
2343 magic_arg_s = line
2343 magic_arg_s = line
2344 else:
2344 else:
2345 magic_arg_s = self.var_expand(line, stack_depth)
2345 magic_arg_s = self.var_expand(line, stack_depth)
2346 kwargs = {}
2346 kwargs = {}
2347 if getattr(fn, "needs_local_scope", False):
2347 if getattr(fn, "needs_local_scope", False):
2348 kwargs['local_ns'] = self.user_ns
2348 kwargs['local_ns'] = self.user_ns
2349
2349
2350 with self.builtin_trap:
2350 with self.builtin_trap:
2351 args = (magic_arg_s, cell)
2351 args = (magic_arg_s, cell)
2352 result = fn(*args, **kwargs)
2352 result = fn(*args, **kwargs)
2353 return result
2353 return result
2354
2354
2355 def find_line_magic(self, magic_name):
2355 def find_line_magic(self, magic_name):
2356 """Find and return a line magic by name.
2356 """Find and return a line magic by name.
2357
2357
2358 Returns None if the magic isn't found."""
2358 Returns None if the magic isn't found."""
2359 return self.magics_manager.magics['line'].get(magic_name)
2359 return self.magics_manager.magics['line'].get(magic_name)
2360
2360
2361 def find_cell_magic(self, magic_name):
2361 def find_cell_magic(self, magic_name):
2362 """Find and return a cell magic by name.
2362 """Find and return a cell magic by name.
2363
2363
2364 Returns None if the magic isn't found."""
2364 Returns None if the magic isn't found."""
2365 return self.magics_manager.magics['cell'].get(magic_name)
2365 return self.magics_manager.magics['cell'].get(magic_name)
2366
2366
2367 def find_magic(self, magic_name, magic_kind='line'):
2367 def find_magic(self, magic_name, magic_kind='line'):
2368 """Find and return a magic of the given type by name.
2368 """Find and return a magic of the given type by name.
2369
2369
2370 Returns None if the magic isn't found."""
2370 Returns None if the magic isn't found."""
2371 return self.magics_manager.magics[magic_kind].get(magic_name)
2371 return self.magics_manager.magics[magic_kind].get(magic_name)
2372
2372
2373 def magic(self, arg_s):
2373 def magic(self, arg_s):
2374 """DEPRECATED. Use run_line_magic() instead.
2374 """DEPRECATED. Use run_line_magic() instead.
2375
2375
2376 Call a magic function by name.
2376 Call a magic function by name.
2377
2377
2378 Input: a string containing the name of the magic function to call and
2378 Input: a string containing the name of the magic function to call and
2379 any additional arguments to be passed to the magic.
2379 any additional arguments to be passed to the magic.
2380
2380
2381 magic('name -opt foo bar') is equivalent to typing at the ipython
2381 magic('name -opt foo bar') is equivalent to typing at the ipython
2382 prompt:
2382 prompt:
2383
2383
2384 In[1]: %name -opt foo bar
2384 In[1]: %name -opt foo bar
2385
2385
2386 To call a magic without arguments, simply use magic('name').
2386 To call a magic without arguments, simply use magic('name').
2387
2387
2388 This provides a proper Python function to call IPython's magics in any
2388 This provides a proper Python function to call IPython's magics in any
2389 valid Python code you can type at the interpreter, including loops and
2389 valid Python code you can type at the interpreter, including loops and
2390 compound statements.
2390 compound statements.
2391 """
2391 """
2392 # TODO: should we issue a loud deprecation warning here?
2392 # TODO: should we issue a loud deprecation warning here?
2393 magic_name, _, magic_arg_s = arg_s.partition(' ')
2393 magic_name, _, magic_arg_s = arg_s.partition(' ')
2394 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2394 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2395 return self.run_line_magic(magic_name, magic_arg_s, _stack_depth=2)
2395 return self.run_line_magic(magic_name, magic_arg_s, _stack_depth=2)
2396
2396
2397 #-------------------------------------------------------------------------
2397 #-------------------------------------------------------------------------
2398 # Things related to macros
2398 # Things related to macros
2399 #-------------------------------------------------------------------------
2399 #-------------------------------------------------------------------------
2400
2400
2401 def define_macro(self, name, themacro):
2401 def define_macro(self, name, themacro):
2402 """Define a new macro
2402 """Define a new macro
2403
2403
2404 Parameters
2404 Parameters
2405 ----------
2405 ----------
2406 name : str
2406 name : str
2407 The name of the macro.
2407 The name of the macro.
2408 themacro : str or Macro
2408 themacro : str or Macro
2409 The action to do upon invoking the macro. If a string, a new
2409 The action to do upon invoking the macro. If a string, a new
2410 Macro object is created by passing the string to it.
2410 Macro object is created by passing the string to it.
2411 """
2411 """
2412
2412
2413 from IPython.core import macro
2413 from IPython.core import macro
2414
2414
2415 if isinstance(themacro, str):
2415 if isinstance(themacro, str):
2416 themacro = macro.Macro(themacro)
2416 themacro = macro.Macro(themacro)
2417 if not isinstance(themacro, macro.Macro):
2417 if not isinstance(themacro, macro.Macro):
2418 raise ValueError('A macro must be a string or a Macro instance.')
2418 raise ValueError('A macro must be a string or a Macro instance.')
2419 self.user_ns[name] = themacro
2419 self.user_ns[name] = themacro
2420
2420
2421 #-------------------------------------------------------------------------
2421 #-------------------------------------------------------------------------
2422 # Things related to the running of system commands
2422 # Things related to the running of system commands
2423 #-------------------------------------------------------------------------
2423 #-------------------------------------------------------------------------
2424
2424
2425 def system_piped(self, cmd):
2425 def system_piped(self, cmd):
2426 """Call the given cmd in a subprocess, piping stdout/err
2426 """Call the given cmd in a subprocess, piping stdout/err
2427
2427
2428 Parameters
2428 Parameters
2429 ----------
2429 ----------
2430 cmd : str
2430 cmd : str
2431 Command to execute (can not end in '&', as background processes are
2431 Command to execute (can not end in '&', as background processes are
2432 not supported. Should not be a command that expects input
2432 not supported. Should not be a command that expects input
2433 other than simple text.
2433 other than simple text.
2434 """
2434 """
2435 if cmd.rstrip().endswith('&'):
2435 if cmd.rstrip().endswith('&'):
2436 # this is *far* from a rigorous test
2436 # this is *far* from a rigorous test
2437 # We do not support backgrounding processes because we either use
2437 # We do not support backgrounding processes because we either use
2438 # pexpect or pipes to read from. Users can always just call
2438 # pexpect or pipes to read from. Users can always just call
2439 # os.system() or use ip.system=ip.system_raw
2439 # os.system() or use ip.system=ip.system_raw
2440 # if they really want a background process.
2440 # if they really want a background process.
2441 raise OSError("Background processes not supported.")
2441 raise OSError("Background processes not supported.")
2442
2442
2443 # we explicitly do NOT return the subprocess status code, because
2443 # we explicitly do NOT return the subprocess status code, because
2444 # a non-None value would trigger :func:`sys.displayhook` calls.
2444 # a non-None value would trigger :func:`sys.displayhook` calls.
2445 # Instead, we store the exit_code in user_ns.
2445 # Instead, we store the exit_code in user_ns.
2446 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2446 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2447
2447
2448 def system_raw(self, cmd):
2448 def system_raw(self, cmd):
2449 """Call the given cmd in a subprocess using os.system on Windows or
2449 """Call the given cmd in a subprocess using os.system on Windows or
2450 subprocess.call using the system shell on other platforms.
2450 subprocess.call using the system shell on other platforms.
2451
2451
2452 Parameters
2452 Parameters
2453 ----------
2453 ----------
2454 cmd : str
2454 cmd : str
2455 Command to execute.
2455 Command to execute.
2456 """
2456 """
2457 cmd = self.var_expand(cmd, depth=1)
2457 cmd = self.var_expand(cmd, depth=1)
2458 # protect os.system from UNC paths on Windows, which it can't handle:
2458 # protect os.system from UNC paths on Windows, which it can't handle:
2459 if sys.platform == 'win32':
2459 if sys.platform == 'win32':
2460 from IPython.utils._process_win32 import AvoidUNCPath
2460 from IPython.utils._process_win32 import AvoidUNCPath
2461 with AvoidUNCPath() as path:
2461 with AvoidUNCPath() as path:
2462 if path is not None:
2462 if path is not None:
2463 cmd = '"pushd %s &&"%s' % (path, cmd)
2463 cmd = '"pushd %s &&"%s' % (path, cmd)
2464 try:
2464 try:
2465 ec = os.system(cmd)
2465 ec = os.system(cmd)
2466 except KeyboardInterrupt:
2466 except KeyboardInterrupt:
2467 print('\n' + self.get_exception_only(), file=sys.stderr)
2467 print('\n' + self.get_exception_only(), file=sys.stderr)
2468 ec = -2
2468 ec = -2
2469 else:
2469 else:
2470 # For posix the result of the subprocess.call() below is an exit
2470 # For posix the result of the subprocess.call() below is an exit
2471 # code, which by convention is zero for success, positive for
2471 # code, which by convention is zero for success, positive for
2472 # program failure. Exit codes above 128 are reserved for signals,
2472 # program failure. Exit codes above 128 are reserved for signals,
2473 # and the formula for converting a signal to an exit code is usually
2473 # and the formula for converting a signal to an exit code is usually
2474 # signal_number+128. To more easily differentiate between exit
2474 # signal_number+128. To more easily differentiate between exit
2475 # codes and signals, ipython uses negative numbers. For instance
2475 # codes and signals, ipython uses negative numbers. For instance
2476 # since control-c is signal 2 but exit code 130, ipython's
2476 # since control-c is signal 2 but exit code 130, ipython's
2477 # _exit_code variable will read -2. Note that some shells like
2477 # _exit_code variable will read -2. Note that some shells like
2478 # csh and fish don't follow sh/bash conventions for exit codes.
2478 # csh and fish don't follow sh/bash conventions for exit codes.
2479 executable = os.environ.get('SHELL', None)
2479 executable = os.environ.get('SHELL', None)
2480 try:
2480 try:
2481 # Use env shell instead of default /bin/sh
2481 # Use env shell instead of default /bin/sh
2482 ec = subprocess.call(cmd, shell=True, executable=executable)
2482 ec = subprocess.call(cmd, shell=True, executable=executable)
2483 except KeyboardInterrupt:
2483 except KeyboardInterrupt:
2484 # intercept control-C; a long traceback is not useful here
2484 # intercept control-C; a long traceback is not useful here
2485 print('\n' + self.get_exception_only(), file=sys.stderr)
2485 print('\n' + self.get_exception_only(), file=sys.stderr)
2486 ec = 130
2486 ec = 130
2487 if ec > 128:
2487 if ec > 128:
2488 ec = -(ec - 128)
2488 ec = -(ec - 128)
2489
2489
2490 # We explicitly do NOT return the subprocess status code, because
2490 # We explicitly do NOT return the subprocess status code, because
2491 # a non-None value would trigger :func:`sys.displayhook` calls.
2491 # a non-None value would trigger :func:`sys.displayhook` calls.
2492 # Instead, we store the exit_code in user_ns. Note the semantics
2492 # Instead, we store the exit_code in user_ns. Note the semantics
2493 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2493 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2494 # but raising SystemExit(_exit_code) will give status 254!
2494 # but raising SystemExit(_exit_code) will give status 254!
2495 self.user_ns['_exit_code'] = ec
2495 self.user_ns['_exit_code'] = ec
2496
2496
2497 # use piped system by default, because it is better behaved
2497 # use piped system by default, because it is better behaved
2498 system = system_piped
2498 system = system_piped
2499
2499
2500 def getoutput(self, cmd, split=True, depth=0):
2500 def getoutput(self, cmd, split=True, depth=0):
2501 """Get output (possibly including stderr) from a subprocess.
2501 """Get output (possibly including stderr) from a subprocess.
2502
2502
2503 Parameters
2503 Parameters
2504 ----------
2504 ----------
2505 cmd : str
2505 cmd : str
2506 Command to execute (can not end in '&', as background processes are
2506 Command to execute (can not end in '&', as background processes are
2507 not supported.
2507 not supported.
2508 split : bool, optional
2508 split : bool, optional
2509 If True, split the output into an IPython SList. Otherwise, an
2509 If True, split the output into an IPython SList. Otherwise, an
2510 IPython LSString is returned. These are objects similar to normal
2510 IPython LSString is returned. These are objects similar to normal
2511 lists and strings, with a few convenience attributes for easier
2511 lists and strings, with a few convenience attributes for easier
2512 manipulation of line-based output. You can use '?' on them for
2512 manipulation of line-based output. You can use '?' on them for
2513 details.
2513 details.
2514 depth : int, optional
2514 depth : int, optional
2515 How many frames above the caller are the local variables which should
2515 How many frames above the caller are the local variables which should
2516 be expanded in the command string? The default (0) assumes that the
2516 be expanded in the command string? The default (0) assumes that the
2517 expansion variables are in the stack frame calling this function.
2517 expansion variables are in the stack frame calling this function.
2518 """
2518 """
2519 if cmd.rstrip().endswith('&'):
2519 if cmd.rstrip().endswith('&'):
2520 # this is *far* from a rigorous test
2520 # this is *far* from a rigorous test
2521 raise OSError("Background processes not supported.")
2521 raise OSError("Background processes not supported.")
2522 out = getoutput(self.var_expand(cmd, depth=depth+1))
2522 out = getoutput(self.var_expand(cmd, depth=depth+1))
2523 if split:
2523 if split:
2524 out = SList(out.splitlines())
2524 out = SList(out.splitlines())
2525 else:
2525 else:
2526 out = LSString(out)
2526 out = LSString(out)
2527 return out
2527 return out
2528
2528
2529 #-------------------------------------------------------------------------
2529 #-------------------------------------------------------------------------
2530 # Things related to aliases
2530 # Things related to aliases
2531 #-------------------------------------------------------------------------
2531 #-------------------------------------------------------------------------
2532
2532
2533 def init_alias(self):
2533 def init_alias(self):
2534 self.alias_manager = AliasManager(shell=self, parent=self)
2534 self.alias_manager = AliasManager(shell=self, parent=self)
2535 self.configurables.append(self.alias_manager)
2535 self.configurables.append(self.alias_manager)
2536
2536
2537 #-------------------------------------------------------------------------
2537 #-------------------------------------------------------------------------
2538 # Things related to extensions
2538 # Things related to extensions
2539 #-------------------------------------------------------------------------
2539 #-------------------------------------------------------------------------
2540
2540
2541 def init_extension_manager(self):
2541 def init_extension_manager(self):
2542 self.extension_manager = ExtensionManager(shell=self, parent=self)
2542 self.extension_manager = ExtensionManager(shell=self, parent=self)
2543 self.configurables.append(self.extension_manager)
2543 self.configurables.append(self.extension_manager)
2544
2544
2545 #-------------------------------------------------------------------------
2545 #-------------------------------------------------------------------------
2546 # Things related to payloads
2546 # Things related to payloads
2547 #-------------------------------------------------------------------------
2547 #-------------------------------------------------------------------------
2548
2548
2549 def init_payload(self):
2549 def init_payload(self):
2550 self.payload_manager = PayloadManager(parent=self)
2550 self.payload_manager = PayloadManager(parent=self)
2551 self.configurables.append(self.payload_manager)
2551 self.configurables.append(self.payload_manager)
2552
2552
2553 #-------------------------------------------------------------------------
2553 #-------------------------------------------------------------------------
2554 # Things related to the prefilter
2554 # Things related to the prefilter
2555 #-------------------------------------------------------------------------
2555 #-------------------------------------------------------------------------
2556
2556
2557 def init_prefilter(self):
2557 def init_prefilter(self):
2558 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2558 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2559 self.configurables.append(self.prefilter_manager)
2559 self.configurables.append(self.prefilter_manager)
2560 # Ultimately this will be refactored in the new interpreter code, but
2560 # Ultimately this will be refactored in the new interpreter code, but
2561 # for now, we should expose the main prefilter method (there's legacy
2561 # for now, we should expose the main prefilter method (there's legacy
2562 # code out there that may rely on this).
2562 # code out there that may rely on this).
2563 self.prefilter = self.prefilter_manager.prefilter_lines
2563 self.prefilter = self.prefilter_manager.prefilter_lines
2564
2564
2565 def auto_rewrite_input(self, cmd):
2565 def auto_rewrite_input(self, cmd):
2566 """Print to the screen the rewritten form of the user's command.
2566 """Print to the screen the rewritten form of the user's command.
2567
2567
2568 This shows visual feedback by rewriting input lines that cause
2568 This shows visual feedback by rewriting input lines that cause
2569 automatic calling to kick in, like::
2569 automatic calling to kick in, like::
2570
2570
2571 /f x
2571 /f x
2572
2572
2573 into::
2573 into::
2574
2574
2575 ------> f(x)
2575 ------> f(x)
2576
2576
2577 after the user's input prompt. This helps the user understand that the
2577 after the user's input prompt. This helps the user understand that the
2578 input line was transformed automatically by IPython.
2578 input line was transformed automatically by IPython.
2579 """
2579 """
2580 if not self.show_rewritten_input:
2580 if not self.show_rewritten_input:
2581 return
2581 return
2582
2582
2583 # This is overridden in TerminalInteractiveShell to use fancy prompts
2583 # This is overridden in TerminalInteractiveShell to use fancy prompts
2584 print("------> " + cmd)
2584 print("------> " + cmd)
2585
2585
2586 #-------------------------------------------------------------------------
2586 #-------------------------------------------------------------------------
2587 # Things related to extracting values/expressions from kernel and user_ns
2587 # Things related to extracting values/expressions from kernel and user_ns
2588 #-------------------------------------------------------------------------
2588 #-------------------------------------------------------------------------
2589
2589
2590 def _user_obj_error(self):
2590 def _user_obj_error(self):
2591 """return simple exception dict
2591 """return simple exception dict
2592
2592
2593 for use in user_expressions
2593 for use in user_expressions
2594 """
2594 """
2595
2595
2596 etype, evalue, tb = self._get_exc_info()
2596 etype, evalue, tb = self._get_exc_info()
2597 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2597 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2598
2598
2599 exc_info = {
2599 exc_info = {
2600 u'status' : 'error',
2600 u'status' : 'error',
2601 u'traceback' : stb,
2601 u'traceback' : stb,
2602 u'ename' : etype.__name__,
2602 u'ename' : etype.__name__,
2603 u'evalue' : py3compat.safe_unicode(evalue),
2603 u'evalue' : py3compat.safe_unicode(evalue),
2604 }
2604 }
2605
2605
2606 return exc_info
2606 return exc_info
2607
2607
2608 def _format_user_obj(self, obj):
2608 def _format_user_obj(self, obj):
2609 """format a user object to display dict
2609 """format a user object to display dict
2610
2610
2611 for use in user_expressions
2611 for use in user_expressions
2612 """
2612 """
2613
2613
2614 data, md = self.display_formatter.format(obj)
2614 data, md = self.display_formatter.format(obj)
2615 value = {
2615 value = {
2616 'status' : 'ok',
2616 'status' : 'ok',
2617 'data' : data,
2617 'data' : data,
2618 'metadata' : md,
2618 'metadata' : md,
2619 }
2619 }
2620 return value
2620 return value
2621
2621
2622 def user_expressions(self, expressions):
2622 def user_expressions(self, expressions):
2623 """Evaluate a dict of expressions in the user's namespace.
2623 """Evaluate a dict of expressions in the user's namespace.
2624
2624
2625 Parameters
2625 Parameters
2626 ----------
2626 ----------
2627 expressions : dict
2627 expressions : dict
2628 A dict with string keys and string values. The expression values
2628 A dict with string keys and string values. The expression values
2629 should be valid Python expressions, each of which will be evaluated
2629 should be valid Python expressions, each of which will be evaluated
2630 in the user namespace.
2630 in the user namespace.
2631
2631
2632 Returns
2632 Returns
2633 -------
2633 -------
2634 A dict, keyed like the input expressions dict, with the rich mime-typed
2634 A dict, keyed like the input expressions dict, with the rich mime-typed
2635 display_data of each value.
2635 display_data of each value.
2636 """
2636 """
2637 out = {}
2637 out = {}
2638 user_ns = self.user_ns
2638 user_ns = self.user_ns
2639 global_ns = self.user_global_ns
2639 global_ns = self.user_global_ns
2640
2640
2641 for key, expr in expressions.items():
2641 for key, expr in expressions.items():
2642 try:
2642 try:
2643 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2643 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2644 except:
2644 except:
2645 value = self._user_obj_error()
2645 value = self._user_obj_error()
2646 out[key] = value
2646 out[key] = value
2647 return out
2647 return out
2648
2648
2649 #-------------------------------------------------------------------------
2649 #-------------------------------------------------------------------------
2650 # Things related to the running of code
2650 # Things related to the running of code
2651 #-------------------------------------------------------------------------
2651 #-------------------------------------------------------------------------
2652
2652
2653 def ex(self, cmd):
2653 def ex(self, cmd):
2654 """Execute a normal python statement in user namespace."""
2654 """Execute a normal python statement in user namespace."""
2655 with self.builtin_trap:
2655 with self.builtin_trap:
2656 exec(cmd, self.user_global_ns, self.user_ns)
2656 exec(cmd, self.user_global_ns, self.user_ns)
2657
2657
2658 def ev(self, expr):
2658 def ev(self, expr):
2659 """Evaluate python expression expr in user namespace.
2659 """Evaluate python expression expr in user namespace.
2660
2660
2661 Returns the result of evaluation
2661 Returns the result of evaluation
2662 """
2662 """
2663 with self.builtin_trap:
2663 with self.builtin_trap:
2664 return eval(expr, self.user_global_ns, self.user_ns)
2664 return eval(expr, self.user_global_ns, self.user_ns)
2665
2665
2666 def safe_execfile(self, fname, *where, exit_ignore=False, raise_exceptions=False, shell_futures=False):
2666 def safe_execfile(self, fname, *where, exit_ignore=False, raise_exceptions=False, shell_futures=False):
2667 """A safe version of the builtin execfile().
2667 """A safe version of the builtin execfile().
2668
2668
2669 This version will never throw an exception, but instead print
2669 This version will never throw an exception, but instead print
2670 helpful error messages to the screen. This only works on pure
2670 helpful error messages to the screen. This only works on pure
2671 Python files with the .py extension.
2671 Python files with the .py extension.
2672
2672
2673 Parameters
2673 Parameters
2674 ----------
2674 ----------
2675 fname : string
2675 fname : string
2676 The name of the file to be executed.
2676 The name of the file to be executed.
2677 where : tuple
2677 where : tuple
2678 One or two namespaces, passed to execfile() as (globals,locals).
2678 One or two namespaces, passed to execfile() as (globals,locals).
2679 If only one is given, it is passed as both.
2679 If only one is given, it is passed as both.
2680 exit_ignore : bool (False)
2680 exit_ignore : bool (False)
2681 If True, then silence SystemExit for non-zero status (it is always
2681 If True, then silence SystemExit for non-zero status (it is always
2682 silenced for zero status, as it is so common).
2682 silenced for zero status, as it is so common).
2683 raise_exceptions : bool (False)
2683 raise_exceptions : bool (False)
2684 If True raise exceptions everywhere. Meant for testing.
2684 If True raise exceptions everywhere. Meant for testing.
2685 shell_futures : bool (False)
2685 shell_futures : bool (False)
2686 If True, the code will share future statements with the interactive
2686 If True, the code will share future statements with the interactive
2687 shell. It will both be affected by previous __future__ imports, and
2687 shell. It will both be affected by previous __future__ imports, and
2688 any __future__ imports in the code will affect the shell. If False,
2688 any __future__ imports in the code will affect the shell. If False,
2689 __future__ imports are not shared in either direction.
2689 __future__ imports are not shared in either direction.
2690
2690
2691 """
2691 """
2692 fname = os.path.abspath(os.path.expanduser(fname))
2692 fname = os.path.abspath(os.path.expanduser(fname))
2693
2693
2694 # Make sure we can open the file
2694 # Make sure we can open the file
2695 try:
2695 try:
2696 with open(fname):
2696 with open(fname):
2697 pass
2697 pass
2698 except:
2698 except:
2699 warn('Could not open file <%s> for safe execution.' % fname)
2699 warn('Could not open file <%s> for safe execution.' % fname)
2700 return
2700 return
2701
2701
2702 # Find things also in current directory. This is needed to mimic the
2702 # Find things also in current directory. This is needed to mimic the
2703 # behavior of running a script from the system command line, where
2703 # behavior of running a script from the system command line, where
2704 # Python inserts the script's directory into sys.path
2704 # Python inserts the script's directory into sys.path
2705 dname = os.path.dirname(fname)
2705 dname = os.path.dirname(fname)
2706
2706
2707 with prepended_to_syspath(dname), self.builtin_trap:
2707 with prepended_to_syspath(dname), self.builtin_trap:
2708 try:
2708 try:
2709 glob, loc = (where + (None, ))[:2]
2709 glob, loc = (where + (None, ))[:2]
2710 py3compat.execfile(
2710 py3compat.execfile(
2711 fname, glob, loc,
2711 fname, glob, loc,
2712 self.compile if shell_futures else None)
2712 self.compile if shell_futures else None)
2713 except SystemExit as status:
2713 except SystemExit as status:
2714 # If the call was made with 0 or None exit status (sys.exit(0)
2714 # If the call was made with 0 or None exit status (sys.exit(0)
2715 # or sys.exit() ), don't bother showing a traceback, as both of
2715 # or sys.exit() ), don't bother showing a traceback, as both of
2716 # these are considered normal by the OS:
2716 # these are considered normal by the OS:
2717 # > python -c'import sys;sys.exit(0)'; echo $?
2717 # > python -c'import sys;sys.exit(0)'; echo $?
2718 # 0
2718 # 0
2719 # > python -c'import sys;sys.exit()'; echo $?
2719 # > python -c'import sys;sys.exit()'; echo $?
2720 # 0
2720 # 0
2721 # For other exit status, we show the exception unless
2721 # For other exit status, we show the exception unless
2722 # explicitly silenced, but only in short form.
2722 # explicitly silenced, but only in short form.
2723 if status.code:
2723 if status.code:
2724 if raise_exceptions:
2724 if raise_exceptions:
2725 raise
2725 raise
2726 if not exit_ignore:
2726 if not exit_ignore:
2727 self.showtraceback(exception_only=True)
2727 self.showtraceback(exception_only=True)
2728 except:
2728 except:
2729 if raise_exceptions:
2729 if raise_exceptions:
2730 raise
2730 raise
2731 # tb offset is 2 because we wrap execfile
2731 # tb offset is 2 because we wrap execfile
2732 self.showtraceback(tb_offset=2)
2732 self.showtraceback(tb_offset=2)
2733
2733
2734 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2734 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2735 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2735 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2736
2736
2737 Parameters
2737 Parameters
2738 ----------
2738 ----------
2739 fname : str
2739 fname : str
2740 The name of the file to execute. The filename must have a
2740 The name of the file to execute. The filename must have a
2741 .ipy or .ipynb extension.
2741 .ipy or .ipynb extension.
2742 shell_futures : bool (False)
2742 shell_futures : bool (False)
2743 If True, the code will share future statements with the interactive
2743 If True, the code will share future statements with the interactive
2744 shell. It will both be affected by previous __future__ imports, and
2744 shell. It will both be affected by previous __future__ imports, and
2745 any __future__ imports in the code will affect the shell. If False,
2745 any __future__ imports in the code will affect the shell. If False,
2746 __future__ imports are not shared in either direction.
2746 __future__ imports are not shared in either direction.
2747 raise_exceptions : bool (False)
2747 raise_exceptions : bool (False)
2748 If True raise exceptions everywhere. Meant for testing.
2748 If True raise exceptions everywhere. Meant for testing.
2749 """
2749 """
2750 fname = os.path.abspath(os.path.expanduser(fname))
2750 fname = os.path.abspath(os.path.expanduser(fname))
2751
2751
2752 # Make sure we can open the file
2752 # Make sure we can open the file
2753 try:
2753 try:
2754 with open(fname):
2754 with open(fname):
2755 pass
2755 pass
2756 except:
2756 except:
2757 warn('Could not open file <%s> for safe execution.' % fname)
2757 warn('Could not open file <%s> for safe execution.' % fname)
2758 return
2758 return
2759
2759
2760 # Find things also in current directory. This is needed to mimic the
2760 # Find things also in current directory. This is needed to mimic the
2761 # behavior of running a script from the system command line, where
2761 # behavior of running a script from the system command line, where
2762 # Python inserts the script's directory into sys.path
2762 # Python inserts the script's directory into sys.path
2763 dname = os.path.dirname(fname)
2763 dname = os.path.dirname(fname)
2764
2764
2765 def get_cells():
2765 def get_cells():
2766 """generator for sequence of code blocks to run"""
2766 """generator for sequence of code blocks to run"""
2767 if fname.endswith('.ipynb'):
2767 if fname.endswith('.ipynb'):
2768 from nbformat import read
2768 from nbformat import read
2769 nb = read(fname, as_version=4)
2769 nb = read(fname, as_version=4)
2770 if not nb.cells:
2770 if not nb.cells:
2771 return
2771 return
2772 for cell in nb.cells:
2772 for cell in nb.cells:
2773 if cell.cell_type == 'code':
2773 if cell.cell_type == 'code':
2774 yield cell.source
2774 yield cell.source
2775 else:
2775 else:
2776 with open(fname) as f:
2776 with open(fname) as f:
2777 yield f.read()
2777 yield f.read()
2778
2778
2779 with prepended_to_syspath(dname):
2779 with prepended_to_syspath(dname):
2780 try:
2780 try:
2781 for cell in get_cells():
2781 for cell in get_cells():
2782 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2782 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2783 if raise_exceptions:
2783 if raise_exceptions:
2784 result.raise_error()
2784 result.raise_error()
2785 elif not result.success:
2785 elif not result.success:
2786 break
2786 break
2787 except:
2787 except:
2788 if raise_exceptions:
2788 if raise_exceptions:
2789 raise
2789 raise
2790 self.showtraceback()
2790 self.showtraceback()
2791 warn('Unknown failure executing file: <%s>' % fname)
2791 warn('Unknown failure executing file: <%s>' % fname)
2792
2792
2793 def safe_run_module(self, mod_name, where):
2793 def safe_run_module(self, mod_name, where):
2794 """A safe version of runpy.run_module().
2794 """A safe version of runpy.run_module().
2795
2795
2796 This version will never throw an exception, but instead print
2796 This version will never throw an exception, but instead print
2797 helpful error messages to the screen.
2797 helpful error messages to the screen.
2798
2798
2799 `SystemExit` exceptions with status code 0 or None are ignored.
2799 `SystemExit` exceptions with status code 0 or None are ignored.
2800
2800
2801 Parameters
2801 Parameters
2802 ----------
2802 ----------
2803 mod_name : string
2803 mod_name : string
2804 The name of the module to be executed.
2804 The name of the module to be executed.
2805 where : dict
2805 where : dict
2806 The globals namespace.
2806 The globals namespace.
2807 """
2807 """
2808 try:
2808 try:
2809 try:
2809 try:
2810 where.update(
2810 where.update(
2811 runpy.run_module(str(mod_name), run_name="__main__",
2811 runpy.run_module(str(mod_name), run_name="__main__",
2812 alter_sys=True)
2812 alter_sys=True)
2813 )
2813 )
2814 except SystemExit as status:
2814 except SystemExit as status:
2815 if status.code:
2815 if status.code:
2816 raise
2816 raise
2817 except:
2817 except:
2818 self.showtraceback()
2818 self.showtraceback()
2819 warn('Unknown failure executing module: <%s>' % mod_name)
2819 warn('Unknown failure executing module: <%s>' % mod_name)
2820
2820
2821 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2821 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2822 """Run a complete IPython cell.
2822 """Run a complete IPython cell.
2823
2823
2824 Parameters
2824 Parameters
2825 ----------
2825 ----------
2826 raw_cell : str
2826 raw_cell : str
2827 The code (including IPython code such as %magic functions) to run.
2827 The code (including IPython code such as %magic functions) to run.
2828 store_history : bool
2828 store_history : bool
2829 If True, the raw and translated cell will be stored in IPython's
2829 If True, the raw and translated cell will be stored in IPython's
2830 history. For user code calling back into IPython's machinery, this
2830 history. For user code calling back into IPython's machinery, this
2831 should be set to False.
2831 should be set to False.
2832 silent : bool
2832 silent : bool
2833 If True, avoid side-effects, such as implicit displayhooks and
2833 If True, avoid side-effects, such as implicit displayhooks and
2834 and logging. silent=True forces store_history=False.
2834 and logging. silent=True forces store_history=False.
2835 shell_futures : bool
2835 shell_futures : bool
2836 If True, the code will share future statements with the interactive
2836 If True, the code will share future statements with the interactive
2837 shell. It will both be affected by previous __future__ imports, and
2837 shell. It will both be affected by previous __future__ imports, and
2838 any __future__ imports in the code will affect the shell. If False,
2838 any __future__ imports in the code will affect the shell. If False,
2839 __future__ imports are not shared in either direction.
2839 __future__ imports are not shared in either direction.
2840
2840
2841 Returns
2841 Returns
2842 -------
2842 -------
2843 result : :class:`ExecutionResult`
2843 result : :class:`ExecutionResult`
2844 """
2844 """
2845 result = None
2845 result = None
2846 try:
2846 try:
2847 result = self._run_cell(
2847 result = self._run_cell(
2848 raw_cell, store_history, silent, shell_futures)
2848 raw_cell, store_history, silent, shell_futures)
2849 finally:
2849 finally:
2850 self.events.trigger('post_execute')
2850 self.events.trigger('post_execute')
2851 if not silent:
2851 if not silent:
2852 self.events.trigger('post_run_cell', result)
2852 self.events.trigger('post_run_cell', result)
2853 return result
2853 return result
2854
2854
2855 def _run_cell(self, raw_cell:str, store_history:bool, silent:bool, shell_futures:bool):
2855 def _run_cell(self, raw_cell:str, store_history:bool, silent:bool, shell_futures:bool):
2856 """Internal method to run a complete IPython cell."""
2856 """Internal method to run a complete IPython cell."""
2857 coro = self.run_cell_async(
2857 coro = self.run_cell_async(
2858 raw_cell,
2858 raw_cell,
2859 store_history=store_history,
2859 store_history=store_history,
2860 silent=silent,
2860 silent=silent,
2861 shell_futures=shell_futures,
2861 shell_futures=shell_futures,
2862 )
2862 )
2863
2863
2864 # run_cell_async is async, but may not actually need an eventloop.
2864 # run_cell_async is async, but may not actually need an eventloop.
2865 # when this is the case, we want to run it using the pseudo_sync_runner
2865 # when this is the case, we want to run it using the pseudo_sync_runner
2866 # so that code can invoke eventloops (for example via the %run , and
2866 # so that code can invoke eventloops (for example via the %run , and
2867 # `%paste` magic.
2867 # `%paste` magic.
2868 if self.should_run_async(raw_cell):
2868 if self.should_run_async(raw_cell):
2869 runner = self.loop_runner
2869 runner = self.loop_runner
2870 else:
2870 else:
2871 runner = _pseudo_sync_runner
2871 runner = _pseudo_sync_runner
2872
2872
2873 try:
2873 try:
2874 return runner(coro)
2874 return runner(coro)
2875 except BaseException as e:
2875 except BaseException as e:
2876 info = ExecutionInfo(raw_cell, store_history, silent, shell_futures)
2876 info = ExecutionInfo(raw_cell, store_history, silent, shell_futures)
2877 result = ExecutionResult(info)
2877 result = ExecutionResult(info)
2878 result.error_in_exec = e
2878 result.error_in_exec = e
2879 self.showtraceback(running_compiled_code=True)
2879 self.showtraceback(running_compiled_code=True)
2880 return result
2880 return result
2881 return
2881 return
2882
2882
2883 def should_run_async(self, raw_cell: str) -> bool:
2883 def should_run_async(self, raw_cell: str) -> bool:
2884 """Return whether a cell should be run asynchronously via a coroutine runner
2884 """Return whether a cell should be run asynchronously via a coroutine runner
2885
2885
2886 Parameters
2886 Parameters
2887 ----------
2887 ----------
2888 raw_cell: str
2888 raw_cell: str
2889 The code to be executed
2889 The code to be executed
2890
2890
2891 Returns
2891 Returns
2892 -------
2892 -------
2893 result: bool
2893 result: bool
2894 Whether the code needs to be run with a coroutine runner or not
2894 Whether the code needs to be run with a coroutine runner or not
2895
2895
2896 .. versionadded: 7.0
2896 .. versionadded: 7.0
2897 """
2897 """
2898 if not self.autoawait:
2898 if not self.autoawait:
2899 return False
2899 return False
2900 try:
2900 try:
2901 cell = self.transform_cell(raw_cell)
2901 cell = self.transform_cell(raw_cell)
2902 except Exception:
2902 except Exception:
2903 # any exception during transform will be raised
2903 # any exception during transform will be raised
2904 # prior to execution
2904 # prior to execution
2905 return False
2905 return False
2906 return _should_be_async(cell)
2906 return _should_be_async(cell)
2907
2907
2908 async def run_cell_async(self, raw_cell: str, store_history=False, silent=False, shell_futures=True) -> ExecutionResult:
2908 async def run_cell_async(self, raw_cell: str, store_history=False, silent=False, shell_futures=True) -> ExecutionResult:
2909 """Run a complete IPython cell asynchronously.
2909 """Run a complete IPython cell asynchronously.
2910
2910
2911 Parameters
2911 Parameters
2912 ----------
2912 ----------
2913 raw_cell : str
2913 raw_cell : str
2914 The code (including IPython code such as %magic functions) to run.
2914 The code (including IPython code such as %magic functions) to run.
2915 store_history : bool
2915 store_history : bool
2916 If True, the raw and translated cell will be stored in IPython's
2916 If True, the raw and translated cell will be stored in IPython's
2917 history. For user code calling back into IPython's machinery, this
2917 history. For user code calling back into IPython's machinery, this
2918 should be set to False.
2918 should be set to False.
2919 silent : bool
2919 silent : bool
2920 If True, avoid side-effects, such as implicit displayhooks and
2920 If True, avoid side-effects, such as implicit displayhooks and
2921 and logging. silent=True forces store_history=False.
2921 and logging. silent=True forces store_history=False.
2922 shell_futures : bool
2922 shell_futures : bool
2923 If True, the code will share future statements with the interactive
2923 If True, the code will share future statements with the interactive
2924 shell. It will both be affected by previous __future__ imports, and
2924 shell. It will both be affected by previous __future__ imports, and
2925 any __future__ imports in the code will affect the shell. If False,
2925 any __future__ imports in the code will affect the shell. If False,
2926 __future__ imports are not shared in either direction.
2926 __future__ imports are not shared in either direction.
2927
2927
2928 Returns
2928 Returns
2929 -------
2929 -------
2930 result : :class:`ExecutionResult`
2930 result : :class:`ExecutionResult`
2931
2931
2932 .. versionadded: 7.0
2932 .. versionadded: 7.0
2933 """
2933 """
2934 info = ExecutionInfo(
2934 info = ExecutionInfo(
2935 raw_cell, store_history, silent, shell_futures)
2935 raw_cell, store_history, silent, shell_futures)
2936 result = ExecutionResult(info)
2936 result = ExecutionResult(info)
2937
2937
2938 if (not raw_cell) or raw_cell.isspace():
2938 if (not raw_cell) or raw_cell.isspace():
2939 self.last_execution_succeeded = True
2939 self.last_execution_succeeded = True
2940 self.last_execution_result = result
2940 self.last_execution_result = result
2941 return result
2941 return result
2942
2942
2943 if silent:
2943 if silent:
2944 store_history = False
2944 store_history = False
2945
2945
2946 if store_history:
2946 if store_history:
2947 result.execution_count = self.execution_count
2947 result.execution_count = self.execution_count
2948
2948
2949 def error_before_exec(value):
2949 def error_before_exec(value):
2950 if store_history:
2950 if store_history:
2951 self.execution_count += 1
2951 self.execution_count += 1
2952 result.error_before_exec = value
2952 result.error_before_exec = value
2953 self.last_execution_succeeded = False
2953 self.last_execution_succeeded = False
2954 self.last_execution_result = result
2954 self.last_execution_result = result
2955 return result
2955 return result
2956
2956
2957 self.events.trigger('pre_execute')
2957 self.events.trigger('pre_execute')
2958 if not silent:
2958 if not silent:
2959 self.events.trigger('pre_run_cell', info)
2959 self.events.trigger('pre_run_cell', info)
2960
2960
2961 # If any of our input transformation (input_transformer_manager or
2961 # If any of our input transformation (input_transformer_manager or
2962 # prefilter_manager) raises an exception, we store it in this variable
2962 # prefilter_manager) raises an exception, we store it in this variable
2963 # so that we can display the error after logging the input and storing
2963 # so that we can display the error after logging the input and storing
2964 # it in the history.
2964 # it in the history.
2965 try:
2965 try:
2966 cell = self.transform_cell(raw_cell)
2966 cell = self.transform_cell(raw_cell)
2967 except Exception:
2967 except Exception:
2968 preprocessing_exc_tuple = sys.exc_info()
2968 preprocessing_exc_tuple = sys.exc_info()
2969 cell = raw_cell # cell has to exist so it can be stored/logged
2969 cell = raw_cell # cell has to exist so it can be stored/logged
2970 else:
2970 else:
2971 preprocessing_exc_tuple = None
2971 preprocessing_exc_tuple = None
2972
2972
2973 # Store raw and processed history
2973 # Store raw and processed history
2974 if store_history:
2974 if store_history:
2975 self.history_manager.store_inputs(self.execution_count,
2975 self.history_manager.store_inputs(self.execution_count,
2976 cell, raw_cell)
2976 cell, raw_cell)
2977 if not silent:
2977 if not silent:
2978 self.logger.log(cell, raw_cell)
2978 self.logger.log(cell, raw_cell)
2979
2979
2980 # Display the exception if input processing failed.
2980 # Display the exception if input processing failed.
2981 if preprocessing_exc_tuple is not None:
2981 if preprocessing_exc_tuple is not None:
2982 self.showtraceback(preprocessing_exc_tuple)
2982 self.showtraceback(preprocessing_exc_tuple)
2983 if store_history:
2983 if store_history:
2984 self.execution_count += 1
2984 self.execution_count += 1
2985 return error_before_exec(preprocessing_exc_tuple[1])
2985 return error_before_exec(preprocessing_exc_tuple[1])
2986
2986
2987 # Our own compiler remembers the __future__ environment. If we want to
2987 # Our own compiler remembers the __future__ environment. If we want to
2988 # run code with a separate __future__ environment, use the default
2988 # run code with a separate __future__ environment, use the default
2989 # compiler
2989 # compiler
2990 compiler = self.compile if shell_futures else CachingCompiler()
2990 compiler = self.compile if shell_futures else CachingCompiler()
2991
2991
2992 _run_async = False
2992 _run_async = False
2993
2993
2994 with self.builtin_trap:
2994 with self.builtin_trap:
2995 cell_name = self.compile.cache(cell, self.execution_count)
2995 cell_name = self.compile.cache(cell, self.execution_count)
2996
2996
2997 with self.display_trap:
2997 with self.display_trap:
2998 # Compile to bytecode
2998 # Compile to bytecode
2999 try:
2999 try:
3000 if sys.version_info < (3,8) and self.autoawait:
3000 if sys.version_info < (3,8) and self.autoawait:
3001 if _should_be_async(cell):
3001 if _should_be_async(cell):
3002 # the code AST below will not be user code: we wrap it
3002 # the code AST below will not be user code: we wrap it
3003 # in an `async def`. This will likely make some AST
3003 # in an `async def`. This will likely make some AST
3004 # transformer below miss some transform opportunity and
3004 # transformer below miss some transform opportunity and
3005 # introduce a small coupling to run_code (in which we
3005 # introduce a small coupling to run_code (in which we
3006 # bake some assumptions of what _ast_asyncify returns.
3006 # bake some assumptions of what _ast_asyncify returns.
3007 # they are ways around (like grafting part of the ast
3007 # they are ways around (like grafting part of the ast
3008 # later:
3008 # later:
3009 # - Here, return code_ast.body[0].body[1:-1], as well
3009 # - Here, return code_ast.body[0].body[1:-1], as well
3010 # as last expression in return statement which is
3010 # as last expression in return statement which is
3011 # the user code part.
3011 # the user code part.
3012 # - Let it go through the AST transformers, and graft
3012 # - Let it go through the AST transformers, and graft
3013 # - it back after the AST transform
3013 # - it back after the AST transform
3014 # But that seem unreasonable, at least while we
3014 # But that seem unreasonable, at least while we
3015 # do not need it.
3015 # do not need it.
3016 code_ast = _ast_asyncify(cell, 'async-def-wrapper')
3016 code_ast = _ast_asyncify(cell, 'async-def-wrapper')
3017 _run_async = True
3017 _run_async = True
3018 else:
3018 else:
3019 code_ast = compiler.ast_parse(cell, filename=cell_name)
3019 code_ast = compiler.ast_parse(cell, filename=cell_name)
3020 else:
3020 else:
3021 code_ast = compiler.ast_parse(cell, filename=cell_name)
3021 code_ast = compiler.ast_parse(cell, filename=cell_name)
3022 except self.custom_exceptions as e:
3022 except self.custom_exceptions as e:
3023 etype, value, tb = sys.exc_info()
3023 etype, value, tb = sys.exc_info()
3024 self.CustomTB(etype, value, tb)
3024 self.CustomTB(etype, value, tb)
3025 return error_before_exec(e)
3025 return error_before_exec(e)
3026 except IndentationError as e:
3026 except IndentationError as e:
3027 self.showindentationerror()
3027 self.showindentationerror()
3028 return error_before_exec(e)
3028 return error_before_exec(e)
3029 except (OverflowError, SyntaxError, ValueError, TypeError,
3029 except (OverflowError, SyntaxError, ValueError, TypeError,
3030 MemoryError) as e:
3030 MemoryError) as e:
3031 self.showsyntaxerror()
3031 self.showsyntaxerror()
3032 return error_before_exec(e)
3032 return error_before_exec(e)
3033
3033
3034 # Apply AST transformations
3034 # Apply AST transformations
3035 try:
3035 try:
3036 code_ast = self.transform_ast(code_ast)
3036 code_ast = self.transform_ast(code_ast)
3037 except InputRejected as e:
3037 except InputRejected as e:
3038 self.showtraceback()
3038 self.showtraceback()
3039 return error_before_exec(e)
3039 return error_before_exec(e)
3040
3040
3041 # Give the displayhook a reference to our ExecutionResult so it
3041 # Give the displayhook a reference to our ExecutionResult so it
3042 # can fill in the output value.
3042 # can fill in the output value.
3043 self.displayhook.exec_result = result
3043 self.displayhook.exec_result = result
3044
3044
3045 # Execute the user code
3045 # Execute the user code
3046 interactivity = "none" if silent else self.ast_node_interactivity
3046 interactivity = "none" if silent else self.ast_node_interactivity
3047 if _run_async:
3047 if _run_async:
3048 interactivity = 'async'
3048 interactivity = 'async'
3049
3049
3050 has_raised = await self.run_ast_nodes(code_ast.body, cell_name,
3050 has_raised = await self.run_ast_nodes(code_ast.body, cell_name,
3051 interactivity=interactivity, compiler=compiler, result=result)
3051 interactivity=interactivity, compiler=compiler, result=result)
3052
3052
3053 self.last_execution_succeeded = not has_raised
3053 self.last_execution_succeeded = not has_raised
3054 self.last_execution_result = result
3054 self.last_execution_result = result
3055
3055
3056 # Reset this so later displayed values do not modify the
3056 # Reset this so later displayed values do not modify the
3057 # ExecutionResult
3057 # ExecutionResult
3058 self.displayhook.exec_result = None
3058 self.displayhook.exec_result = None
3059
3059
3060 if store_history:
3060 if store_history:
3061 # Write output to the database. Does nothing unless
3061 # Write output to the database. Does nothing unless
3062 # history output logging is enabled.
3062 # history output logging is enabled.
3063 self.history_manager.store_output(self.execution_count)
3063 self.history_manager.store_output(self.execution_count)
3064 # Each cell is a *single* input, regardless of how many lines it has
3064 # Each cell is a *single* input, regardless of how many lines it has
3065 self.execution_count += 1
3065 self.execution_count += 1
3066
3066
3067 return result
3067 return result
3068
3068
3069 def transform_cell(self, raw_cell):
3069 def transform_cell(self, raw_cell):
3070 """Transform an input cell before parsing it.
3070 """Transform an input cell before parsing it.
3071
3071
3072 Static transformations, implemented in IPython.core.inputtransformer2,
3072 Static transformations, implemented in IPython.core.inputtransformer2,
3073 deal with things like ``%magic`` and ``!system`` commands.
3073 deal with things like ``%magic`` and ``!system`` commands.
3074 These run on all input.
3074 These run on all input.
3075 Dynamic transformations, for things like unescaped magics and the exit
3075 Dynamic transformations, for things like unescaped magics and the exit
3076 autocall, depend on the state of the interpreter.
3076 autocall, depend on the state of the interpreter.
3077 These only apply to single line inputs.
3077 These only apply to single line inputs.
3078
3078
3079 These string-based transformations are followed by AST transformations;
3079 These string-based transformations are followed by AST transformations;
3080 see :meth:`transform_ast`.
3080 see :meth:`transform_ast`.
3081 """
3081 """
3082 # Static input transformations
3082 # Static input transformations
3083 cell = self.input_transformer_manager.transform_cell(raw_cell)
3083 cell = self.input_transformer_manager.transform_cell(raw_cell)
3084
3084
3085 if len(cell.splitlines()) == 1:
3085 if len(cell.splitlines()) == 1:
3086 # Dynamic transformations - only applied for single line commands
3086 # Dynamic transformations - only applied for single line commands
3087 with self.builtin_trap:
3087 with self.builtin_trap:
3088 # use prefilter_lines to handle trailing newlines
3088 # use prefilter_lines to handle trailing newlines
3089 # restore trailing newline for ast.parse
3089 # restore trailing newline for ast.parse
3090 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
3090 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
3091
3091
3092 lines = cell.splitlines(keepends=True)
3092 lines = cell.splitlines(keepends=True)
3093 for transform in self.input_transformers_post:
3093 for transform in self.input_transformers_post:
3094 lines = transform(lines)
3094 lines = transform(lines)
3095 cell = ''.join(lines)
3095 cell = ''.join(lines)
3096
3096
3097 return cell
3097 return cell
3098
3098
3099 def transform_ast(self, node):
3099 def transform_ast(self, node):
3100 """Apply the AST transformations from self.ast_transformers
3100 """Apply the AST transformations from self.ast_transformers
3101
3101
3102 Parameters
3102 Parameters
3103 ----------
3103 ----------
3104 node : ast.Node
3104 node : ast.Node
3105 The root node to be transformed. Typically called with the ast.Module
3105 The root node to be transformed. Typically called with the ast.Module
3106 produced by parsing user input.
3106 produced by parsing user input.
3107
3107
3108 Returns
3108 Returns
3109 -------
3109 -------
3110 An ast.Node corresponding to the node it was called with. Note that it
3110 An ast.Node corresponding to the node it was called with. Note that it
3111 may also modify the passed object, so don't rely on references to the
3111 may also modify the passed object, so don't rely on references to the
3112 original AST.
3112 original AST.
3113 """
3113 """
3114 for transformer in self.ast_transformers:
3114 for transformer in self.ast_transformers:
3115 try:
3115 try:
3116 node = transformer.visit(node)
3116 node = transformer.visit(node)
3117 except InputRejected:
3117 except InputRejected:
3118 # User-supplied AST transformers can reject an input by raising
3118 # User-supplied AST transformers can reject an input by raising
3119 # an InputRejected. Short-circuit in this case so that we
3119 # an InputRejected. Short-circuit in this case so that we
3120 # don't unregister the transform.
3120 # don't unregister the transform.
3121 raise
3121 raise
3122 except Exception:
3122 except Exception:
3123 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
3123 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
3124 self.ast_transformers.remove(transformer)
3124 self.ast_transformers.remove(transformer)
3125
3125
3126 if self.ast_transformers:
3126 if self.ast_transformers:
3127 ast.fix_missing_locations(node)
3127 ast.fix_missing_locations(node)
3128 return node
3128 return node
3129
3129
3130 async def run_ast_nodes(self, nodelist:ListType[AST], cell_name:str, interactivity='last_expr',
3130 async def run_ast_nodes(self, nodelist:ListType[AST], cell_name:str, interactivity='last_expr',
3131 compiler=compile, result=None):
3131 compiler=compile, result=None):
3132 """Run a sequence of AST nodes. The execution mode depends on the
3132 """Run a sequence of AST nodes. The execution mode depends on the
3133 interactivity parameter.
3133 interactivity parameter.
3134
3134
3135 Parameters
3135 Parameters
3136 ----------
3136 ----------
3137 nodelist : list
3137 nodelist : list
3138 A sequence of AST nodes to run.
3138 A sequence of AST nodes to run.
3139 cell_name : str
3139 cell_name : str
3140 Will be passed to the compiler as the filename of the cell. Typically
3140 Will be passed to the compiler as the filename of the cell. Typically
3141 the value returned by ip.compile.cache(cell).
3141 the value returned by ip.compile.cache(cell).
3142 interactivity : str
3142 interactivity : str
3143 'all', 'last', 'last_expr' , 'last_expr_or_assign' or 'none',
3143 'all', 'last', 'last_expr' , 'last_expr_or_assign' or 'none',
3144 specifying which nodes should be run interactively (displaying output
3144 specifying which nodes should be run interactively (displaying output
3145 from expressions). 'last_expr' will run the last node interactively
3145 from expressions). 'last_expr' will run the last node interactively
3146 only if it is an expression (i.e. expressions in loops or other blocks
3146 only if it is an expression (i.e. expressions in loops or other blocks
3147 are not displayed) 'last_expr_or_assign' will run the last expression
3147 are not displayed) 'last_expr_or_assign' will run the last expression
3148 or the last assignment. Other values for this parameter will raise a
3148 or the last assignment. Other values for this parameter will raise a
3149 ValueError.
3149 ValueError.
3150
3150
3151 Experimental value: 'async' Will try to run top level interactive
3151 Experimental value: 'async' Will try to run top level interactive
3152 async/await code in default runner, this will not respect the
3152 async/await code in default runner, this will not respect the
3153 interactivity setting and will only run the last node if it is an
3153 interactivity setting and will only run the last node if it is an
3154 expression.
3154 expression.
3155
3155
3156 compiler : callable
3156 compiler : callable
3157 A function with the same interface as the built-in compile(), to turn
3157 A function with the same interface as the built-in compile(), to turn
3158 the AST nodes into code objects. Default is the built-in compile().
3158 the AST nodes into code objects. Default is the built-in compile().
3159 result : ExecutionResult, optional
3159 result : ExecutionResult, optional
3160 An object to store exceptions that occur during execution.
3160 An object to store exceptions that occur during execution.
3161
3161
3162 Returns
3162 Returns
3163 -------
3163 -------
3164 True if an exception occurred while running code, False if it finished
3164 True if an exception occurred while running code, False if it finished
3165 running.
3165 running.
3166 """
3166 """
3167 if not nodelist:
3167 if not nodelist:
3168 return
3168 return
3169
3169
3170 if interactivity == 'last_expr_or_assign':
3170 if interactivity == 'last_expr_or_assign':
3171 if isinstance(nodelist[-1], _assign_nodes):
3171 if isinstance(nodelist[-1], _assign_nodes):
3172 asg = nodelist[-1]
3172 asg = nodelist[-1]
3173 if isinstance(asg, ast.Assign) and len(asg.targets) == 1:
3173 if isinstance(asg, ast.Assign) and len(asg.targets) == 1:
3174 target = asg.targets[0]
3174 target = asg.targets[0]
3175 elif isinstance(asg, _single_targets_nodes):
3175 elif isinstance(asg, _single_targets_nodes):
3176 target = asg.target
3176 target = asg.target
3177 else:
3177 else:
3178 target = None
3178 target = None
3179 if isinstance(target, ast.Name):
3179 if isinstance(target, ast.Name):
3180 nnode = ast.Expr(ast.Name(target.id, ast.Load()))
3180 nnode = ast.Expr(ast.Name(target.id, ast.Load()))
3181 ast.fix_missing_locations(nnode)
3181 ast.fix_missing_locations(nnode)
3182 nodelist.append(nnode)
3182 nodelist.append(nnode)
3183 interactivity = 'last_expr'
3183 interactivity = 'last_expr'
3184
3184
3185 _async = False
3185 _async = False
3186 if interactivity == 'last_expr':
3186 if interactivity == 'last_expr':
3187 if isinstance(nodelist[-1], ast.Expr):
3187 if isinstance(nodelist[-1], ast.Expr):
3188 interactivity = "last"
3188 interactivity = "last"
3189 else:
3189 else:
3190 interactivity = "none"
3190 interactivity = "none"
3191
3191
3192 if interactivity == 'none':
3192 if interactivity == 'none':
3193 to_run_exec, to_run_interactive = nodelist, []
3193 to_run_exec, to_run_interactive = nodelist, []
3194 elif interactivity == 'last':
3194 elif interactivity == 'last':
3195 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
3195 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
3196 elif interactivity == 'all':
3196 elif interactivity == 'all':
3197 to_run_exec, to_run_interactive = [], nodelist
3197 to_run_exec, to_run_interactive = [], nodelist
3198 elif interactivity == 'async':
3198 elif interactivity == 'async':
3199 to_run_exec, to_run_interactive = [], nodelist
3199 to_run_exec, to_run_interactive = [], nodelist
3200 _async = True
3200 _async = True
3201 else:
3201 else:
3202 raise ValueError("Interactivity was %r" % interactivity)
3202 raise ValueError("Interactivity was %r" % interactivity)
3203
3203
3204 try:
3204 try:
3205 if _async and sys.version_info > (3,8):
3205 if _async and sys.version_info > (3,8):
3206 raise ValueError("This branch should never happen on Python 3.8 and above, "
3206 raise ValueError("This branch should never happen on Python 3.8 and above, "
3207 "please try to upgrade IPython and open a bug report with your case.")
3207 "please try to upgrade IPython and open a bug report with your case.")
3208 if _async:
3208 if _async:
3209 # If interactivity is async the semantics of run_code are
3209 # If interactivity is async the semantics of run_code are
3210 # completely different Skip usual machinery.
3210 # completely different Skip usual machinery.
3211 mod = Module(nodelist, [])
3211 mod = Module(nodelist, [])
3212 async_wrapper_code = compiler(mod, cell_name, 'exec')
3212 async_wrapper_code = compiler(mod, cell_name, 'exec')
3213 exec(async_wrapper_code, self.user_global_ns, self.user_ns)
3213 exec(async_wrapper_code, self.user_global_ns, self.user_ns)
3214 async_code = removed_co_newlocals(self.user_ns.pop('async-def-wrapper')).__code__
3214 async_code = removed_co_newlocals(self.user_ns.pop('async-def-wrapper')).__code__
3215 if (await self.run_code(async_code, result, async_=True)):
3215 if (await self.run_code(async_code, result, async_=True)):
3216 return True
3216 return True
3217 else:
3217 else:
3218 if sys.version_info > (3, 8):
3218 if sys.version_info > (3, 8):
3219 def compare(code):
3219 def compare(code):
3220 is_async = (inspect.CO_COROUTINE & code.co_flags == inspect.CO_COROUTINE)
3220 is_async = (inspect.CO_COROUTINE & code.co_flags == inspect.CO_COROUTINE)
3221 return is_async
3221 return is_async
3222 else:
3222 else:
3223 def compare(code):
3223 def compare(code):
3224 return _async
3224 return _async
3225
3225
3226 # refactor that to just change the mod constructor.
3226 # refactor that to just change the mod constructor.
3227 to_run = []
3227 to_run = []
3228 for node in to_run_exec:
3228 for node in to_run_exec:
3229 to_run.append((node, 'exec'))
3229 to_run.append((node, 'exec'))
3230
3230
3231 for node in to_run_interactive:
3231 for node in to_run_interactive:
3232 to_run.append((node, 'single'))
3232 to_run.append((node, 'single'))
3233
3233
3234 for node,mode in to_run:
3234 for node,mode in to_run:
3235 if mode == 'exec':
3235 if mode == 'exec':
3236 mod = Module([node], [])
3236 mod = Module([node], [])
3237 elif mode == 'single':
3237 elif mode == 'single':
3238 mod = ast.Interactive([node])
3238 mod = ast.Interactive([node])
3239 with compiler.extra_flags(getattr(ast, 'PyCF_ALLOW_TOP_LEVEL_AWAIT', 0x0) if self.autoawait else 0x0):
3239 with compiler.extra_flags(getattr(ast, 'PyCF_ALLOW_TOP_LEVEL_AWAIT', 0x0) if self.autoawait else 0x0):
3240 code = compiler(mod, cell_name, mode)
3240 code = compiler(mod, cell_name, mode)
3241 asy = compare(code)
3241 asy = compare(code)
3242 if (await self.run_code(code, result, async_=asy)):
3242 if (await self.run_code(code, result, async_=asy)):
3243 return True
3243 return True
3244
3244
3245 # Flush softspace
3245 # Flush softspace
3246 if softspace(sys.stdout, 0):
3246 if softspace(sys.stdout, 0):
3247 print()
3247 print()
3248
3248
3249 except:
3249 except:
3250 # It's possible to have exceptions raised here, typically by
3250 # It's possible to have exceptions raised here, typically by
3251 # compilation of odd code (such as a naked 'return' outside a
3251 # compilation of odd code (such as a naked 'return' outside a
3252 # function) that did parse but isn't valid. Typically the exception
3252 # function) that did parse but isn't valid. Typically the exception
3253 # is a SyntaxError, but it's safest just to catch anything and show
3253 # is a SyntaxError, but it's safest just to catch anything and show
3254 # the user a traceback.
3254 # the user a traceback.
3255
3255
3256 # We do only one try/except outside the loop to minimize the impact
3256 # We do only one try/except outside the loop to minimize the impact
3257 # on runtime, and also because if any node in the node list is
3257 # on runtime, and also because if any node in the node list is
3258 # broken, we should stop execution completely.
3258 # broken, we should stop execution completely.
3259 if result:
3259 if result:
3260 result.error_before_exec = sys.exc_info()[1]
3260 result.error_before_exec = sys.exc_info()[1]
3261 self.showtraceback()
3261 self.showtraceback()
3262 return True
3262 return True
3263
3263
3264 return False
3264 return False
3265
3265
3266 def _async_exec(self, code_obj: types.CodeType, user_ns: dict):
3266 def _async_exec(self, code_obj: types.CodeType, user_ns: dict):
3267 """
3267 """
3268 Evaluate an asynchronous code object using a code runner
3268 Evaluate an asynchronous code object using a code runner
3269
3269
3270 Fake asynchronous execution of code_object in a namespace via a proxy namespace.
3270 Fake asynchronous execution of code_object in a namespace via a proxy namespace.
3271
3271
3272 Returns coroutine object, which can be executed via async loop runner
3272 Returns coroutine object, which can be executed via async loop runner
3273
3273
3274 WARNING: The semantics of `async_exec` are quite different from `exec`,
3274 WARNING: The semantics of `async_exec` are quite different from `exec`,
3275 in particular you can only pass a single namespace. It also return a
3275 in particular you can only pass a single namespace. It also return a
3276 handle to the value of the last things returned by code_object.
3276 handle to the value of the last things returned by code_object.
3277 """
3277 """
3278
3278
3279 return eval(code_obj, user_ns)
3279 return eval(code_obj, user_ns)
3280
3280
3281 async def run_code(self, code_obj, result=None, *, async_=False):
3281 async def run_code(self, code_obj, result=None, *, async_=False):
3282 """Execute a code object.
3282 """Execute a code object.
3283
3283
3284 When an exception occurs, self.showtraceback() is called to display a
3284 When an exception occurs, self.showtraceback() is called to display a
3285 traceback.
3285 traceback.
3286
3286
3287 Parameters
3287 Parameters
3288 ----------
3288 ----------
3289 code_obj : code object
3289 code_obj : code object
3290 A compiled code object, to be executed
3290 A compiled code object, to be executed
3291 result : ExecutionResult, optional
3291 result : ExecutionResult, optional
3292 An object to store exceptions that occur during execution.
3292 An object to store exceptions that occur during execution.
3293 async_ : Bool (Experimental)
3293 async_ : Bool (Experimental)
3294 Attempt to run top-level asynchronous code in a default loop.
3294 Attempt to run top-level asynchronous code in a default loop.
3295
3295
3296 Returns
3296 Returns
3297 -------
3297 -------
3298 False : successful execution.
3298 False : successful execution.
3299 True : an error occurred.
3299 True : an error occurred.
3300 """
3300 """
3301 # Set our own excepthook in case the user code tries to call it
3301 # Set our own excepthook in case the user code tries to call it
3302 # directly, so that the IPython crash handler doesn't get triggered
3302 # directly, so that the IPython crash handler doesn't get triggered
3303 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
3303 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
3304
3304
3305 # we save the original sys.excepthook in the instance, in case config
3305 # we save the original sys.excepthook in the instance, in case config
3306 # code (such as magics) needs access to it.
3306 # code (such as magics) needs access to it.
3307 self.sys_excepthook = old_excepthook
3307 self.sys_excepthook = old_excepthook
3308 outflag = True # happens in more places, so it's easier as default
3308 outflag = True # happens in more places, so it's easier as default
3309 try:
3309 try:
3310 try:
3310 try:
3311 self.hooks.pre_run_code_hook()
3311 self.hooks.pre_run_code_hook()
3312 if async_ and sys.version_info < (3,8):
3312 if async_ and sys.version_info < (3,8):
3313 last_expr = (await self._async_exec(code_obj, self.user_ns))
3313 last_expr = (await self._async_exec(code_obj, self.user_ns))
3314 code = compile('last_expr', 'fake', "single")
3314 code = compile('last_expr', 'fake', "single")
3315 exec(code, {'last_expr': last_expr})
3315 exec(code, {'last_expr': last_expr})
3316 elif async_ :
3316 elif async_ :
3317 await eval(code_obj, self.user_global_ns, self.user_ns)
3317 await eval(code_obj, self.user_global_ns, self.user_ns)
3318 else:
3318 else:
3319 exec(code_obj, self.user_global_ns, self.user_ns)
3319 exec(code_obj, self.user_global_ns, self.user_ns)
3320 finally:
3320 finally:
3321 # Reset our crash handler in place
3321 # Reset our crash handler in place
3322 sys.excepthook = old_excepthook
3322 sys.excepthook = old_excepthook
3323 except SystemExit as e:
3323 except SystemExit as e:
3324 if result is not None:
3324 if result is not None:
3325 result.error_in_exec = e
3325 result.error_in_exec = e
3326 self.showtraceback(exception_only=True)
3326 self.showtraceback(exception_only=True)
3327 warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
3327 warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
3328 except self.custom_exceptions:
3328 except self.custom_exceptions:
3329 etype, value, tb = sys.exc_info()
3329 etype, value, tb = sys.exc_info()
3330 if result is not None:
3330 if result is not None:
3331 result.error_in_exec = value
3331 result.error_in_exec = value
3332 self.CustomTB(etype, value, tb)
3332 self.CustomTB(etype, value, tb)
3333 except:
3333 except:
3334 if result is not None:
3334 if result is not None:
3335 result.error_in_exec = sys.exc_info()[1]
3335 result.error_in_exec = sys.exc_info()[1]
3336 self.showtraceback(running_compiled_code=True)
3336 self.showtraceback(running_compiled_code=True)
3337 else:
3337 else:
3338 outflag = False
3338 outflag = False
3339 return outflag
3339 return outflag
3340
3340
3341 # For backwards compatibility
3341 # For backwards compatibility
3342 runcode = run_code
3342 runcode = run_code
3343
3343
3344 def check_complete(self, code: str) -> Tuple[str, str]:
3344 def check_complete(self, code: str) -> Tuple[str, str]:
3345 """Return whether a block of code is ready to execute, or should be continued
3345 """Return whether a block of code is ready to execute, or should be continued
3346
3346
3347 Parameters
3347 Parameters
3348 ----------
3348 ----------
3349 source : string
3349 source : string
3350 Python input code, which can be multiline.
3350 Python input code, which can be multiline.
3351
3351
3352 Returns
3352 Returns
3353 -------
3353 -------
3354 status : str
3354 status : str
3355 One of 'complete', 'incomplete', or 'invalid' if source is not a
3355 One of 'complete', 'incomplete', or 'invalid' if source is not a
3356 prefix of valid code.
3356 prefix of valid code.
3357 indent : str
3357 indent : str
3358 When status is 'incomplete', this is some whitespace to insert on
3358 When status is 'incomplete', this is some whitespace to insert on
3359 the next line of the prompt.
3359 the next line of the prompt.
3360 """
3360 """
3361 status, nspaces = self.input_transformer_manager.check_complete(code)
3361 status, nspaces = self.input_transformer_manager.check_complete(code)
3362 return status, ' ' * (nspaces or 0)
3362 return status, ' ' * (nspaces or 0)
3363
3363
3364 #-------------------------------------------------------------------------
3364 #-------------------------------------------------------------------------
3365 # Things related to GUI support and pylab
3365 # Things related to GUI support and pylab
3366 #-------------------------------------------------------------------------
3366 #-------------------------------------------------------------------------
3367
3367
3368 active_eventloop = None
3368 active_eventloop = None
3369
3369
3370 def enable_gui(self, gui=None):
3370 def enable_gui(self, gui=None):
3371 raise NotImplementedError('Implement enable_gui in a subclass')
3371 raise NotImplementedError('Implement enable_gui in a subclass')
3372
3372
3373 def enable_matplotlib(self, gui=None):
3373 def enable_matplotlib(self, gui=None):
3374 """Enable interactive matplotlib and inline figure support.
3374 """Enable interactive matplotlib and inline figure support.
3375
3375
3376 This takes the following steps:
3376 This takes the following steps:
3377
3377
3378 1. select the appropriate eventloop and matplotlib backend
3378 1. select the appropriate eventloop and matplotlib backend
3379 2. set up matplotlib for interactive use with that backend
3379 2. set up matplotlib for interactive use with that backend
3380 3. configure formatters for inline figure display
3380 3. configure formatters for inline figure display
3381 4. enable the selected gui eventloop
3381 4. enable the selected gui eventloop
3382
3382
3383 Parameters
3383 Parameters
3384 ----------
3384 ----------
3385 gui : optional, string
3385 gui : optional, string
3386 If given, dictates the choice of matplotlib GUI backend to use
3386 If given, dictates the choice of matplotlib GUI backend to use
3387 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3387 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3388 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3388 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3389 matplotlib (as dictated by the matplotlib build-time options plus the
3389 matplotlib (as dictated by the matplotlib build-time options plus the
3390 user's matplotlibrc configuration file). Note that not all backends
3390 user's matplotlibrc configuration file). Note that not all backends
3391 make sense in all contexts, for example a terminal ipython can't
3391 make sense in all contexts, for example a terminal ipython can't
3392 display figures inline.
3392 display figures inline.
3393 """
3393 """
3394 from IPython.core import pylabtools as pt
3394 from IPython.core import pylabtools as pt
3395 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
3395 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
3396
3396
3397 if gui != 'inline':
3397 if gui != 'inline':
3398 # If we have our first gui selection, store it
3398 # If we have our first gui selection, store it
3399 if self.pylab_gui_select is None:
3399 if self.pylab_gui_select is None:
3400 self.pylab_gui_select = gui
3400 self.pylab_gui_select = gui
3401 # Otherwise if they are different
3401 # Otherwise if they are different
3402 elif gui != self.pylab_gui_select:
3402 elif gui != self.pylab_gui_select:
3403 print('Warning: Cannot change to a different GUI toolkit: %s.'
3403 print('Warning: Cannot change to a different GUI toolkit: %s.'
3404 ' Using %s instead.' % (gui, self.pylab_gui_select))
3404 ' Using %s instead.' % (gui, self.pylab_gui_select))
3405 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
3405 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
3406
3406
3407 pt.activate_matplotlib(backend)
3407 pt.activate_matplotlib(backend)
3408 pt.configure_inline_support(self, backend)
3408 pt.configure_inline_support(self, backend)
3409
3409
3410 # Now we must activate the gui pylab wants to use, and fix %run to take
3410 # Now we must activate the gui pylab wants to use, and fix %run to take
3411 # plot updates into account
3411 # plot updates into account
3412 self.enable_gui(gui)
3412 self.enable_gui(gui)
3413 self.magics_manager.registry['ExecutionMagics'].default_runner = \
3413 self.magics_manager.registry['ExecutionMagics'].default_runner = \
3414 pt.mpl_runner(self.safe_execfile)
3414 pt.mpl_runner(self.safe_execfile)
3415
3415
3416 return gui, backend
3416 return gui, backend
3417
3417
3418 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
3418 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
3419 """Activate pylab support at runtime.
3419 """Activate pylab support at runtime.
3420
3420
3421 This turns on support for matplotlib, preloads into the interactive
3421 This turns on support for matplotlib, preloads into the interactive
3422 namespace all of numpy and pylab, and configures IPython to correctly
3422 namespace all of numpy and pylab, and configures IPython to correctly
3423 interact with the GUI event loop. The GUI backend to be used can be
3423 interact with the GUI event loop. The GUI backend to be used can be
3424 optionally selected with the optional ``gui`` argument.
3424 optionally selected with the optional ``gui`` argument.
3425
3425
3426 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
3426 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
3427
3427
3428 Parameters
3428 Parameters
3429 ----------
3429 ----------
3430 gui : optional, string
3430 gui : optional, string
3431 If given, dictates the choice of matplotlib GUI backend to use
3431 If given, dictates the choice of matplotlib GUI backend to use
3432 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3432 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3433 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3433 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3434 matplotlib (as dictated by the matplotlib build-time options plus the
3434 matplotlib (as dictated by the matplotlib build-time options plus the
3435 user's matplotlibrc configuration file). Note that not all backends
3435 user's matplotlibrc configuration file). Note that not all backends
3436 make sense in all contexts, for example a terminal ipython can't
3436 make sense in all contexts, for example a terminal ipython can't
3437 display figures inline.
3437 display figures inline.
3438 import_all : optional, bool, default: True
3438 import_all : optional, bool, default: True
3439 Whether to do `from numpy import *` and `from pylab import *`
3439 Whether to do `from numpy import *` and `from pylab import *`
3440 in addition to module imports.
3440 in addition to module imports.
3441 welcome_message : deprecated
3441 welcome_message : deprecated
3442 This argument is ignored, no welcome message will be displayed.
3442 This argument is ignored, no welcome message will be displayed.
3443 """
3443 """
3444 from IPython.core.pylabtools import import_pylab
3444 from IPython.core.pylabtools import import_pylab
3445
3445
3446 gui, backend = self.enable_matplotlib(gui)
3446 gui, backend = self.enable_matplotlib(gui)
3447
3447
3448 # We want to prevent the loading of pylab to pollute the user's
3448 # We want to prevent the loading of pylab to pollute the user's
3449 # namespace as shown by the %who* magics, so we execute the activation
3449 # namespace as shown by the %who* magics, so we execute the activation
3450 # code in an empty namespace, and we update *both* user_ns and
3450 # code in an empty namespace, and we update *both* user_ns and
3451 # user_ns_hidden with this information.
3451 # user_ns_hidden with this information.
3452 ns = {}
3452 ns = {}
3453 import_pylab(ns, import_all)
3453 import_pylab(ns, import_all)
3454 # warn about clobbered names
3454 # warn about clobbered names
3455 ignored = {"__builtins__"}
3455 ignored = {"__builtins__"}
3456 both = set(ns).intersection(self.user_ns).difference(ignored)
3456 both = set(ns).intersection(self.user_ns).difference(ignored)
3457 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3457 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3458 self.user_ns.update(ns)
3458 self.user_ns.update(ns)
3459 self.user_ns_hidden.update(ns)
3459 self.user_ns_hidden.update(ns)
3460 return gui, backend, clobbered
3460 return gui, backend, clobbered
3461
3461
3462 #-------------------------------------------------------------------------
3462 #-------------------------------------------------------------------------
3463 # Utilities
3463 # Utilities
3464 #-------------------------------------------------------------------------
3464 #-------------------------------------------------------------------------
3465
3465
3466 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3466 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3467 """Expand python variables in a string.
3467 """Expand python variables in a string.
3468
3468
3469 The depth argument indicates how many frames above the caller should
3469 The depth argument indicates how many frames above the caller should
3470 be walked to look for the local namespace where to expand variables.
3470 be walked to look for the local namespace where to expand variables.
3471
3471
3472 The global namespace for expansion is always the user's interactive
3472 The global namespace for expansion is always the user's interactive
3473 namespace.
3473 namespace.
3474 """
3474 """
3475 ns = self.user_ns.copy()
3475 ns = self.user_ns.copy()
3476 try:
3476 try:
3477 frame = sys._getframe(depth+1)
3477 frame = sys._getframe(depth+1)
3478 except ValueError:
3478 except ValueError:
3479 # This is thrown if there aren't that many frames on the stack,
3479 # This is thrown if there aren't that many frames on the stack,
3480 # e.g. if a script called run_line_magic() directly.
3480 # e.g. if a script called run_line_magic() directly.
3481 pass
3481 pass
3482 else:
3482 else:
3483 ns.update(frame.f_locals)
3483 ns.update(frame.f_locals)
3484
3484
3485 try:
3485 try:
3486 # We have to use .vformat() here, because 'self' is a valid and common
3486 # We have to use .vformat() here, because 'self' is a valid and common
3487 # name, and expanding **ns for .format() would make it collide with
3487 # name, and expanding **ns for .format() would make it collide with
3488 # the 'self' argument of the method.
3488 # the 'self' argument of the method.
3489 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3489 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3490 except Exception:
3490 except Exception:
3491 # if formatter couldn't format, just let it go untransformed
3491 # if formatter couldn't format, just let it go untransformed
3492 pass
3492 pass
3493 return cmd
3493 return cmd
3494
3494
3495 def mktempfile(self, data=None, prefix='ipython_edit_'):
3495 def mktempfile(self, data=None, prefix='ipython_edit_'):
3496 """Make a new tempfile and return its filename.
3496 """Make a new tempfile and return its filename.
3497
3497
3498 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3498 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3499 but it registers the created filename internally so ipython cleans it up
3499 but it registers the created filename internally so ipython cleans it up
3500 at exit time.
3500 at exit time.
3501
3501
3502 Optional inputs:
3502 Optional inputs:
3503
3503
3504 - data(None): if data is given, it gets written out to the temp file
3504 - data(None): if data is given, it gets written out to the temp file
3505 immediately, and the file is closed again."""
3505 immediately, and the file is closed again."""
3506
3506
3507 dirname = tempfile.mkdtemp(prefix=prefix)
3507 dirname = tempfile.mkdtemp(prefix=prefix)
3508 self.tempdirs.append(dirname)
3508 self.tempdirs.append(dirname)
3509
3509
3510 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3510 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3511 os.close(handle) # On Windows, there can only be one open handle on a file
3511 os.close(handle) # On Windows, there can only be one open handle on a file
3512 self.tempfiles.append(filename)
3512 self.tempfiles.append(filename)
3513
3513
3514 if data:
3514 if data:
3515 with open(filename, 'w') as tmp_file:
3515 with open(filename, 'w') as tmp_file:
3516 tmp_file.write(data)
3516 tmp_file.write(data)
3517 return filename
3517 return filename
3518
3518
3519 @undoc
3519 @undoc
3520 def write(self,data):
3520 def write(self,data):
3521 """DEPRECATED: Write a string to the default output"""
3521 """DEPRECATED: Write a string to the default output"""
3522 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3522 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3523 DeprecationWarning, stacklevel=2)
3523 DeprecationWarning, stacklevel=2)
3524 sys.stdout.write(data)
3524 sys.stdout.write(data)
3525
3525
3526 @undoc
3526 @undoc
3527 def write_err(self,data):
3527 def write_err(self,data):
3528 """DEPRECATED: Write a string to the default error output"""
3528 """DEPRECATED: Write a string to the default error output"""
3529 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3529 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3530 DeprecationWarning, stacklevel=2)
3530 DeprecationWarning, stacklevel=2)
3531 sys.stderr.write(data)
3531 sys.stderr.write(data)
3532
3532
3533 def ask_yes_no(self, prompt, default=None, interrupt=None):
3533 def ask_yes_no(self, prompt, default=None, interrupt=None):
3534 if self.quiet:
3534 if self.quiet:
3535 return True
3535 return True
3536 return ask_yes_no(prompt,default,interrupt)
3536 return ask_yes_no(prompt,default,interrupt)
3537
3537
3538 def show_usage(self):
3538 def show_usage(self):
3539 """Show a usage message"""
3539 """Show a usage message"""
3540 page.page(IPython.core.usage.interactive_usage)
3540 page.page(IPython.core.usage.interactive_usage)
3541
3541
3542 def extract_input_lines(self, range_str, raw=False):
3542 def extract_input_lines(self, range_str, raw=False):
3543 """Return as a string a set of input history slices.
3543 """Return as a string a set of input history slices.
3544
3544
3545 Parameters
3545 Parameters
3546 ----------
3546 ----------
3547 range_str : string
3547 range_str : string
3548 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3548 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3549 since this function is for use by magic functions which get their
3549 since this function is for use by magic functions which get their
3550 arguments as strings. The number before the / is the session
3550 arguments as strings. The number before the / is the session
3551 number: ~n goes n back from the current session.
3551 number: ~n goes n back from the current session.
3552
3552
3553 raw : bool, optional
3553 raw : bool, optional
3554 By default, the processed input is used. If this is true, the raw
3554 By default, the processed input is used. If this is true, the raw
3555 input history is used instead.
3555 input history is used instead.
3556
3556
3557 Notes
3557 Notes
3558 -----
3558 -----
3559
3559
3560 Slices can be described with two notations:
3560 Slices can be described with two notations:
3561
3561
3562 * ``N:M`` -> standard python form, means including items N...(M-1).
3562 * ``N:M`` -> standard python form, means including items N...(M-1).
3563 * ``N-M`` -> include items N..M (closed endpoint).
3563 * ``N-M`` -> include items N..M (closed endpoint).
3564 """
3564 """
3565 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3565 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3566 return "\n".join(x for _, _, x in lines)
3566 return "\n".join(x for _, _, x in lines)
3567
3567
3568 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3568 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3569 """Get a code string from history, file, url, or a string or macro.
3569 """Get a code string from history, file, url, or a string or macro.
3570
3570
3571 This is mainly used by magic functions.
3571 This is mainly used by magic functions.
3572
3572
3573 Parameters
3573 Parameters
3574 ----------
3574 ----------
3575
3575
3576 target : str
3576 target : str
3577
3577
3578 A string specifying code to retrieve. This will be tried respectively
3578 A string specifying code to retrieve. This will be tried respectively
3579 as: ranges of input history (see %history for syntax), url,
3579 as: ranges of input history (see %history for syntax), url,
3580 corresponding .py file, filename, or an expression evaluating to a
3580 corresponding .py file, filename, or an expression evaluating to a
3581 string or Macro in the user namespace.
3581 string or Macro in the user namespace.
3582
3582
3583 raw : bool
3583 raw : bool
3584 If true (default), retrieve raw history. Has no effect on the other
3584 If true (default), retrieve raw history. Has no effect on the other
3585 retrieval mechanisms.
3585 retrieval mechanisms.
3586
3586
3587 py_only : bool (default False)
3587 py_only : bool (default False)
3588 Only try to fetch python code, do not try alternative methods to decode file
3588 Only try to fetch python code, do not try alternative methods to decode file
3589 if unicode fails.
3589 if unicode fails.
3590
3590
3591 Returns
3591 Returns
3592 -------
3592 -------
3593 A string of code.
3593 A string of code.
3594
3594
3595 ValueError is raised if nothing is found, and TypeError if it evaluates
3595 ValueError is raised if nothing is found, and TypeError if it evaluates
3596 to an object of another type. In each case, .args[0] is a printable
3596 to an object of another type. In each case, .args[0] is a printable
3597 message.
3597 message.
3598 """
3598 """
3599 code = self.extract_input_lines(target, raw=raw) # Grab history
3599 code = self.extract_input_lines(target, raw=raw) # Grab history
3600 if code:
3600 if code:
3601 return code
3601 return code
3602 try:
3602 try:
3603 if target.startswith(('http://', 'https://')):
3603 if target.startswith(('http://', 'https://')):
3604 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3604 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3605 except UnicodeDecodeError:
3605 except UnicodeDecodeError:
3606 if not py_only :
3606 if not py_only :
3607 # Deferred import
3607 # Deferred import
3608 from urllib.request import urlopen
3608 from urllib.request import urlopen
3609 response = urlopen(target)
3609 response = urlopen(target)
3610 return response.read().decode('latin1')
3610 return response.read().decode('latin1')
3611 raise ValueError(("'%s' seem to be unreadable.") % target)
3611 raise ValueError(("'%s' seem to be unreadable.") % target)
3612
3612
3613 potential_target = [target]
3613 potential_target = [target]
3614 try :
3614 try :
3615 potential_target.insert(0,get_py_filename(target))
3615 potential_target.insert(0,get_py_filename(target))
3616 except IOError:
3616 except IOError:
3617 pass
3617 pass
3618
3618
3619 for tgt in potential_target :
3619 for tgt in potential_target :
3620 if os.path.isfile(tgt): # Read file
3620 if os.path.isfile(tgt): # Read file
3621 try :
3621 try :
3622 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3622 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3623 except UnicodeDecodeError :
3623 except UnicodeDecodeError :
3624 if not py_only :
3624 if not py_only :
3625 with io_open(tgt,'r', encoding='latin1') as f :
3625 with io_open(tgt,'r', encoding='latin1') as f :
3626 return f.read()
3626 return f.read()
3627 raise ValueError(("'%s' seem to be unreadable.") % target)
3627 raise ValueError(("'%s' seem to be unreadable.") % target)
3628 elif os.path.isdir(os.path.expanduser(tgt)):
3628 elif os.path.isdir(os.path.expanduser(tgt)):
3629 raise ValueError("'%s' is a directory, not a regular file." % target)
3629 raise ValueError("'%s' is a directory, not a regular file." % target)
3630
3630
3631 if search_ns:
3631 if search_ns:
3632 # Inspect namespace to load object source
3632 # Inspect namespace to load object source
3633 object_info = self.object_inspect(target, detail_level=1)
3633 object_info = self.object_inspect(target, detail_level=1)
3634 if object_info['found'] and object_info['source']:
3634 if object_info['found'] and object_info['source']:
3635 return object_info['source']
3635 return object_info['source']
3636
3636
3637 try: # User namespace
3637 try: # User namespace
3638 codeobj = eval(target, self.user_ns)
3638 codeobj = eval(target, self.user_ns)
3639 except Exception:
3639 except Exception:
3640 raise ValueError(("'%s' was not found in history, as a file, url, "
3640 raise ValueError(("'%s' was not found in history, as a file, url, "
3641 "nor in the user namespace.") % target)
3641 "nor in the user namespace.") % target)
3642
3642
3643 if isinstance(codeobj, str):
3643 if isinstance(codeobj, str):
3644 return codeobj
3644 return codeobj
3645 elif isinstance(codeobj, Macro):
3645 elif isinstance(codeobj, Macro):
3646 return codeobj.value
3646 return codeobj.value
3647
3647
3648 raise TypeError("%s is neither a string nor a macro." % target,
3648 raise TypeError("%s is neither a string nor a macro." % target,
3649 codeobj)
3649 codeobj)
3650
3650
3651 #-------------------------------------------------------------------------
3651 #-------------------------------------------------------------------------
3652 # Things related to IPython exiting
3652 # Things related to IPython exiting
3653 #-------------------------------------------------------------------------
3653 #-------------------------------------------------------------------------
3654 def atexit_operations(self):
3654 def atexit_operations(self):
3655 """This will be executed at the time of exit.
3655 """This will be executed at the time of exit.
3656
3656
3657 Cleanup operations and saving of persistent data that is done
3657 Cleanup operations and saving of persistent data that is done
3658 unconditionally by IPython should be performed here.
3658 unconditionally by IPython should be performed here.
3659
3659
3660 For things that may depend on startup flags or platform specifics (such
3660 For things that may depend on startup flags or platform specifics (such
3661 as having readline or not), register a separate atexit function in the
3661 as having readline or not), register a separate atexit function in the
3662 code that has the appropriate information, rather than trying to
3662 code that has the appropriate information, rather than trying to
3663 clutter
3663 clutter
3664 """
3664 """
3665 # Close the history session (this stores the end time and line count)
3665 # Close the history session (this stores the end time and line count)
3666 # this must be *before* the tempfile cleanup, in case of temporary
3666 # this must be *before* the tempfile cleanup, in case of temporary
3667 # history db
3667 # history db
3668 self.history_manager.end_session()
3668 self.history_manager.end_session()
3669
3669
3670 # Cleanup all tempfiles and folders left around
3670 # Cleanup all tempfiles and folders left around
3671 for tfile in self.tempfiles:
3671 for tfile in self.tempfiles:
3672 try:
3672 try:
3673 os.unlink(tfile)
3673 os.unlink(tfile)
3674 except OSError:
3674 except OSError:
3675 pass
3675 pass
3676
3676
3677 for tdir in self.tempdirs:
3677 for tdir in self.tempdirs:
3678 try:
3678 try:
3679 os.rmdir(tdir)
3679 os.rmdir(tdir)
3680 except OSError:
3680 except OSError:
3681 pass
3681 pass
3682
3682
3683 # Clear all user namespaces to release all references cleanly.
3683 # Clear all user namespaces to release all references cleanly.
3684 self.reset(new_session=False)
3684 self.reset(new_session=False)
3685
3685
3686 # Run user hooks
3686 # Run user hooks
3687 self.hooks.shutdown_hook()
3687 self.hooks.shutdown_hook()
3688
3688
3689 def cleanup(self):
3689 def cleanup(self):
3690 self.restore_sys_module_state()
3690 self.restore_sys_module_state()
3691
3691
3692
3692
3693 # Overridden in terminal subclass to change prompts
3693 # Overridden in terminal subclass to change prompts
3694 def switch_doctest_mode(self, mode):
3694 def switch_doctest_mode(self, mode):
3695 pass
3695 pass
3696
3696
3697
3697
3698 class InteractiveShellABC(metaclass=abc.ABCMeta):
3698 class InteractiveShellABC(metaclass=abc.ABCMeta):
3699 """An abstract base class for InteractiveShell."""
3699 """An abstract base class for InteractiveShell."""
3700
3700
3701 InteractiveShellABC.register(InteractiveShell)
3701 InteractiveShellABC.register(InteractiveShell)
@@ -1,1501 +1,1503 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Implementation of execution-related magic functions."""
2 """Implementation of execution-related magic functions."""
3
3
4 # Copyright (c) IPython Development Team.
4 # Copyright (c) IPython Development Team.
5 # Distributed under the terms of the Modified BSD License.
5 # Distributed under the terms of the Modified BSD License.
6
6
7
7
8 import ast
8 import ast
9 import bdb
9 import bdb
10 import builtins as builtin_mod
10 import builtins as builtin_mod
11 import gc
11 import gc
12 import itertools
12 import itertools
13 import os
13 import os
14 import shlex
14 import shlex
15 import sys
15 import sys
16 import time
16 import time
17 import timeit
17 import timeit
18 import math
18 import math
19 import re
19 import re
20 from pdb import Restart
20 from pdb import Restart
21
21
22 # cProfile was added in Python2.5
22 # cProfile was added in Python2.5
23 try:
23 try:
24 import cProfile as profile
24 import cProfile as profile
25 import pstats
25 import pstats
26 except ImportError:
26 except ImportError:
27 # profile isn't bundled by default in Debian for license reasons
27 # profile isn't bundled by default in Debian for license reasons
28 try:
28 try:
29 import profile, pstats
29 import profile, pstats
30 except ImportError:
30 except ImportError:
31 profile = pstats = None
31 profile = pstats = None
32
32
33 from IPython.core import oinspect
33 from IPython.core import oinspect
34 from IPython.core import magic_arguments
34 from IPython.core import magic_arguments
35 from IPython.core import page
35 from IPython.core import page
36 from IPython.core.error import UsageError
36 from IPython.core.error import UsageError
37 from IPython.core.macro import Macro
37 from IPython.core.macro import Macro
38 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
38 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
39 line_cell_magic, on_off, needs_local_scope,
39 line_cell_magic, on_off, needs_local_scope,
40 no_var_expand)
40 no_var_expand)
41 from IPython.testing.skipdoctest import skip_doctest
41 from IPython.testing.skipdoctest import skip_doctest
42 from IPython.utils.contexts import preserve_keys
42 from IPython.utils.contexts import preserve_keys
43 from IPython.utils.capture import capture_output
43 from IPython.utils.capture import capture_output
44 from IPython.utils.ipstruct import Struct
44 from IPython.utils.ipstruct import Struct
45 from IPython.utils.module_paths import find_mod
45 from IPython.utils.module_paths import find_mod
46 from IPython.utils.path import get_py_filename, shellglob
46 from IPython.utils.path import get_py_filename, shellglob
47 from IPython.utils.timing import clock, clock2
47 from IPython.utils.timing import clock, clock2
48 from warnings import warn
48 from warnings import warn
49 from logging import error
49 from logging import error
50 from io import StringIO
50 from io import StringIO
51
51
52 if sys.version_info > (3,8):
52 if sys.version_info > (3,8):
53 from ast import Module
53 from ast import Module
54 else :
54 else :
55 # mock the new API, ignore second argument
55 # mock the new API, ignore second argument
56 # see https://github.com/ipython/ipython/issues/11590
56 # see https://github.com/ipython/ipython/issues/11590
57 from ast import Module as OriginalModule
57 from ast import Module as OriginalModule
58 Module = lambda nodelist, type_ignores: OriginalModule(nodelist)
58 Module = lambda nodelist, type_ignores: OriginalModule(nodelist)
59
59
60
60
61 #-----------------------------------------------------------------------------
61 #-----------------------------------------------------------------------------
62 # Magic implementation classes
62 # Magic implementation classes
63 #-----------------------------------------------------------------------------
63 #-----------------------------------------------------------------------------
64
64
65
65
66 class TimeitResult(object):
66 class TimeitResult(object):
67 """
67 """
68 Object returned by the timeit magic with info about the run.
68 Object returned by the timeit magic with info about the run.
69
69
70 Contains the following attributes :
70 Contains the following attributes :
71
71
72 loops: (int) number of loops done per measurement
72 loops: (int) number of loops done per measurement
73 repeat: (int) number of times the measurement has been repeated
73 repeat: (int) number of times the measurement has been repeated
74 best: (float) best execution time / number
74 best: (float) best execution time / number
75 all_runs: (list of float) execution time of each run (in s)
75 all_runs: (list of float) execution time of each run (in s)
76 compile_time: (float) time of statement compilation (s)
76 compile_time: (float) time of statement compilation (s)
77
77
78 """
78 """
79 def __init__(self, loops, repeat, best, worst, all_runs, compile_time, precision):
79 def __init__(self, loops, repeat, best, worst, all_runs, compile_time, precision):
80 self.loops = loops
80 self.loops = loops
81 self.repeat = repeat
81 self.repeat = repeat
82 self.best = best
82 self.best = best
83 self.worst = worst
83 self.worst = worst
84 self.all_runs = all_runs
84 self.all_runs = all_runs
85 self.compile_time = compile_time
85 self.compile_time = compile_time
86 self._precision = precision
86 self._precision = precision
87 self.timings = [ dt / self.loops for dt in all_runs]
87 self.timings = [ dt / self.loops for dt in all_runs]
88
88
89 @property
89 @property
90 def average(self):
90 def average(self):
91 return math.fsum(self.timings) / len(self.timings)
91 return math.fsum(self.timings) / len(self.timings)
92
92
93 @property
93 @property
94 def stdev(self):
94 def stdev(self):
95 mean = self.average
95 mean = self.average
96 return (math.fsum([(x - mean) ** 2 for x in self.timings]) / len(self.timings)) ** 0.5
96 return (math.fsum([(x - mean) ** 2 for x in self.timings]) / len(self.timings)) ** 0.5
97
97
98 def __str__(self):
98 def __str__(self):
99 pm = '+-'
99 pm = '+-'
100 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
100 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
101 try:
101 try:
102 u'\xb1'.encode(sys.stdout.encoding)
102 u'\xb1'.encode(sys.stdout.encoding)
103 pm = u'\xb1'
103 pm = u'\xb1'
104 except:
104 except:
105 pass
105 pass
106 return (
106 return (
107 u"{mean} {pm} {std} per loop (mean {pm} std. dev. of {runs} run{run_plural}, {loops} loop{loop_plural} each)"
107 u"{mean} {pm} {std} per loop (mean {pm} std. dev. of {runs} run{run_plural}, {loops} loop{loop_plural} each)"
108 .format(
108 .format(
109 pm = pm,
109 pm = pm,
110 runs = self.repeat,
110 runs = self.repeat,
111 loops = self.loops,
111 loops = self.loops,
112 loop_plural = "" if self.loops == 1 else "s",
112 loop_plural = "" if self.loops == 1 else "s",
113 run_plural = "" if self.repeat == 1 else "s",
113 run_plural = "" if self.repeat == 1 else "s",
114 mean = _format_time(self.average, self._precision),
114 mean = _format_time(self.average, self._precision),
115 std = _format_time(self.stdev, self._precision))
115 std = _format_time(self.stdev, self._precision))
116 )
116 )
117
117
118 def _repr_pretty_(self, p , cycle):
118 def _repr_pretty_(self, p , cycle):
119 unic = self.__str__()
119 unic = self.__str__()
120 p.text(u'<TimeitResult : '+unic+u'>')
120 p.text(u'<TimeitResult : '+unic+u'>')
121
121
122
122
123 class TimeitTemplateFiller(ast.NodeTransformer):
123 class TimeitTemplateFiller(ast.NodeTransformer):
124 """Fill in the AST template for timing execution.
124 """Fill in the AST template for timing execution.
125
125
126 This is quite closely tied to the template definition, which is in
126 This is quite closely tied to the template definition, which is in
127 :meth:`ExecutionMagics.timeit`.
127 :meth:`ExecutionMagics.timeit`.
128 """
128 """
129 def __init__(self, ast_setup, ast_stmt):
129 def __init__(self, ast_setup, ast_stmt):
130 self.ast_setup = ast_setup
130 self.ast_setup = ast_setup
131 self.ast_stmt = ast_stmt
131 self.ast_stmt = ast_stmt
132
132
133 def visit_FunctionDef(self, node):
133 def visit_FunctionDef(self, node):
134 "Fill in the setup statement"
134 "Fill in the setup statement"
135 self.generic_visit(node)
135 self.generic_visit(node)
136 if node.name == "inner":
136 if node.name == "inner":
137 node.body[:1] = self.ast_setup.body
137 node.body[:1] = self.ast_setup.body
138
138
139 return node
139 return node
140
140
141 def visit_For(self, node):
141 def visit_For(self, node):
142 "Fill in the statement to be timed"
142 "Fill in the statement to be timed"
143 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
143 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
144 node.body = self.ast_stmt.body
144 node.body = self.ast_stmt.body
145 return node
145 return node
146
146
147
147
148 class Timer(timeit.Timer):
148 class Timer(timeit.Timer):
149 """Timer class that explicitly uses self.inner
149 """Timer class that explicitly uses self.inner
150
150
151 which is an undocumented implementation detail of CPython,
151 which is an undocumented implementation detail of CPython,
152 not shared by PyPy.
152 not shared by PyPy.
153 """
153 """
154 # Timer.timeit copied from CPython 3.4.2
154 # Timer.timeit copied from CPython 3.4.2
155 def timeit(self, number=timeit.default_number):
155 def timeit(self, number=timeit.default_number):
156 """Time 'number' executions of the main statement.
156 """Time 'number' executions of the main statement.
157
157
158 To be precise, this executes the setup statement once, and
158 To be precise, this executes the setup statement once, and
159 then returns the time it takes to execute the main statement
159 then returns the time it takes to execute the main statement
160 a number of times, as a float measured in seconds. The
160 a number of times, as a float measured in seconds. The
161 argument is the number of times through the loop, defaulting
161 argument is the number of times through the loop, defaulting
162 to one million. The main statement, the setup statement and
162 to one million. The main statement, the setup statement and
163 the timer function to be used are passed to the constructor.
163 the timer function to be used are passed to the constructor.
164 """
164 """
165 it = itertools.repeat(None, number)
165 it = itertools.repeat(None, number)
166 gcold = gc.isenabled()
166 gcold = gc.isenabled()
167 gc.disable()
167 gc.disable()
168 try:
168 try:
169 timing = self.inner(it, self.timer)
169 timing = self.inner(it, self.timer)
170 finally:
170 finally:
171 if gcold:
171 if gcold:
172 gc.enable()
172 gc.enable()
173 return timing
173 return timing
174
174
175
175
176 @magics_class
176 @magics_class
177 class ExecutionMagics(Magics):
177 class ExecutionMagics(Magics):
178 """Magics related to code execution, debugging, profiling, etc.
178 """Magics related to code execution, debugging, profiling, etc.
179
179
180 """
180 """
181
181
182 def __init__(self, shell):
182 def __init__(self, shell):
183 super(ExecutionMagics, self).__init__(shell)
183 super(ExecutionMagics, self).__init__(shell)
184 if profile is None:
184 if profile is None:
185 self.prun = self.profile_missing_notice
185 self.prun = self.profile_missing_notice
186 # Default execution function used to actually run user code.
186 # Default execution function used to actually run user code.
187 self.default_runner = None
187 self.default_runner = None
188
188
189 def profile_missing_notice(self, *args, **kwargs):
189 def profile_missing_notice(self, *args, **kwargs):
190 error("""\
190 error("""\
191 The profile module could not be found. It has been removed from the standard
191 The profile module could not be found. It has been removed from the standard
192 python packages because of its non-free license. To use profiling, install the
192 python packages because of its non-free license. To use profiling, install the
193 python-profiler package from non-free.""")
193 python-profiler package from non-free.""")
194
194
195 @skip_doctest
195 @skip_doctest
196 @no_var_expand
196 @no_var_expand
197 @line_cell_magic
197 @line_cell_magic
198 def prun(self, parameter_s='', cell=None):
198 def prun(self, parameter_s='', cell=None):
199
199
200 """Run a statement through the python code profiler.
200 """Run a statement through the python code profiler.
201
201
202 Usage, in line mode:
202 Usage, in line mode:
203 %prun [options] statement
203 %prun [options] statement
204
204
205 Usage, in cell mode:
205 Usage, in cell mode:
206 %%prun [options] [statement]
206 %%prun [options] [statement]
207 code...
207 code...
208 code...
208 code...
209
209
210 In cell mode, the additional code lines are appended to the (possibly
210 In cell mode, the additional code lines are appended to the (possibly
211 empty) statement in the first line. Cell mode allows you to easily
211 empty) statement in the first line. Cell mode allows you to easily
212 profile multiline blocks without having to put them in a separate
212 profile multiline blocks without having to put them in a separate
213 function.
213 function.
214
214
215 The given statement (which doesn't require quote marks) is run via the
215 The given statement (which doesn't require quote marks) is run via the
216 python profiler in a manner similar to the profile.run() function.
216 python profiler in a manner similar to the profile.run() function.
217 Namespaces are internally managed to work correctly; profile.run
217 Namespaces are internally managed to work correctly; profile.run
218 cannot be used in IPython because it makes certain assumptions about
218 cannot be used in IPython because it makes certain assumptions about
219 namespaces which do not hold under IPython.
219 namespaces which do not hold under IPython.
220
220
221 Options:
221 Options:
222
222
223 -l <limit>
223 -l <limit>
224 you can place restrictions on what or how much of the
224 you can place restrictions on what or how much of the
225 profile gets printed. The limit value can be:
225 profile gets printed. The limit value can be:
226
226
227 * A string: only information for function names containing this string
227 * A string: only information for function names containing this string
228 is printed.
228 is printed.
229
229
230 * An integer: only these many lines are printed.
230 * An integer: only these many lines are printed.
231
231
232 * A float (between 0 and 1): this fraction of the report is printed
232 * A float (between 0 and 1): this fraction of the report is printed
233 (for example, use a limit of 0.4 to see the topmost 40% only).
233 (for example, use a limit of 0.4 to see the topmost 40% only).
234
234
235 You can combine several limits with repeated use of the option. For
235 You can combine several limits with repeated use of the option. For
236 example, ``-l __init__ -l 5`` will print only the topmost 5 lines of
236 example, ``-l __init__ -l 5`` will print only the topmost 5 lines of
237 information about class constructors.
237 information about class constructors.
238
238
239 -r
239 -r
240 return the pstats.Stats object generated by the profiling. This
240 return the pstats.Stats object generated by the profiling. This
241 object has all the information about the profile in it, and you can
241 object has all the information about the profile in it, and you can
242 later use it for further analysis or in other functions.
242 later use it for further analysis or in other functions.
243
243
244 -s <key>
244 -s <key>
245 sort profile by given key. You can provide more than one key
245 sort profile by given key. You can provide more than one key
246 by using the option several times: '-s key1 -s key2 -s key3...'. The
246 by using the option several times: '-s key1 -s key2 -s key3...'. The
247 default sorting key is 'time'.
247 default sorting key is 'time'.
248
248
249 The following is copied verbatim from the profile documentation
249 The following is copied verbatim from the profile documentation
250 referenced below:
250 referenced below:
251
251
252 When more than one key is provided, additional keys are used as
252 When more than one key is provided, additional keys are used as
253 secondary criteria when the there is equality in all keys selected
253 secondary criteria when the there is equality in all keys selected
254 before them.
254 before them.
255
255
256 Abbreviations can be used for any key names, as long as the
256 Abbreviations can be used for any key names, as long as the
257 abbreviation is unambiguous. The following are the keys currently
257 abbreviation is unambiguous. The following are the keys currently
258 defined:
258 defined:
259
259
260 ============ =====================
260 ============ =====================
261 Valid Arg Meaning
261 Valid Arg Meaning
262 ============ =====================
262 ============ =====================
263 "calls" call count
263 "calls" call count
264 "cumulative" cumulative time
264 "cumulative" cumulative time
265 "file" file name
265 "file" file name
266 "module" file name
266 "module" file name
267 "pcalls" primitive call count
267 "pcalls" primitive call count
268 "line" line number
268 "line" line number
269 "name" function name
269 "name" function name
270 "nfl" name/file/line
270 "nfl" name/file/line
271 "stdname" standard name
271 "stdname" standard name
272 "time" internal time
272 "time" internal time
273 ============ =====================
273 ============ =====================
274
274
275 Note that all sorts on statistics are in descending order (placing
275 Note that all sorts on statistics are in descending order (placing
276 most time consuming items first), where as name, file, and line number
276 most time consuming items first), where as name, file, and line number
277 searches are in ascending order (i.e., alphabetical). The subtle
277 searches are in ascending order (i.e., alphabetical). The subtle
278 distinction between "nfl" and "stdname" is that the standard name is a
278 distinction between "nfl" and "stdname" is that the standard name is a
279 sort of the name as printed, which means that the embedded line
279 sort of the name as printed, which means that the embedded line
280 numbers get compared in an odd way. For example, lines 3, 20, and 40
280 numbers get compared in an odd way. For example, lines 3, 20, and 40
281 would (if the file names were the same) appear in the string order
281 would (if the file names were the same) appear in the string order
282 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
282 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
283 line numbers. In fact, sort_stats("nfl") is the same as
283 line numbers. In fact, sort_stats("nfl") is the same as
284 sort_stats("name", "file", "line").
284 sort_stats("name", "file", "line").
285
285
286 -T <filename>
286 -T <filename>
287 save profile results as shown on screen to a text
287 save profile results as shown on screen to a text
288 file. The profile is still shown on screen.
288 file. The profile is still shown on screen.
289
289
290 -D <filename>
290 -D <filename>
291 save (via dump_stats) profile statistics to given
291 save (via dump_stats) profile statistics to given
292 filename. This data is in a format understood by the pstats module, and
292 filename. This data is in a format understood by the pstats module, and
293 is generated by a call to the dump_stats() method of profile
293 is generated by a call to the dump_stats() method of profile
294 objects. The profile is still shown on screen.
294 objects. The profile is still shown on screen.
295
295
296 -q
296 -q
297 suppress output to the pager. Best used with -T and/or -D above.
297 suppress output to the pager. Best used with -T and/or -D above.
298
298
299 If you want to run complete programs under the profiler's control, use
299 If you want to run complete programs under the profiler's control, use
300 ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts
300 ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts
301 contains profiler specific options as described here.
301 contains profiler specific options as described here.
302
302
303 You can read the complete documentation for the profile module with::
303 You can read the complete documentation for the profile module with::
304
304
305 In [1]: import profile; profile.help()
305 In [1]: import profile; profile.help()
306
306
307 .. versionchanged:: 7.3
307 .. versionchanged:: 7.3
308 User variables are no longer expanded,
308 User variables are no longer expanded,
309 the magic line is always left unmodified.
309 the magic line is always left unmodified.
310
310
311 """
311 """
312 opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q',
312 opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q',
313 list_all=True, posix=False)
313 list_all=True, posix=False)
314 if cell is not None:
314 if cell is not None:
315 arg_str += '\n' + cell
315 arg_str += '\n' + cell
316 arg_str = self.shell.transform_cell(arg_str)
316 arg_str = self.shell.transform_cell(arg_str)
317 return self._run_with_profiler(arg_str, opts, self.shell.user_ns)
317 return self._run_with_profiler(arg_str, opts, self.shell.user_ns)
318
318
319 def _run_with_profiler(self, code, opts, namespace):
319 def _run_with_profiler(self, code, opts, namespace):
320 """
320 """
321 Run `code` with profiler. Used by ``%prun`` and ``%run -p``.
321 Run `code` with profiler. Used by ``%prun`` and ``%run -p``.
322
322
323 Parameters
323 Parameters
324 ----------
324 ----------
325 code : str
325 code : str
326 Code to be executed.
326 Code to be executed.
327 opts : Struct
327 opts : Struct
328 Options parsed by `self.parse_options`.
328 Options parsed by `self.parse_options`.
329 namespace : dict
329 namespace : dict
330 A dictionary for Python namespace (e.g., `self.shell.user_ns`).
330 A dictionary for Python namespace (e.g., `self.shell.user_ns`).
331
331
332 """
332 """
333
333
334 # Fill default values for unspecified options:
334 # Fill default values for unspecified options:
335 opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
335 opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
336
336
337 prof = profile.Profile()
337 prof = profile.Profile()
338 try:
338 try:
339 prof = prof.runctx(code, namespace, namespace)
339 prof = prof.runctx(code, namespace, namespace)
340 sys_exit = ''
340 sys_exit = ''
341 except SystemExit:
341 except SystemExit:
342 sys_exit = """*** SystemExit exception caught in code being profiled."""
342 sys_exit = """*** SystemExit exception caught in code being profiled."""
343
343
344 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
344 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
345
345
346 lims = opts.l
346 lims = opts.l
347 if lims:
347 if lims:
348 lims = [] # rebuild lims with ints/floats/strings
348 lims = [] # rebuild lims with ints/floats/strings
349 for lim in opts.l:
349 for lim in opts.l:
350 try:
350 try:
351 lims.append(int(lim))
351 lims.append(int(lim))
352 except ValueError:
352 except ValueError:
353 try:
353 try:
354 lims.append(float(lim))
354 lims.append(float(lim))
355 except ValueError:
355 except ValueError:
356 lims.append(lim)
356 lims.append(lim)
357
357
358 # Trap output.
358 # Trap output.
359 stdout_trap = StringIO()
359 stdout_trap = StringIO()
360 stats_stream = stats.stream
360 stats_stream = stats.stream
361 try:
361 try:
362 stats.stream = stdout_trap
362 stats.stream = stdout_trap
363 stats.print_stats(*lims)
363 stats.print_stats(*lims)
364 finally:
364 finally:
365 stats.stream = stats_stream
365 stats.stream = stats_stream
366
366
367 output = stdout_trap.getvalue()
367 output = stdout_trap.getvalue()
368 output = output.rstrip()
368 output = output.rstrip()
369
369
370 if 'q' not in opts:
370 if 'q' not in opts:
371 page.page(output)
371 page.page(output)
372 print(sys_exit, end=' ')
372 print(sys_exit, end=' ')
373
373
374 dump_file = opts.D[0]
374 dump_file = opts.D[0]
375 text_file = opts.T[0]
375 text_file = opts.T[0]
376 if dump_file:
376 if dump_file:
377 prof.dump_stats(dump_file)
377 prof.dump_stats(dump_file)
378 print('\n*** Profile stats marshalled to file',\
378 print('\n*** Profile stats marshalled to file',\
379 repr(dump_file)+'.',sys_exit)
379 repr(dump_file)+'.',sys_exit)
380 if text_file:
380 if text_file:
381 with open(text_file, 'w') as pfile:
381 with open(text_file, 'w') as pfile:
382 pfile.write(output)
382 pfile.write(output)
383 print('\n*** Profile printout saved to text file',\
383 print('\n*** Profile printout saved to text file',\
384 repr(text_file)+'.',sys_exit)
384 repr(text_file)+'.',sys_exit)
385
385
386 if 'r' in opts:
386 if 'r' in opts:
387 return stats
387 return stats
388 else:
388 else:
389 return None
389 return None
390
390
391 @line_magic
391 @line_magic
392 def pdb(self, parameter_s=''):
392 def pdb(self, parameter_s=''):
393 """Control the automatic calling of the pdb interactive debugger.
393 """Control the automatic calling of the pdb interactive debugger.
394
394
395 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
395 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
396 argument it works as a toggle.
396 argument it works as a toggle.
397
397
398 When an exception is triggered, IPython can optionally call the
398 When an exception is triggered, IPython can optionally call the
399 interactive pdb debugger after the traceback printout. %pdb toggles
399 interactive pdb debugger after the traceback printout. %pdb toggles
400 this feature on and off.
400 this feature on and off.
401
401
402 The initial state of this feature is set in your configuration
402 The initial state of this feature is set in your configuration
403 file (the option is ``InteractiveShell.pdb``).
403 file (the option is ``InteractiveShell.pdb``).
404
404
405 If you want to just activate the debugger AFTER an exception has fired,
405 If you want to just activate the debugger AFTER an exception has fired,
406 without having to type '%pdb on' and rerunning your code, you can use
406 without having to type '%pdb on' and rerunning your code, you can use
407 the %debug magic."""
407 the %debug magic."""
408
408
409 par = parameter_s.strip().lower()
409 par = parameter_s.strip().lower()
410
410
411 if par:
411 if par:
412 try:
412 try:
413 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
413 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
414 except KeyError:
414 except KeyError:
415 print ('Incorrect argument. Use on/1, off/0, '
415 print ('Incorrect argument. Use on/1, off/0, '
416 'or nothing for a toggle.')
416 'or nothing for a toggle.')
417 return
417 return
418 else:
418 else:
419 # toggle
419 # toggle
420 new_pdb = not self.shell.call_pdb
420 new_pdb = not self.shell.call_pdb
421
421
422 # set on the shell
422 # set on the shell
423 self.shell.call_pdb = new_pdb
423 self.shell.call_pdb = new_pdb
424 print('Automatic pdb calling has been turned',on_off(new_pdb))
424 print('Automatic pdb calling has been turned',on_off(new_pdb))
425
425
426 @skip_doctest
426 @skip_doctest
427 @magic_arguments.magic_arguments()
427 @magic_arguments.magic_arguments()
428 @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
428 @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
429 help="""
429 help="""
430 Set break point at LINE in FILE.
430 Set break point at LINE in FILE.
431 """
431 """
432 )
432 )
433 @magic_arguments.argument('statement', nargs='*',
433 @magic_arguments.argument('statement', nargs='*',
434 help="""
434 help="""
435 Code to run in debugger.
435 Code to run in debugger.
436 You can omit this in cell magic mode.
436 You can omit this in cell magic mode.
437 """
437 """
438 )
438 )
439 @no_var_expand
439 @no_var_expand
440 @line_cell_magic
440 @line_cell_magic
441 def debug(self, line='', cell=None):
441 def debug(self, line='', cell=None):
442 """Activate the interactive debugger.
442 """Activate the interactive debugger.
443
443
444 This magic command support two ways of activating debugger.
444 This magic command support two ways of activating debugger.
445 One is to activate debugger before executing code. This way, you
445 One is to activate debugger before executing code. This way, you
446 can set a break point, to step through the code from the point.
446 can set a break point, to step through the code from the point.
447 You can use this mode by giving statements to execute and optionally
447 You can use this mode by giving statements to execute and optionally
448 a breakpoint.
448 a breakpoint.
449
449
450 The other one is to activate debugger in post-mortem mode. You can
450 The other one is to activate debugger in post-mortem mode. You can
451 activate this mode simply running %debug without any argument.
451 activate this mode simply running %debug without any argument.
452 If an exception has just occurred, this lets you inspect its stack
452 If an exception has just occurred, this lets you inspect its stack
453 frames interactively. Note that this will always work only on the last
453 frames interactively. Note that this will always work only on the last
454 traceback that occurred, so you must call this quickly after an
454 traceback that occurred, so you must call this quickly after an
455 exception that you wish to inspect has fired, because if another one
455 exception that you wish to inspect has fired, because if another one
456 occurs, it clobbers the previous one.
456 occurs, it clobbers the previous one.
457
457
458 If you want IPython to automatically do this on every exception, see
458 If you want IPython to automatically do this on every exception, see
459 the %pdb magic for more details.
459 the %pdb magic for more details.
460
460
461 .. versionchanged:: 7.3
461 .. versionchanged:: 7.3
462 When running code, user variables are no longer expanded,
462 When running code, user variables are no longer expanded,
463 the magic line is always left unmodified.
463 the magic line is always left unmodified.
464
464
465 """
465 """
466 args = magic_arguments.parse_argstring(self.debug, line)
466 args = magic_arguments.parse_argstring(self.debug, line)
467
467
468 if not (args.breakpoint or args.statement or cell):
468 if not (args.breakpoint or args.statement or cell):
469 self._debug_post_mortem()
469 self._debug_post_mortem()
470 else:
470 else:
471 code = "\n".join(args.statement)
471 code = "\n".join(args.statement)
472 if cell:
472 if cell:
473 code += "\n" + cell
473 code += "\n" + cell
474 self._debug_exec(code, args.breakpoint)
474 self._debug_exec(code, args.breakpoint)
475
475
476 def _debug_post_mortem(self):
476 def _debug_post_mortem(self):
477 self.shell.debugger(force=True)
477 self.shell.debugger(force=True)
478
478
479 def _debug_exec(self, code, breakpoint):
479 def _debug_exec(self, code, breakpoint):
480 if breakpoint:
480 if breakpoint:
481 (filename, bp_line) = breakpoint.rsplit(':', 1)
481 (filename, bp_line) = breakpoint.rsplit(':', 1)
482 bp_line = int(bp_line)
482 bp_line = int(bp_line)
483 else:
483 else:
484 (filename, bp_line) = (None, None)
484 (filename, bp_line) = (None, None)
485 self._run_with_debugger(code, self.shell.user_ns, filename, bp_line)
485 self._run_with_debugger(code, self.shell.user_ns, filename, bp_line)
486
486
487 @line_magic
487 @line_magic
488 def tb(self, s):
488 def tb(self, s):
489 """Print the last traceback.
489 """Print the last traceback.
490
490
491 Optionally, specify an exception reporting mode, tuning the
491 Optionally, specify an exception reporting mode, tuning the
492 verbosity of the traceback. By default the currently-active exception
492 verbosity of the traceback. By default the currently-active exception
493 mode is used. See %xmode for changing exception reporting modes.
493 mode is used. See %xmode for changing exception reporting modes.
494
494
495 Valid modes: Plain, Context, Verbose, and Minimal.
495 Valid modes: Plain, Context, Verbose, and Minimal.
496 """
496 """
497 interactive_tb = self.shell.InteractiveTB
497 interactive_tb = self.shell.InteractiveTB
498 if s:
498 if s:
499 # Switch exception reporting mode for this one call.
499 # Switch exception reporting mode for this one call.
500 # Ensure it is switched back.
500 # Ensure it is switched back.
501 def xmode_switch_err(name):
501 def xmode_switch_err(name):
502 warn('Error changing %s exception modes.\n%s' %
502 warn('Error changing %s exception modes.\n%s' %
503 (name,sys.exc_info()[1]))
503 (name,sys.exc_info()[1]))
504
504
505 new_mode = s.strip().capitalize()
505 new_mode = s.strip().capitalize()
506 original_mode = interactive_tb.mode
506 original_mode = interactive_tb.mode
507 try:
507 try:
508 try:
508 try:
509 interactive_tb.set_mode(mode=new_mode)
509 interactive_tb.set_mode(mode=new_mode)
510 except Exception:
510 except Exception:
511 xmode_switch_err('user')
511 xmode_switch_err('user')
512 else:
512 else:
513 self.shell.showtraceback()
513 self.shell.showtraceback()
514 finally:
514 finally:
515 interactive_tb.set_mode(mode=original_mode)
515 interactive_tb.set_mode(mode=original_mode)
516 else:
516 else:
517 self.shell.showtraceback()
517 self.shell.showtraceback()
518
518
519 @skip_doctest
519 @skip_doctest
520 @line_magic
520 @line_magic
521 def run(self, parameter_s='', runner=None,
521 def run(self, parameter_s='', runner=None,
522 file_finder=get_py_filename):
522 file_finder=get_py_filename):
523 """Run the named file inside IPython as a program.
523 """Run the named file inside IPython as a program.
524
524
525 Usage::
525 Usage::
526
526
527 %run [-n -i -e -G]
527 %run [-n -i -e -G]
528 [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
528 [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
529 ( -m mod | file ) [args]
529 ( -m mod | file ) [args]
530
530
531 Parameters after the filename are passed as command-line arguments to
531 Parameters after the filename are passed as command-line arguments to
532 the program (put in sys.argv). Then, control returns to IPython's
532 the program (put in sys.argv). Then, control returns to IPython's
533 prompt.
533 prompt.
534
534
535 This is similar to running at a system prompt ``python file args``,
535 This is similar to running at a system prompt ``python file args``,
536 but with the advantage of giving you IPython's tracebacks, and of
536 but with the advantage of giving you IPython's tracebacks, and of
537 loading all variables into your interactive namespace for further use
537 loading all variables into your interactive namespace for further use
538 (unless -p is used, see below).
538 (unless -p is used, see below).
539
539
540 The file is executed in a namespace initially consisting only of
540 The file is executed in a namespace initially consisting only of
541 ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
541 ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
542 sees its environment as if it were being run as a stand-alone program
542 sees its environment as if it were being run as a stand-alone program
543 (except for sharing global objects such as previously imported
543 (except for sharing global objects such as previously imported
544 modules). But after execution, the IPython interactive namespace gets
544 modules). But after execution, the IPython interactive namespace gets
545 updated with all variables defined in the program (except for __name__
545 updated with all variables defined in the program (except for __name__
546 and sys.argv). This allows for very convenient loading of code for
546 and sys.argv). This allows for very convenient loading of code for
547 interactive work, while giving each program a 'clean sheet' to run in.
547 interactive work, while giving each program a 'clean sheet' to run in.
548
548
549 Arguments are expanded using shell-like glob match. Patterns
549 Arguments are expanded using shell-like glob match. Patterns
550 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
550 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
551 tilde '~' will be expanded into user's home directory. Unlike
551 tilde '~' will be expanded into user's home directory. Unlike
552 real shells, quotation does not suppress expansions. Use
552 real shells, quotation does not suppress expansions. Use
553 *two* back slashes (e.g. ``\\\\*``) to suppress expansions.
553 *two* back slashes (e.g. ``\\\\*``) to suppress expansions.
554 To completely disable these expansions, you can use -G flag.
554 To completely disable these expansions, you can use -G flag.
555
555
556 On Windows systems, the use of single quotes `'` when specifying
556 On Windows systems, the use of single quotes `'` when specifying
557 a file is not supported. Use double quotes `"`.
557 a file is not supported. Use double quotes `"`.
558
558
559 Options:
559 Options:
560
560
561 -n
561 -n
562 __name__ is NOT set to '__main__', but to the running file's name
562 __name__ is NOT set to '__main__', but to the running file's name
563 without extension (as python does under import). This allows running
563 without extension (as python does under import). This allows running
564 scripts and reloading the definitions in them without calling code
564 scripts and reloading the definitions in them without calling code
565 protected by an ``if __name__ == "__main__"`` clause.
565 protected by an ``if __name__ == "__main__"`` clause.
566
566
567 -i
567 -i
568 run the file in IPython's namespace instead of an empty one. This
568 run the file in IPython's namespace instead of an empty one. This
569 is useful if you are experimenting with code written in a text editor
569 is useful if you are experimenting with code written in a text editor
570 which depends on variables defined interactively.
570 which depends on variables defined interactively.
571
571
572 -e
572 -e
573 ignore sys.exit() calls or SystemExit exceptions in the script
573 ignore sys.exit() calls or SystemExit exceptions in the script
574 being run. This is particularly useful if IPython is being used to
574 being run. This is particularly useful if IPython is being used to
575 run unittests, which always exit with a sys.exit() call. In such
575 run unittests, which always exit with a sys.exit() call. In such
576 cases you are interested in the output of the test results, not in
576 cases you are interested in the output of the test results, not in
577 seeing a traceback of the unittest module.
577 seeing a traceback of the unittest module.
578
578
579 -t
579 -t
580 print timing information at the end of the run. IPython will give
580 print timing information at the end of the run. IPython will give
581 you an estimated CPU time consumption for your script, which under
581 you an estimated CPU time consumption for your script, which under
582 Unix uses the resource module to avoid the wraparound problems of
582 Unix uses the resource module to avoid the wraparound problems of
583 time.clock(). Under Unix, an estimate of time spent on system tasks
583 time.clock(). Under Unix, an estimate of time spent on system tasks
584 is also given (for Windows platforms this is reported as 0.0).
584 is also given (for Windows platforms this is reported as 0.0).
585
585
586 If -t is given, an additional ``-N<N>`` option can be given, where <N>
586 If -t is given, an additional ``-N<N>`` option can be given, where <N>
587 must be an integer indicating how many times you want the script to
587 must be an integer indicating how many times you want the script to
588 run. The final timing report will include total and per run results.
588 run. The final timing report will include total and per run results.
589
589
590 For example (testing the script uniq_stable.py)::
590 For example (testing the script uniq_stable.py)::
591
591
592 In [1]: run -t uniq_stable
592 In [1]: run -t uniq_stable
593
593
594 IPython CPU timings (estimated):
594 IPython CPU timings (estimated):
595 User : 0.19597 s.
595 User : 0.19597 s.
596 System: 0.0 s.
596 System: 0.0 s.
597
597
598 In [2]: run -t -N5 uniq_stable
598 In [2]: run -t -N5 uniq_stable
599
599
600 IPython CPU timings (estimated):
600 IPython CPU timings (estimated):
601 Total runs performed: 5
601 Total runs performed: 5
602 Times : Total Per run
602 Times : Total Per run
603 User : 0.910862 s, 0.1821724 s.
603 User : 0.910862 s, 0.1821724 s.
604 System: 0.0 s, 0.0 s.
604 System: 0.0 s, 0.0 s.
605
605
606 -d
606 -d
607 run your program under the control of pdb, the Python debugger.
607 run your program under the control of pdb, the Python debugger.
608 This allows you to execute your program step by step, watch variables,
608 This allows you to execute your program step by step, watch variables,
609 etc. Internally, what IPython does is similar to calling::
609 etc. Internally, what IPython does is similar to calling::
610
610
611 pdb.run('execfile("YOURFILENAME")')
611 pdb.run('execfile("YOURFILENAME")')
612
612
613 with a breakpoint set on line 1 of your file. You can change the line
613 with a breakpoint set on line 1 of your file. You can change the line
614 number for this automatic breakpoint to be <N> by using the -bN option
614 number for this automatic breakpoint to be <N> by using the -bN option
615 (where N must be an integer). For example::
615 (where N must be an integer). For example::
616
616
617 %run -d -b40 myscript
617 %run -d -b40 myscript
618
618
619 will set the first breakpoint at line 40 in myscript.py. Note that
619 will set the first breakpoint at line 40 in myscript.py. Note that
620 the first breakpoint must be set on a line which actually does
620 the first breakpoint must be set on a line which actually does
621 something (not a comment or docstring) for it to stop execution.
621 something (not a comment or docstring) for it to stop execution.
622
622
623 Or you can specify a breakpoint in a different file::
623 Or you can specify a breakpoint in a different file::
624
624
625 %run -d -b myotherfile.py:20 myscript
625 %run -d -b myotherfile.py:20 myscript
626
626
627 When the pdb debugger starts, you will see a (Pdb) prompt. You must
627 When the pdb debugger starts, you will see a (Pdb) prompt. You must
628 first enter 'c' (without quotes) to start execution up to the first
628 first enter 'c' (without quotes) to start execution up to the first
629 breakpoint.
629 breakpoint.
630
630
631 Entering 'help' gives information about the use of the debugger. You
631 Entering 'help' gives information about the use of the debugger. You
632 can easily see pdb's full documentation with "import pdb;pdb.help()"
632 can easily see pdb's full documentation with "import pdb;pdb.help()"
633 at a prompt.
633 at a prompt.
634
634
635 -p
635 -p
636 run program under the control of the Python profiler module (which
636 run program under the control of the Python profiler module (which
637 prints a detailed report of execution times, function calls, etc).
637 prints a detailed report of execution times, function calls, etc).
638
638
639 You can pass other options after -p which affect the behavior of the
639 You can pass other options after -p which affect the behavior of the
640 profiler itself. See the docs for %prun for details.
640 profiler itself. See the docs for %prun for details.
641
641
642 In this mode, the program's variables do NOT propagate back to the
642 In this mode, the program's variables do NOT propagate back to the
643 IPython interactive namespace (because they remain in the namespace
643 IPython interactive namespace (because they remain in the namespace
644 where the profiler executes them).
644 where the profiler executes them).
645
645
646 Internally this triggers a call to %prun, see its documentation for
646 Internally this triggers a call to %prun, see its documentation for
647 details on the options available specifically for profiling.
647 details on the options available specifically for profiling.
648
648
649 There is one special usage for which the text above doesn't apply:
649 There is one special usage for which the text above doesn't apply:
650 if the filename ends with .ipy[nb], the file is run as ipython script,
650 if the filename ends with .ipy[nb], the file is run as ipython script,
651 just as if the commands were written on IPython prompt.
651 just as if the commands were written on IPython prompt.
652
652
653 -m
653 -m
654 specify module name to load instead of script path. Similar to
654 specify module name to load instead of script path. Similar to
655 the -m option for the python interpreter. Use this option last if you
655 the -m option for the python interpreter. Use this option last if you
656 want to combine with other %run options. Unlike the python interpreter
656 want to combine with other %run options. Unlike the python interpreter
657 only source modules are allowed no .pyc or .pyo files.
657 only source modules are allowed no .pyc or .pyo files.
658 For example::
658 For example::
659
659
660 %run -m example
660 %run -m example
661
661
662 will run the example module.
662 will run the example module.
663
663
664 -G
664 -G
665 disable shell-like glob expansion of arguments.
665 disable shell-like glob expansion of arguments.
666
666
667 """
667 """
668
668
669 # Logic to handle issue #3664
669 # Logic to handle issue #3664
670 # Add '--' after '-m <module_name>' to ignore additional args passed to a module.
670 # Add '--' after '-m <module_name>' to ignore additional args passed to a module.
671 if '-m' in parameter_s and '--' not in parameter_s:
671 if '-m' in parameter_s and '--' not in parameter_s:
672 argv = shlex.split(parameter_s, posix=(os.name == 'posix'))
672 argv = shlex.split(parameter_s, posix=(os.name == 'posix'))
673 for idx, arg in enumerate(argv):
673 for idx, arg in enumerate(argv):
674 if arg and arg.startswith('-') and arg != '-':
674 if arg and arg.startswith('-') and arg != '-':
675 if arg == '-m':
675 if arg == '-m':
676 argv.insert(idx + 2, '--')
676 argv.insert(idx + 2, '--')
677 break
677 break
678 else:
678 else:
679 # Positional arg, break
679 # Positional arg, break
680 break
680 break
681 parameter_s = ' '.join(shlex.quote(arg) for arg in argv)
681 parameter_s = ' '.join(shlex.quote(arg) for arg in argv)
682
682
683 # get arguments and set sys.argv for program to be run.
683 # get arguments and set sys.argv for program to be run.
684 opts, arg_lst = self.parse_options(parameter_s,
684 opts, arg_lst = self.parse_options(parameter_s,
685 'nidtN:b:pD:l:rs:T:em:G',
685 'nidtN:b:pD:l:rs:T:em:G',
686 mode='list', list_all=1)
686 mode='list', list_all=1)
687 if "m" in opts:
687 if "m" in opts:
688 modulename = opts["m"][0]
688 modulename = opts["m"][0]
689 modpath = find_mod(modulename)
689 modpath = find_mod(modulename)
690 if modpath is None:
690 if modpath is None:
691 warn('%r is not a valid modulename on sys.path'%modulename)
691 warn('%r is not a valid modulename on sys.path'%modulename)
692 return
692 return
693 arg_lst = [modpath] + arg_lst
693 arg_lst = [modpath] + arg_lst
694 try:
694 try:
695 fpath = None # initialize to make sure fpath is in scope later
695 fpath = None # initialize to make sure fpath is in scope later
696 fpath = arg_lst[0]
696 fpath = arg_lst[0]
697 filename = file_finder(fpath)
697 filename = file_finder(fpath)
698 except IndexError:
698 except IndexError:
699 warn('you must provide at least a filename.')
699 warn('you must provide at least a filename.')
700 print('\n%run:\n', oinspect.getdoc(self.run))
700 print('\n%run:\n', oinspect.getdoc(self.run))
701 return
701 return
702 except IOError as e:
702 except IOError as e:
703 try:
703 try:
704 msg = str(e)
704 msg = str(e)
705 except UnicodeError:
705 except UnicodeError:
706 msg = e.message
706 msg = e.message
707 if os.name == 'nt' and re.match(r"^'.*'$",fpath):
707 if os.name == 'nt' and re.match(r"^'.*'$",fpath):
708 warn('For Windows, use double quotes to wrap a filename: %run "mypath\\myfile.py"')
708 warn('For Windows, use double quotes to wrap a filename: %run "mypath\\myfile.py"')
709 error(msg)
709 error(msg)
710 return
710 return
711
711
712 if filename.lower().endswith(('.ipy', '.ipynb')):
712 if filename.lower().endswith(('.ipy', '.ipynb')):
713 with preserve_keys(self.shell.user_ns, '__file__'):
713 with preserve_keys(self.shell.user_ns, '__file__'):
714 self.shell.user_ns['__file__'] = filename
714 self.shell.user_ns['__file__'] = filename
715 self.shell.safe_execfile_ipy(filename)
715 self.shell.safe_execfile_ipy(filename)
716 return
716 return
717
717
718 # Control the response to exit() calls made by the script being run
718 # Control the response to exit() calls made by the script being run
719 exit_ignore = 'e' in opts
719 exit_ignore = 'e' in opts
720
720
721 # Make sure that the running script gets a proper sys.argv as if it
721 # Make sure that the running script gets a proper sys.argv as if it
722 # were run from a system shell.
722 # were run from a system shell.
723 save_argv = sys.argv # save it for later restoring
723 save_argv = sys.argv # save it for later restoring
724
724
725 if 'G' in opts:
725 if 'G' in opts:
726 args = arg_lst[1:]
726 args = arg_lst[1:]
727 else:
727 else:
728 # tilde and glob expansion
728 # tilde and glob expansion
729 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
729 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
730
730
731 sys.argv = [filename] + args # put in the proper filename
731 sys.argv = [filename] + args # put in the proper filename
732
732
733 if 'n' in opts:
733 if 'n' in opts:
734 name = os.path.splitext(os.path.basename(filename))[0]
734 name = os.path.splitext(os.path.basename(filename))[0]
735 else:
735 else:
736 name = '__main__'
736 name = '__main__'
737
737
738 if 'i' in opts:
738 if 'i' in opts:
739 # Run in user's interactive namespace
739 # Run in user's interactive namespace
740 prog_ns = self.shell.user_ns
740 prog_ns = self.shell.user_ns
741 __name__save = self.shell.user_ns['__name__']
741 __name__save = self.shell.user_ns['__name__']
742 prog_ns['__name__'] = name
742 prog_ns['__name__'] = name
743 main_mod = self.shell.user_module
743 main_mod = self.shell.user_module
744
744
745 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
745 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
746 # set the __file__ global in the script's namespace
746 # set the __file__ global in the script's namespace
747 # TK: Is this necessary in interactive mode?
747 # TK: Is this necessary in interactive mode?
748 prog_ns['__file__'] = filename
748 prog_ns['__file__'] = filename
749 else:
749 else:
750 # Run in a fresh, empty namespace
750 # Run in a fresh, empty namespace
751
751
752 # The shell MUST hold a reference to prog_ns so after %run
752 # The shell MUST hold a reference to prog_ns so after %run
753 # exits, the python deletion mechanism doesn't zero it out
753 # exits, the python deletion mechanism doesn't zero it out
754 # (leaving dangling references). See interactiveshell for details
754 # (leaving dangling references). See interactiveshell for details
755 main_mod = self.shell.new_main_mod(filename, name)
755 main_mod = self.shell.new_main_mod(filename, name)
756 prog_ns = main_mod.__dict__
756 prog_ns = main_mod.__dict__
757
757
758 # pickle fix. See interactiveshell for an explanation. But we need to
758 # pickle fix. See interactiveshell for an explanation. But we need to
759 # make sure that, if we overwrite __main__, we replace it at the end
759 # make sure that, if we overwrite __main__, we replace it at the end
760 main_mod_name = prog_ns['__name__']
760 main_mod_name = prog_ns['__name__']
761
761
762 if main_mod_name == '__main__':
762 if main_mod_name == '__main__':
763 restore_main = sys.modules['__main__']
763 restore_main = sys.modules['__main__']
764 else:
764 else:
765 restore_main = False
765 restore_main = False
766
766
767 # This needs to be undone at the end to prevent holding references to
767 # This needs to be undone at the end to prevent holding references to
768 # every single object ever created.
768 # every single object ever created.
769 sys.modules[main_mod_name] = main_mod
769 sys.modules[main_mod_name] = main_mod
770
770
771 if 'p' in opts or 'd' in opts:
771 if 'p' in opts or 'd' in opts:
772 if 'm' in opts:
772 if 'm' in opts:
773 code = 'run_module(modulename, prog_ns)'
773 code = 'run_module(modulename, prog_ns)'
774 code_ns = {
774 code_ns = {
775 'run_module': self.shell.safe_run_module,
775 'run_module': self.shell.safe_run_module,
776 'prog_ns': prog_ns,
776 'prog_ns': prog_ns,
777 'modulename': modulename,
777 'modulename': modulename,
778 }
778 }
779 else:
779 else:
780 if 'd' in opts:
780 if 'd' in opts:
781 # allow exceptions to raise in debug mode
781 # allow exceptions to raise in debug mode
782 code = 'execfile(filename, prog_ns, raise_exceptions=True)'
782 code = 'execfile(filename, prog_ns, raise_exceptions=True)'
783 else:
783 else:
784 code = 'execfile(filename, prog_ns)'
784 code = 'execfile(filename, prog_ns)'
785 code_ns = {
785 code_ns = {
786 'execfile': self.shell.safe_execfile,
786 'execfile': self.shell.safe_execfile,
787 'prog_ns': prog_ns,
787 'prog_ns': prog_ns,
788 'filename': get_py_filename(filename),
788 'filename': get_py_filename(filename),
789 }
789 }
790
790
791 try:
791 try:
792 stats = None
792 stats = None
793 if 'p' in opts:
793 if 'p' in opts:
794 stats = self._run_with_profiler(code, opts, code_ns)
794 stats = self._run_with_profiler(code, opts, code_ns)
795 else:
795 else:
796 if 'd' in opts:
796 if 'd' in opts:
797 bp_file, bp_line = parse_breakpoint(
797 bp_file, bp_line = parse_breakpoint(
798 opts.get('b', ['1'])[0], filename)
798 opts.get('b', ['1'])[0], filename)
799 self._run_with_debugger(
799 self._run_with_debugger(
800 code, code_ns, filename, bp_line, bp_file)
800 code, code_ns, filename, bp_line, bp_file)
801 else:
801 else:
802 if 'm' in opts:
802 if 'm' in opts:
803 def run():
803 def run():
804 self.shell.safe_run_module(modulename, prog_ns)
804 self.shell.safe_run_module(modulename, prog_ns)
805 else:
805 else:
806 if runner is None:
806 if runner is None:
807 runner = self.default_runner
807 runner = self.default_runner
808 if runner is None:
808 if runner is None:
809 runner = self.shell.safe_execfile
809 runner = self.shell.safe_execfile
810
810
811 def run():
811 def run():
812 runner(filename, prog_ns, prog_ns,
812 runner(filename, prog_ns, prog_ns,
813 exit_ignore=exit_ignore)
813 exit_ignore=exit_ignore)
814
814
815 if 't' in opts:
815 if 't' in opts:
816 # timed execution
816 # timed execution
817 try:
817 try:
818 nruns = int(opts['N'][0])
818 nruns = int(opts['N'][0])
819 if nruns < 1:
819 if nruns < 1:
820 error('Number of runs must be >=1')
820 error('Number of runs must be >=1')
821 return
821 return
822 except (KeyError):
822 except (KeyError):
823 nruns = 1
823 nruns = 1
824 self._run_with_timing(run, nruns)
824 self._run_with_timing(run, nruns)
825 else:
825 else:
826 # regular execution
826 # regular execution
827 run()
827 run()
828
828
829 if 'i' in opts:
829 if 'i' in opts:
830 self.shell.user_ns['__name__'] = __name__save
830 self.shell.user_ns['__name__'] = __name__save
831 else:
831 else:
832 # update IPython interactive namespace
832 # update IPython interactive namespace
833
833
834 # Some forms of read errors on the file may mean the
834 # Some forms of read errors on the file may mean the
835 # __name__ key was never set; using pop we don't have to
835 # __name__ key was never set; using pop we don't have to
836 # worry about a possible KeyError.
836 # worry about a possible KeyError.
837 prog_ns.pop('__name__', None)
837 prog_ns.pop('__name__', None)
838
838
839 with preserve_keys(self.shell.user_ns, '__file__'):
839 with preserve_keys(self.shell.user_ns, '__file__'):
840 self.shell.user_ns.update(prog_ns)
840 self.shell.user_ns.update(prog_ns)
841 finally:
841 finally:
842 # It's a bit of a mystery why, but __builtins__ can change from
842 # It's a bit of a mystery why, but __builtins__ can change from
843 # being a module to becoming a dict missing some key data after
843 # being a module to becoming a dict missing some key data after
844 # %run. As best I can see, this is NOT something IPython is doing
844 # %run. As best I can see, this is NOT something IPython is doing
845 # at all, and similar problems have been reported before:
845 # at all, and similar problems have been reported before:
846 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
846 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
847 # Since this seems to be done by the interpreter itself, the best
847 # Since this seems to be done by the interpreter itself, the best
848 # we can do is to at least restore __builtins__ for the user on
848 # we can do is to at least restore __builtins__ for the user on
849 # exit.
849 # exit.
850 self.shell.user_ns['__builtins__'] = builtin_mod
850 self.shell.user_ns['__builtins__'] = builtin_mod
851
851
852 # Ensure key global structures are restored
852 # Ensure key global structures are restored
853 sys.argv = save_argv
853 sys.argv = save_argv
854 if restore_main:
854 if restore_main:
855 sys.modules['__main__'] = restore_main
855 sys.modules['__main__'] = restore_main
856 if '__mp_main__' in sys.modules:
857 sys.modules['__mp_main__'] = restore_main
856 else:
858 else:
857 # Remove from sys.modules the reference to main_mod we'd
859 # Remove from sys.modules the reference to main_mod we'd
858 # added. Otherwise it will trap references to objects
860 # added. Otherwise it will trap references to objects
859 # contained therein.
861 # contained therein.
860 del sys.modules[main_mod_name]
862 del sys.modules[main_mod_name]
861
863
862 return stats
864 return stats
863
865
864 def _run_with_debugger(self, code, code_ns, filename=None,
866 def _run_with_debugger(self, code, code_ns, filename=None,
865 bp_line=None, bp_file=None):
867 bp_line=None, bp_file=None):
866 """
868 """
867 Run `code` in debugger with a break point.
869 Run `code` in debugger with a break point.
868
870
869 Parameters
871 Parameters
870 ----------
872 ----------
871 code : str
873 code : str
872 Code to execute.
874 Code to execute.
873 code_ns : dict
875 code_ns : dict
874 A namespace in which `code` is executed.
876 A namespace in which `code` is executed.
875 filename : str
877 filename : str
876 `code` is ran as if it is in `filename`.
878 `code` is ran as if it is in `filename`.
877 bp_line : int, optional
879 bp_line : int, optional
878 Line number of the break point.
880 Line number of the break point.
879 bp_file : str, optional
881 bp_file : str, optional
880 Path to the file in which break point is specified.
882 Path to the file in which break point is specified.
881 `filename` is used if not given.
883 `filename` is used if not given.
882
884
883 Raises
885 Raises
884 ------
886 ------
885 UsageError
887 UsageError
886 If the break point given by `bp_line` is not valid.
888 If the break point given by `bp_line` is not valid.
887
889
888 """
890 """
889 deb = self.shell.InteractiveTB.pdb
891 deb = self.shell.InteractiveTB.pdb
890 if not deb:
892 if not deb:
891 self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls()
893 self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls()
892 deb = self.shell.InteractiveTB.pdb
894 deb = self.shell.InteractiveTB.pdb
893
895
894 # deb.checkline() fails if deb.curframe exists but is None; it can
896 # deb.checkline() fails if deb.curframe exists but is None; it can
895 # handle it not existing. https://github.com/ipython/ipython/issues/10028
897 # handle it not existing. https://github.com/ipython/ipython/issues/10028
896 if hasattr(deb, 'curframe'):
898 if hasattr(deb, 'curframe'):
897 del deb.curframe
899 del deb.curframe
898
900
899 # reset Breakpoint state, which is moronically kept
901 # reset Breakpoint state, which is moronically kept
900 # in a class
902 # in a class
901 bdb.Breakpoint.next = 1
903 bdb.Breakpoint.next = 1
902 bdb.Breakpoint.bplist = {}
904 bdb.Breakpoint.bplist = {}
903 bdb.Breakpoint.bpbynumber = [None]
905 bdb.Breakpoint.bpbynumber = [None]
904 deb.clear_all_breaks()
906 deb.clear_all_breaks()
905 if bp_line is not None:
907 if bp_line is not None:
906 # Set an initial breakpoint to stop execution
908 # Set an initial breakpoint to stop execution
907 maxtries = 10
909 maxtries = 10
908 bp_file = bp_file or filename
910 bp_file = bp_file or filename
909 checkline = deb.checkline(bp_file, bp_line)
911 checkline = deb.checkline(bp_file, bp_line)
910 if not checkline:
912 if not checkline:
911 for bp in range(bp_line + 1, bp_line + maxtries + 1):
913 for bp in range(bp_line + 1, bp_line + maxtries + 1):
912 if deb.checkline(bp_file, bp):
914 if deb.checkline(bp_file, bp):
913 break
915 break
914 else:
916 else:
915 msg = ("\nI failed to find a valid line to set "
917 msg = ("\nI failed to find a valid line to set "
916 "a breakpoint\n"
918 "a breakpoint\n"
917 "after trying up to line: %s.\n"
919 "after trying up to line: %s.\n"
918 "Please set a valid breakpoint manually "
920 "Please set a valid breakpoint manually "
919 "with the -b option." % bp)
921 "with the -b option." % bp)
920 raise UsageError(msg)
922 raise UsageError(msg)
921 # if we find a good linenumber, set the breakpoint
923 # if we find a good linenumber, set the breakpoint
922 deb.do_break('%s:%s' % (bp_file, bp_line))
924 deb.do_break('%s:%s' % (bp_file, bp_line))
923
925
924 if filename:
926 if filename:
925 # Mimic Pdb._runscript(...)
927 # Mimic Pdb._runscript(...)
926 deb._wait_for_mainpyfile = True
928 deb._wait_for_mainpyfile = True
927 deb.mainpyfile = deb.canonic(filename)
929 deb.mainpyfile = deb.canonic(filename)
928
930
929 # Start file run
931 # Start file run
930 print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
932 print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
931 try:
933 try:
932 if filename:
934 if filename:
933 # save filename so it can be used by methods on the deb object
935 # save filename so it can be used by methods on the deb object
934 deb._exec_filename = filename
936 deb._exec_filename = filename
935 while True:
937 while True:
936 try:
938 try:
937 trace = sys.gettrace()
939 trace = sys.gettrace()
938 deb.run(code, code_ns)
940 deb.run(code, code_ns)
939 except Restart:
941 except Restart:
940 print("Restarting")
942 print("Restarting")
941 if filename:
943 if filename:
942 deb._wait_for_mainpyfile = True
944 deb._wait_for_mainpyfile = True
943 deb.mainpyfile = deb.canonic(filename)
945 deb.mainpyfile = deb.canonic(filename)
944 continue
946 continue
945 else:
947 else:
946 break
948 break
947 finally:
949 finally:
948 sys.settrace(trace)
950 sys.settrace(trace)
949
951
950
952
951 except:
953 except:
952 etype, value, tb = sys.exc_info()
954 etype, value, tb = sys.exc_info()
953 # Skip three frames in the traceback: the %run one,
955 # Skip three frames in the traceback: the %run one,
954 # one inside bdb.py, and the command-line typed by the
956 # one inside bdb.py, and the command-line typed by the
955 # user (run by exec in pdb itself).
957 # user (run by exec in pdb itself).
956 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
958 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
957
959
958 @staticmethod
960 @staticmethod
959 def _run_with_timing(run, nruns):
961 def _run_with_timing(run, nruns):
960 """
962 """
961 Run function `run` and print timing information.
963 Run function `run` and print timing information.
962
964
963 Parameters
965 Parameters
964 ----------
966 ----------
965 run : callable
967 run : callable
966 Any callable object which takes no argument.
968 Any callable object which takes no argument.
967 nruns : int
969 nruns : int
968 Number of times to execute `run`.
970 Number of times to execute `run`.
969
971
970 """
972 """
971 twall0 = time.perf_counter()
973 twall0 = time.perf_counter()
972 if nruns == 1:
974 if nruns == 1:
973 t0 = clock2()
975 t0 = clock2()
974 run()
976 run()
975 t1 = clock2()
977 t1 = clock2()
976 t_usr = t1[0] - t0[0]
978 t_usr = t1[0] - t0[0]
977 t_sys = t1[1] - t0[1]
979 t_sys = t1[1] - t0[1]
978 print("\nIPython CPU timings (estimated):")
980 print("\nIPython CPU timings (estimated):")
979 print(" User : %10.2f s." % t_usr)
981 print(" User : %10.2f s." % t_usr)
980 print(" System : %10.2f s." % t_sys)
982 print(" System : %10.2f s." % t_sys)
981 else:
983 else:
982 runs = range(nruns)
984 runs = range(nruns)
983 t0 = clock2()
985 t0 = clock2()
984 for nr in runs:
986 for nr in runs:
985 run()
987 run()
986 t1 = clock2()
988 t1 = clock2()
987 t_usr = t1[0] - t0[0]
989 t_usr = t1[0] - t0[0]
988 t_sys = t1[1] - t0[1]
990 t_sys = t1[1] - t0[1]
989 print("\nIPython CPU timings (estimated):")
991 print("\nIPython CPU timings (estimated):")
990 print("Total runs performed:", nruns)
992 print("Total runs performed:", nruns)
991 print(" Times : %10s %10s" % ('Total', 'Per run'))
993 print(" Times : %10s %10s" % ('Total', 'Per run'))
992 print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns))
994 print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns))
993 print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns))
995 print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns))
994 twall1 = time.perf_counter()
996 twall1 = time.perf_counter()
995 print("Wall time: %10.2f s." % (twall1 - twall0))
997 print("Wall time: %10.2f s." % (twall1 - twall0))
996
998
997 @skip_doctest
999 @skip_doctest
998 @no_var_expand
1000 @no_var_expand
999 @line_cell_magic
1001 @line_cell_magic
1000 @needs_local_scope
1002 @needs_local_scope
1001 def timeit(self, line='', cell=None, local_ns=None):
1003 def timeit(self, line='', cell=None, local_ns=None):
1002 """Time execution of a Python statement or expression
1004 """Time execution of a Python statement or expression
1003
1005
1004 Usage, in line mode:
1006 Usage, in line mode:
1005 %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
1007 %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
1006 or in cell mode:
1008 or in cell mode:
1007 %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
1009 %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
1008 code
1010 code
1009 code...
1011 code...
1010
1012
1011 Time execution of a Python statement or expression using the timeit
1013 Time execution of a Python statement or expression using the timeit
1012 module. This function can be used both as a line and cell magic:
1014 module. This function can be used both as a line and cell magic:
1013
1015
1014 - In line mode you can time a single-line statement (though multiple
1016 - In line mode you can time a single-line statement (though multiple
1015 ones can be chained with using semicolons).
1017 ones can be chained with using semicolons).
1016
1018
1017 - In cell mode, the statement in the first line is used as setup code
1019 - In cell mode, the statement in the first line is used as setup code
1018 (executed but not timed) and the body of the cell is timed. The cell
1020 (executed but not timed) and the body of the cell is timed. The cell
1019 body has access to any variables created in the setup code.
1021 body has access to any variables created in the setup code.
1020
1022
1021 Options:
1023 Options:
1022 -n<N>: execute the given statement <N> times in a loop. If <N> is not
1024 -n<N>: execute the given statement <N> times in a loop. If <N> is not
1023 provided, <N> is determined so as to get sufficient accuracy.
1025 provided, <N> is determined so as to get sufficient accuracy.
1024
1026
1025 -r<R>: number of repeats <R>, each consisting of <N> loops, and take the
1027 -r<R>: number of repeats <R>, each consisting of <N> loops, and take the
1026 best result.
1028 best result.
1027 Default: 7
1029 Default: 7
1028
1030
1029 -t: use time.time to measure the time, which is the default on Unix.
1031 -t: use time.time to measure the time, which is the default on Unix.
1030 This function measures wall time.
1032 This function measures wall time.
1031
1033
1032 -c: use time.clock to measure the time, which is the default on
1034 -c: use time.clock to measure the time, which is the default on
1033 Windows and measures wall time. On Unix, resource.getrusage is used
1035 Windows and measures wall time. On Unix, resource.getrusage is used
1034 instead and returns the CPU user time.
1036 instead and returns the CPU user time.
1035
1037
1036 -p<P>: use a precision of <P> digits to display the timing result.
1038 -p<P>: use a precision of <P> digits to display the timing result.
1037 Default: 3
1039 Default: 3
1038
1040
1039 -q: Quiet, do not print result.
1041 -q: Quiet, do not print result.
1040
1042
1041 -o: return a TimeitResult that can be stored in a variable to inspect
1043 -o: return a TimeitResult that can be stored in a variable to inspect
1042 the result in more details.
1044 the result in more details.
1043
1045
1044 .. versionchanged:: 7.3
1046 .. versionchanged:: 7.3
1045 User variables are no longer expanded,
1047 User variables are no longer expanded,
1046 the magic line is always left unmodified.
1048 the magic line is always left unmodified.
1047
1049
1048 Examples
1050 Examples
1049 --------
1051 --------
1050 ::
1052 ::
1051
1053
1052 In [1]: %timeit pass
1054 In [1]: %timeit pass
1053 8.26 ns ± 0.12 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)
1055 8.26 ns ± 0.12 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)
1054
1056
1055 In [2]: u = None
1057 In [2]: u = None
1056
1058
1057 In [3]: %timeit u is None
1059 In [3]: %timeit u is None
1058 29.9 ns ± 0.643 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
1060 29.9 ns ± 0.643 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
1059
1061
1060 In [4]: %timeit -r 4 u == None
1062 In [4]: %timeit -r 4 u == None
1061
1063
1062 In [5]: import time
1064 In [5]: import time
1063
1065
1064 In [6]: %timeit -n1 time.sleep(2)
1066 In [6]: %timeit -n1 time.sleep(2)
1065
1067
1066
1068
1067 The times reported by %timeit will be slightly higher than those
1069 The times reported by %timeit will be slightly higher than those
1068 reported by the timeit.py script when variables are accessed. This is
1070 reported by the timeit.py script when variables are accessed. This is
1069 due to the fact that %timeit executes the statement in the namespace
1071 due to the fact that %timeit executes the statement in the namespace
1070 of the shell, compared with timeit.py, which uses a single setup
1072 of the shell, compared with timeit.py, which uses a single setup
1071 statement to import function or create variables. Generally, the bias
1073 statement to import function or create variables. Generally, the bias
1072 does not matter as long as results from timeit.py are not mixed with
1074 does not matter as long as results from timeit.py are not mixed with
1073 those from %timeit."""
1075 those from %timeit."""
1074
1076
1075 opts, stmt = self.parse_options(line,'n:r:tcp:qo',
1077 opts, stmt = self.parse_options(line,'n:r:tcp:qo',
1076 posix=False, strict=False)
1078 posix=False, strict=False)
1077 if stmt == "" and cell is None:
1079 if stmt == "" and cell is None:
1078 return
1080 return
1079
1081
1080 timefunc = timeit.default_timer
1082 timefunc = timeit.default_timer
1081 number = int(getattr(opts, "n", 0))
1083 number = int(getattr(opts, "n", 0))
1082 default_repeat = 7 if timeit.default_repeat < 7 else timeit.default_repeat
1084 default_repeat = 7 if timeit.default_repeat < 7 else timeit.default_repeat
1083 repeat = int(getattr(opts, "r", default_repeat))
1085 repeat = int(getattr(opts, "r", default_repeat))
1084 precision = int(getattr(opts, "p", 3))
1086 precision = int(getattr(opts, "p", 3))
1085 quiet = 'q' in opts
1087 quiet = 'q' in opts
1086 return_result = 'o' in opts
1088 return_result = 'o' in opts
1087 if hasattr(opts, "t"):
1089 if hasattr(opts, "t"):
1088 timefunc = time.time
1090 timefunc = time.time
1089 if hasattr(opts, "c"):
1091 if hasattr(opts, "c"):
1090 timefunc = clock
1092 timefunc = clock
1091
1093
1092 timer = Timer(timer=timefunc)
1094 timer = Timer(timer=timefunc)
1093 # this code has tight coupling to the inner workings of timeit.Timer,
1095 # this code has tight coupling to the inner workings of timeit.Timer,
1094 # but is there a better way to achieve that the code stmt has access
1096 # but is there a better way to achieve that the code stmt has access
1095 # to the shell namespace?
1097 # to the shell namespace?
1096 transform = self.shell.transform_cell
1098 transform = self.shell.transform_cell
1097
1099
1098 if cell is None:
1100 if cell is None:
1099 # called as line magic
1101 # called as line magic
1100 ast_setup = self.shell.compile.ast_parse("pass")
1102 ast_setup = self.shell.compile.ast_parse("pass")
1101 ast_stmt = self.shell.compile.ast_parse(transform(stmt))
1103 ast_stmt = self.shell.compile.ast_parse(transform(stmt))
1102 else:
1104 else:
1103 ast_setup = self.shell.compile.ast_parse(transform(stmt))
1105 ast_setup = self.shell.compile.ast_parse(transform(stmt))
1104 ast_stmt = self.shell.compile.ast_parse(transform(cell))
1106 ast_stmt = self.shell.compile.ast_parse(transform(cell))
1105
1107
1106 ast_setup = self.shell.transform_ast(ast_setup)
1108 ast_setup = self.shell.transform_ast(ast_setup)
1107 ast_stmt = self.shell.transform_ast(ast_stmt)
1109 ast_stmt = self.shell.transform_ast(ast_stmt)
1108
1110
1109 # Check that these compile to valid Python code *outside* the timer func
1111 # Check that these compile to valid Python code *outside* the timer func
1110 # Invalid code may become valid when put inside the function & loop,
1112 # Invalid code may become valid when put inside the function & loop,
1111 # which messes up error messages.
1113 # which messes up error messages.
1112 # https://github.com/ipython/ipython/issues/10636
1114 # https://github.com/ipython/ipython/issues/10636
1113 self.shell.compile(ast_setup, "<magic-timeit-setup>", "exec")
1115 self.shell.compile(ast_setup, "<magic-timeit-setup>", "exec")
1114 self.shell.compile(ast_stmt, "<magic-timeit-stmt>", "exec")
1116 self.shell.compile(ast_stmt, "<magic-timeit-stmt>", "exec")
1115
1117
1116 # This codestring is taken from timeit.template - we fill it in as an
1118 # This codestring is taken from timeit.template - we fill it in as an
1117 # AST, so that we can apply our AST transformations to the user code
1119 # AST, so that we can apply our AST transformations to the user code
1118 # without affecting the timing code.
1120 # without affecting the timing code.
1119 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
1121 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
1120 ' setup\n'
1122 ' setup\n'
1121 ' _t0 = _timer()\n'
1123 ' _t0 = _timer()\n'
1122 ' for _i in _it:\n'
1124 ' for _i in _it:\n'
1123 ' stmt\n'
1125 ' stmt\n'
1124 ' _t1 = _timer()\n'
1126 ' _t1 = _timer()\n'
1125 ' return _t1 - _t0\n')
1127 ' return _t1 - _t0\n')
1126
1128
1127 timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
1129 timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
1128 timeit_ast = ast.fix_missing_locations(timeit_ast)
1130 timeit_ast = ast.fix_missing_locations(timeit_ast)
1129
1131
1130 # Track compilation time so it can be reported if too long
1132 # Track compilation time so it can be reported if too long
1131 # Minimum time above which compilation time will be reported
1133 # Minimum time above which compilation time will be reported
1132 tc_min = 0.1
1134 tc_min = 0.1
1133
1135
1134 t0 = clock()
1136 t0 = clock()
1135 code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
1137 code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
1136 tc = clock()-t0
1138 tc = clock()-t0
1137
1139
1138 ns = {}
1140 ns = {}
1139 glob = self.shell.user_ns
1141 glob = self.shell.user_ns
1140 # handles global vars with same name as local vars. We store them in conflict_globs.
1142 # handles global vars with same name as local vars. We store them in conflict_globs.
1141 conflict_globs = {}
1143 conflict_globs = {}
1142 if local_ns and cell is None:
1144 if local_ns and cell is None:
1143 for var_name, var_val in glob.items():
1145 for var_name, var_val in glob.items():
1144 if var_name in local_ns:
1146 if var_name in local_ns:
1145 conflict_globs[var_name] = var_val
1147 conflict_globs[var_name] = var_val
1146 glob.update(local_ns)
1148 glob.update(local_ns)
1147
1149
1148 exec(code, glob, ns)
1150 exec(code, glob, ns)
1149 timer.inner = ns["inner"]
1151 timer.inner = ns["inner"]
1150
1152
1151 # This is used to check if there is a huge difference between the
1153 # This is used to check if there is a huge difference between the
1152 # best and worst timings.
1154 # best and worst timings.
1153 # Issue: https://github.com/ipython/ipython/issues/6471
1155 # Issue: https://github.com/ipython/ipython/issues/6471
1154 if number == 0:
1156 if number == 0:
1155 # determine number so that 0.2 <= total time < 2.0
1157 # determine number so that 0.2 <= total time < 2.0
1156 for index in range(0, 10):
1158 for index in range(0, 10):
1157 number = 10 ** index
1159 number = 10 ** index
1158 time_number = timer.timeit(number)
1160 time_number = timer.timeit(number)
1159 if time_number >= 0.2:
1161 if time_number >= 0.2:
1160 break
1162 break
1161
1163
1162 all_runs = timer.repeat(repeat, number)
1164 all_runs = timer.repeat(repeat, number)
1163 best = min(all_runs) / number
1165 best = min(all_runs) / number
1164 worst = max(all_runs) / number
1166 worst = max(all_runs) / number
1165 timeit_result = TimeitResult(number, repeat, best, worst, all_runs, tc, precision)
1167 timeit_result = TimeitResult(number, repeat, best, worst, all_runs, tc, precision)
1166
1168
1167 # Restore global vars from conflict_globs
1169 # Restore global vars from conflict_globs
1168 if conflict_globs:
1170 if conflict_globs:
1169 glob.update(conflict_globs)
1171 glob.update(conflict_globs)
1170
1172
1171 if not quiet :
1173 if not quiet :
1172 # Check best timing is greater than zero to avoid a
1174 # Check best timing is greater than zero to avoid a
1173 # ZeroDivisionError.
1175 # ZeroDivisionError.
1174 # In cases where the slowest timing is lesser than a microsecond
1176 # In cases where the slowest timing is lesser than a microsecond
1175 # we assume that it does not really matter if the fastest
1177 # we assume that it does not really matter if the fastest
1176 # timing is 4 times faster than the slowest timing or not.
1178 # timing is 4 times faster than the slowest timing or not.
1177 if worst > 4 * best and best > 0 and worst > 1e-6:
1179 if worst > 4 * best and best > 0 and worst > 1e-6:
1178 print("The slowest run took %0.2f times longer than the "
1180 print("The slowest run took %0.2f times longer than the "
1179 "fastest. This could mean that an intermediate result "
1181 "fastest. This could mean that an intermediate result "
1180 "is being cached." % (worst / best))
1182 "is being cached." % (worst / best))
1181
1183
1182 print( timeit_result )
1184 print( timeit_result )
1183
1185
1184 if tc > tc_min:
1186 if tc > tc_min:
1185 print("Compiler time: %.2f s" % tc)
1187 print("Compiler time: %.2f s" % tc)
1186 if return_result:
1188 if return_result:
1187 return timeit_result
1189 return timeit_result
1188
1190
1189 @skip_doctest
1191 @skip_doctest
1190 @no_var_expand
1192 @no_var_expand
1191 @needs_local_scope
1193 @needs_local_scope
1192 @line_cell_magic
1194 @line_cell_magic
1193 def time(self,line='', cell=None, local_ns=None):
1195 def time(self,line='', cell=None, local_ns=None):
1194 """Time execution of a Python statement or expression.
1196 """Time execution of a Python statement or expression.
1195
1197
1196 The CPU and wall clock times are printed, and the value of the
1198 The CPU and wall clock times are printed, and the value of the
1197 expression (if any) is returned. Note that under Win32, system time
1199 expression (if any) is returned. Note that under Win32, system time
1198 is always reported as 0, since it can not be measured.
1200 is always reported as 0, since it can not be measured.
1199
1201
1200 This function can be used both as a line and cell magic:
1202 This function can be used both as a line and cell magic:
1201
1203
1202 - In line mode you can time a single-line statement (though multiple
1204 - In line mode you can time a single-line statement (though multiple
1203 ones can be chained with using semicolons).
1205 ones can be chained with using semicolons).
1204
1206
1205 - In cell mode, you can time the cell body (a directly
1207 - In cell mode, you can time the cell body (a directly
1206 following statement raises an error).
1208 following statement raises an error).
1207
1209
1208 This function provides very basic timing functionality. Use the timeit
1210 This function provides very basic timing functionality. Use the timeit
1209 magic for more control over the measurement.
1211 magic for more control over the measurement.
1210
1212
1211 .. versionchanged:: 7.3
1213 .. versionchanged:: 7.3
1212 User variables are no longer expanded,
1214 User variables are no longer expanded,
1213 the magic line is always left unmodified.
1215 the magic line is always left unmodified.
1214
1216
1215 Examples
1217 Examples
1216 --------
1218 --------
1217 ::
1219 ::
1218
1220
1219 In [1]: %time 2**128
1221 In [1]: %time 2**128
1220 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1222 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1221 Wall time: 0.00
1223 Wall time: 0.00
1222 Out[1]: 340282366920938463463374607431768211456L
1224 Out[1]: 340282366920938463463374607431768211456L
1223
1225
1224 In [2]: n = 1000000
1226 In [2]: n = 1000000
1225
1227
1226 In [3]: %time sum(range(n))
1228 In [3]: %time sum(range(n))
1227 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1229 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1228 Wall time: 1.37
1230 Wall time: 1.37
1229 Out[3]: 499999500000L
1231 Out[3]: 499999500000L
1230
1232
1231 In [4]: %time print 'hello world'
1233 In [4]: %time print 'hello world'
1232 hello world
1234 hello world
1233 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1235 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1234 Wall time: 0.00
1236 Wall time: 0.00
1235
1237
1236 Note that the time needed by Python to compile the given expression
1238 Note that the time needed by Python to compile the given expression
1237 will be reported if it is more than 0.1s. In this example, the
1239 will be reported if it is more than 0.1s. In this example, the
1238 actual exponentiation is done by Python at compilation time, so while
1240 actual exponentiation is done by Python at compilation time, so while
1239 the expression can take a noticeable amount of time to compute, that
1241 the expression can take a noticeable amount of time to compute, that
1240 time is purely due to the compilation:
1242 time is purely due to the compilation:
1241
1243
1242 In [5]: %time 3**9999;
1244 In [5]: %time 3**9999;
1243 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1245 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1244 Wall time: 0.00 s
1246 Wall time: 0.00 s
1245
1247
1246 In [6]: %time 3**999999;
1248 In [6]: %time 3**999999;
1247 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1249 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1248 Wall time: 0.00 s
1250 Wall time: 0.00 s
1249 Compiler : 0.78 s
1251 Compiler : 0.78 s
1250 """
1252 """
1251
1253
1252 # fail immediately if the given expression can't be compiled
1254 # fail immediately if the given expression can't be compiled
1253
1255
1254 if line and cell:
1256 if line and cell:
1255 raise UsageError("Can't use statement directly after '%%time'!")
1257 raise UsageError("Can't use statement directly after '%%time'!")
1256
1258
1257 if cell:
1259 if cell:
1258 expr = self.shell.transform_cell(cell)
1260 expr = self.shell.transform_cell(cell)
1259 else:
1261 else:
1260 expr = self.shell.transform_cell(line)
1262 expr = self.shell.transform_cell(line)
1261
1263
1262 # Minimum time above which parse time will be reported
1264 # Minimum time above which parse time will be reported
1263 tp_min = 0.1
1265 tp_min = 0.1
1264
1266
1265 t0 = clock()
1267 t0 = clock()
1266 expr_ast = self.shell.compile.ast_parse(expr)
1268 expr_ast = self.shell.compile.ast_parse(expr)
1267 tp = clock()-t0
1269 tp = clock()-t0
1268
1270
1269 # Apply AST transformations
1271 # Apply AST transformations
1270 expr_ast = self.shell.transform_ast(expr_ast)
1272 expr_ast = self.shell.transform_ast(expr_ast)
1271
1273
1272 # Minimum time above which compilation time will be reported
1274 # Minimum time above which compilation time will be reported
1273 tc_min = 0.1
1275 tc_min = 0.1
1274
1276
1275 expr_val=None
1277 expr_val=None
1276 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
1278 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
1277 mode = 'eval'
1279 mode = 'eval'
1278 source = '<timed eval>'
1280 source = '<timed eval>'
1279 expr_ast = ast.Expression(expr_ast.body[0].value)
1281 expr_ast = ast.Expression(expr_ast.body[0].value)
1280 else:
1282 else:
1281 mode = 'exec'
1283 mode = 'exec'
1282 source = '<timed exec>'
1284 source = '<timed exec>'
1283 # multi-line %%time case
1285 # multi-line %%time case
1284 if len(expr_ast.body) > 1 and isinstance(expr_ast.body[-1], ast.Expr):
1286 if len(expr_ast.body) > 1 and isinstance(expr_ast.body[-1], ast.Expr):
1285 expr_val= expr_ast.body[-1]
1287 expr_val= expr_ast.body[-1]
1286 expr_ast = expr_ast.body[:-1]
1288 expr_ast = expr_ast.body[:-1]
1287 expr_ast = Module(expr_ast, [])
1289 expr_ast = Module(expr_ast, [])
1288 expr_val = ast.Expression(expr_val.value)
1290 expr_val = ast.Expression(expr_val.value)
1289
1291
1290 t0 = clock()
1292 t0 = clock()
1291 code = self.shell.compile(expr_ast, source, mode)
1293 code = self.shell.compile(expr_ast, source, mode)
1292 tc = clock()-t0
1294 tc = clock()-t0
1293
1295
1294 # skew measurement as little as possible
1296 # skew measurement as little as possible
1295 glob = self.shell.user_ns
1297 glob = self.shell.user_ns
1296 wtime = time.time
1298 wtime = time.time
1297 # time execution
1299 # time execution
1298 wall_st = wtime()
1300 wall_st = wtime()
1299 if mode=='eval':
1301 if mode=='eval':
1300 st = clock2()
1302 st = clock2()
1301 try:
1303 try:
1302 out = eval(code, glob, local_ns)
1304 out = eval(code, glob, local_ns)
1303 except:
1305 except:
1304 self.shell.showtraceback()
1306 self.shell.showtraceback()
1305 return
1307 return
1306 end = clock2()
1308 end = clock2()
1307 else:
1309 else:
1308 st = clock2()
1310 st = clock2()
1309 try:
1311 try:
1310 exec(code, glob, local_ns)
1312 exec(code, glob, local_ns)
1311 out=None
1313 out=None
1312 # multi-line %%time case
1314 # multi-line %%time case
1313 if expr_val is not None:
1315 if expr_val is not None:
1314 code_2 = self.shell.compile(expr_val, source, 'eval')
1316 code_2 = self.shell.compile(expr_val, source, 'eval')
1315 out = eval(code_2, glob, local_ns)
1317 out = eval(code_2, glob, local_ns)
1316 except:
1318 except:
1317 self.shell.showtraceback()
1319 self.shell.showtraceback()
1318 return
1320 return
1319 end = clock2()
1321 end = clock2()
1320
1322
1321 wall_end = wtime()
1323 wall_end = wtime()
1322 # Compute actual times and report
1324 # Compute actual times and report
1323 wall_time = wall_end-wall_st
1325 wall_time = wall_end-wall_st
1324 cpu_user = end[0]-st[0]
1326 cpu_user = end[0]-st[0]
1325 cpu_sys = end[1]-st[1]
1327 cpu_sys = end[1]-st[1]
1326 cpu_tot = cpu_user+cpu_sys
1328 cpu_tot = cpu_user+cpu_sys
1327 # On windows cpu_sys is always zero, so no new information to the next print
1329 # On windows cpu_sys is always zero, so no new information to the next print
1328 if sys.platform != 'win32':
1330 if sys.platform != 'win32':
1329 print("CPU times: user %s, sys: %s, total: %s" % \
1331 print("CPU times: user %s, sys: %s, total: %s" % \
1330 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
1332 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
1331 print("Wall time: %s" % _format_time(wall_time))
1333 print("Wall time: %s" % _format_time(wall_time))
1332 if tc > tc_min:
1334 if tc > tc_min:
1333 print("Compiler : %s" % _format_time(tc))
1335 print("Compiler : %s" % _format_time(tc))
1334 if tp > tp_min:
1336 if tp > tp_min:
1335 print("Parser : %s" % _format_time(tp))
1337 print("Parser : %s" % _format_time(tp))
1336 return out
1338 return out
1337
1339
1338 @skip_doctest
1340 @skip_doctest
1339 @line_magic
1341 @line_magic
1340 def macro(self, parameter_s=''):
1342 def macro(self, parameter_s=''):
1341 """Define a macro for future re-execution. It accepts ranges of history,
1343 """Define a macro for future re-execution. It accepts ranges of history,
1342 filenames or string objects.
1344 filenames or string objects.
1343
1345
1344 Usage:\\
1346 Usage:\\
1345 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1347 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1346
1348
1347 Options:
1349 Options:
1348
1350
1349 -r: use 'raw' input. By default, the 'processed' history is used,
1351 -r: use 'raw' input. By default, the 'processed' history is used,
1350 so that magics are loaded in their transformed version to valid
1352 so that magics are loaded in their transformed version to valid
1351 Python. If this option is given, the raw input as typed at the
1353 Python. If this option is given, the raw input as typed at the
1352 command line is used instead.
1354 command line is used instead.
1353
1355
1354 -q: quiet macro definition. By default, a tag line is printed
1356 -q: quiet macro definition. By default, a tag line is printed
1355 to indicate the macro has been created, and then the contents of
1357 to indicate the macro has been created, and then the contents of
1356 the macro are printed. If this option is given, then no printout
1358 the macro are printed. If this option is given, then no printout
1357 is produced once the macro is created.
1359 is produced once the macro is created.
1358
1360
1359 This will define a global variable called `name` which is a string
1361 This will define a global variable called `name` which is a string
1360 made of joining the slices and lines you specify (n1,n2,... numbers
1362 made of joining the slices and lines you specify (n1,n2,... numbers
1361 above) from your input history into a single string. This variable
1363 above) from your input history into a single string. This variable
1362 acts like an automatic function which re-executes those lines as if
1364 acts like an automatic function which re-executes those lines as if
1363 you had typed them. You just type 'name' at the prompt and the code
1365 you had typed them. You just type 'name' at the prompt and the code
1364 executes.
1366 executes.
1365
1367
1366 The syntax for indicating input ranges is described in %history.
1368 The syntax for indicating input ranges is described in %history.
1367
1369
1368 Note: as a 'hidden' feature, you can also use traditional python slice
1370 Note: as a 'hidden' feature, you can also use traditional python slice
1369 notation, where N:M means numbers N through M-1.
1371 notation, where N:M means numbers N through M-1.
1370
1372
1371 For example, if your history contains (print using %hist -n )::
1373 For example, if your history contains (print using %hist -n )::
1372
1374
1373 44: x=1
1375 44: x=1
1374 45: y=3
1376 45: y=3
1375 46: z=x+y
1377 46: z=x+y
1376 47: print x
1378 47: print x
1377 48: a=5
1379 48: a=5
1378 49: print 'x',x,'y',y
1380 49: print 'x',x,'y',y
1379
1381
1380 you can create a macro with lines 44 through 47 (included) and line 49
1382 you can create a macro with lines 44 through 47 (included) and line 49
1381 called my_macro with::
1383 called my_macro with::
1382
1384
1383 In [55]: %macro my_macro 44-47 49
1385 In [55]: %macro my_macro 44-47 49
1384
1386
1385 Now, typing `my_macro` (without quotes) will re-execute all this code
1387 Now, typing `my_macro` (without quotes) will re-execute all this code
1386 in one pass.
1388 in one pass.
1387
1389
1388 You don't need to give the line-numbers in order, and any given line
1390 You don't need to give the line-numbers in order, and any given line
1389 number can appear multiple times. You can assemble macros with any
1391 number can appear multiple times. You can assemble macros with any
1390 lines from your input history in any order.
1392 lines from your input history in any order.
1391
1393
1392 The macro is a simple object which holds its value in an attribute,
1394 The macro is a simple object which holds its value in an attribute,
1393 but IPython's display system checks for macros and executes them as
1395 but IPython's display system checks for macros and executes them as
1394 code instead of printing them when you type their name.
1396 code instead of printing them when you type their name.
1395
1397
1396 You can view a macro's contents by explicitly printing it with::
1398 You can view a macro's contents by explicitly printing it with::
1397
1399
1398 print macro_name
1400 print macro_name
1399
1401
1400 """
1402 """
1401 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1403 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1402 if not args: # List existing macros
1404 if not args: # List existing macros
1403 return sorted(k for k,v in self.shell.user_ns.items() if isinstance(v, Macro))
1405 return sorted(k for k,v in self.shell.user_ns.items() if isinstance(v, Macro))
1404 if len(args) == 1:
1406 if len(args) == 1:
1405 raise UsageError(
1407 raise UsageError(
1406 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1408 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1407 name, codefrom = args[0], " ".join(args[1:])
1409 name, codefrom = args[0], " ".join(args[1:])
1408
1410
1409 #print 'rng',ranges # dbg
1411 #print 'rng',ranges # dbg
1410 try:
1412 try:
1411 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1413 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1412 except (ValueError, TypeError) as e:
1414 except (ValueError, TypeError) as e:
1413 print(e.args[0])
1415 print(e.args[0])
1414 return
1416 return
1415 macro = Macro(lines)
1417 macro = Macro(lines)
1416 self.shell.define_macro(name, macro)
1418 self.shell.define_macro(name, macro)
1417 if not ( 'q' in opts) :
1419 if not ( 'q' in opts) :
1418 print('Macro `%s` created. To execute, type its name (without quotes).' % name)
1420 print('Macro `%s` created. To execute, type its name (without quotes).' % name)
1419 print('=== Macro contents: ===')
1421 print('=== Macro contents: ===')
1420 print(macro, end=' ')
1422 print(macro, end=' ')
1421
1423
1422 @magic_arguments.magic_arguments()
1424 @magic_arguments.magic_arguments()
1423 @magic_arguments.argument('output', type=str, default='', nargs='?',
1425 @magic_arguments.argument('output', type=str, default='', nargs='?',
1424 help="""The name of the variable in which to store output.
1426 help="""The name of the variable in which to store output.
1425 This is a utils.io.CapturedIO object with stdout/err attributes
1427 This is a utils.io.CapturedIO object with stdout/err attributes
1426 for the text of the captured output.
1428 for the text of the captured output.
1427
1429
1428 CapturedOutput also has a show() method for displaying the output,
1430 CapturedOutput also has a show() method for displaying the output,
1429 and __call__ as well, so you can use that to quickly display the
1431 and __call__ as well, so you can use that to quickly display the
1430 output.
1432 output.
1431
1433
1432 If unspecified, captured output is discarded.
1434 If unspecified, captured output is discarded.
1433 """
1435 """
1434 )
1436 )
1435 @magic_arguments.argument('--no-stderr', action="store_true",
1437 @magic_arguments.argument('--no-stderr', action="store_true",
1436 help="""Don't capture stderr."""
1438 help="""Don't capture stderr."""
1437 )
1439 )
1438 @magic_arguments.argument('--no-stdout', action="store_true",
1440 @magic_arguments.argument('--no-stdout', action="store_true",
1439 help="""Don't capture stdout."""
1441 help="""Don't capture stdout."""
1440 )
1442 )
1441 @magic_arguments.argument('--no-display', action="store_true",
1443 @magic_arguments.argument('--no-display', action="store_true",
1442 help="""Don't capture IPython's rich display."""
1444 help="""Don't capture IPython's rich display."""
1443 )
1445 )
1444 @cell_magic
1446 @cell_magic
1445 def capture(self, line, cell):
1447 def capture(self, line, cell):
1446 """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
1448 """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
1447 args = magic_arguments.parse_argstring(self.capture, line)
1449 args = magic_arguments.parse_argstring(self.capture, line)
1448 out = not args.no_stdout
1450 out = not args.no_stdout
1449 err = not args.no_stderr
1451 err = not args.no_stderr
1450 disp = not args.no_display
1452 disp = not args.no_display
1451 with capture_output(out, err, disp) as io:
1453 with capture_output(out, err, disp) as io:
1452 self.shell.run_cell(cell)
1454 self.shell.run_cell(cell)
1453 if args.output:
1455 if args.output:
1454 self.shell.user_ns[args.output] = io
1456 self.shell.user_ns[args.output] = io
1455
1457
1456 def parse_breakpoint(text, current_file):
1458 def parse_breakpoint(text, current_file):
1457 '''Returns (file, line) for file:line and (current_file, line) for line'''
1459 '''Returns (file, line) for file:line and (current_file, line) for line'''
1458 colon = text.find(':')
1460 colon = text.find(':')
1459 if colon == -1:
1461 if colon == -1:
1460 return current_file, int(text)
1462 return current_file, int(text)
1461 else:
1463 else:
1462 return text[:colon], int(text[colon+1:])
1464 return text[:colon], int(text[colon+1:])
1463
1465
1464 def _format_time(timespan, precision=3):
1466 def _format_time(timespan, precision=3):
1465 """Formats the timespan in a human readable form"""
1467 """Formats the timespan in a human readable form"""
1466
1468
1467 if timespan >= 60.0:
1469 if timespan >= 60.0:
1468 # we have more than a minute, format that in a human readable form
1470 # we have more than a minute, format that in a human readable form
1469 # Idea from http://snipplr.com/view/5713/
1471 # Idea from http://snipplr.com/view/5713/
1470 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1472 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1471 time = []
1473 time = []
1472 leftover = timespan
1474 leftover = timespan
1473 for suffix, length in parts:
1475 for suffix, length in parts:
1474 value = int(leftover / length)
1476 value = int(leftover / length)
1475 if value > 0:
1477 if value > 0:
1476 leftover = leftover % length
1478 leftover = leftover % length
1477 time.append(u'%s%s' % (str(value), suffix))
1479 time.append(u'%s%s' % (str(value), suffix))
1478 if leftover < 1:
1480 if leftover < 1:
1479 break
1481 break
1480 return " ".join(time)
1482 return " ".join(time)
1481
1483
1482
1484
1483 # Unfortunately the unicode 'micro' symbol can cause problems in
1485 # Unfortunately the unicode 'micro' symbol can cause problems in
1484 # certain terminals.
1486 # certain terminals.
1485 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1487 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1486 # Try to prevent crashes by being more secure than it needs to
1488 # Try to prevent crashes by being more secure than it needs to
1487 # E.g. eclipse is able to print a µ, but has no sys.stdout.encoding set.
1489 # E.g. eclipse is able to print a µ, but has no sys.stdout.encoding set.
1488 units = [u"s", u"ms",u'us',"ns"] # the save value
1490 units = [u"s", u"ms",u'us',"ns"] # the save value
1489 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1491 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1490 try:
1492 try:
1491 u'\xb5'.encode(sys.stdout.encoding)
1493 u'\xb5'.encode(sys.stdout.encoding)
1492 units = [u"s", u"ms",u'\xb5s',"ns"]
1494 units = [u"s", u"ms",u'\xb5s',"ns"]
1493 except:
1495 except:
1494 pass
1496 pass
1495 scaling = [1, 1e3, 1e6, 1e9]
1497 scaling = [1, 1e3, 1e6, 1e9]
1496
1498
1497 if timespan > 0.0:
1499 if timespan > 0.0:
1498 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1500 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1499 else:
1501 else:
1500 order = 3
1502 order = 3
1501 return u"%.*g %s" % (precision, timespan * scaling[order], units[order])
1503 return u"%.*g %s" % (precision, timespan * scaling[order], units[order])
@@ -1,1072 +1,1058 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Tools for inspecting Python objects.
2 """Tools for inspecting Python objects.
3
3
4 Uses syntax highlighting for presenting the various information elements.
4 Uses syntax highlighting for presenting the various information elements.
5
5
6 Similar in spirit to the inspect module, but all calls take a name argument to
6 Similar in spirit to the inspect module, but all calls take a name argument to
7 reference the name under which an object is being read.
7 reference the name under which an object is being read.
8 """
8 """
9
9
10 # Copyright (c) IPython Development Team.
10 # Copyright (c) IPython Development Team.
11 # Distributed under the terms of the Modified BSD License.
11 # Distributed under the terms of the Modified BSD License.
12
12
13 __all__ = ['Inspector','InspectColors']
13 __all__ = ['Inspector','InspectColors']
14
14
15 # stdlib modules
15 # stdlib modules
16 import ast
16 import ast
17 import inspect
17 import inspect
18 from inspect import signature
18 from inspect import signature
19 import linecache
19 import linecache
20 import warnings
20 import warnings
21 import os
21 import os
22 from textwrap import dedent
22 from textwrap import dedent
23 import types
23 import types
24 import io as stdlib_io
24 import io as stdlib_io
25 from itertools import zip_longest
25 from itertools import zip_longest
26
26
27 # IPython's own
27 # IPython's own
28 from IPython.core import page
28 from IPython.core import page
29 from IPython.lib.pretty import pretty
29 from IPython.lib.pretty import pretty
30 from IPython.testing.skipdoctest import skip_doctest
30 from IPython.testing.skipdoctest import skip_doctest
31 from IPython.utils import PyColorize
31 from IPython.utils import PyColorize
32 from IPython.utils import openpy
32 from IPython.utils import openpy
33 from IPython.utils import py3compat
33 from IPython.utils import py3compat
34 from IPython.utils.dir2 import safe_hasattr
34 from IPython.utils.dir2 import safe_hasattr
35 from IPython.utils.path import compress_user
35 from IPython.utils.path import compress_user
36 from IPython.utils.text import indent
36 from IPython.utils.text import indent
37 from IPython.utils.wildcard import list_namespace
37 from IPython.utils.wildcard import list_namespace
38 from IPython.utils.wildcard import typestr2type
38 from IPython.utils.wildcard import typestr2type
39 from IPython.utils.coloransi import TermColors, ColorScheme, ColorSchemeTable
39 from IPython.utils.coloransi import TermColors, ColorScheme, ColorSchemeTable
40 from IPython.utils.py3compat import cast_unicode
40 from IPython.utils.py3compat import cast_unicode
41 from IPython.utils.colorable import Colorable
41 from IPython.utils.colorable import Colorable
42 from IPython.utils.decorators import undoc
42 from IPython.utils.decorators import undoc
43
43
44 from pygments import highlight
44 from pygments import highlight
45 from pygments.lexers import PythonLexer
45 from pygments.lexers import PythonLexer
46 from pygments.formatters import HtmlFormatter
46 from pygments.formatters import HtmlFormatter
47
47
48 def pylight(code):
48 def pylight(code):
49 return highlight(code, PythonLexer(), HtmlFormatter(noclasses=True))
49 return highlight(code, PythonLexer(), HtmlFormatter(noclasses=True))
50
50
51 # builtin docstrings to ignore
51 # builtin docstrings to ignore
52 _func_call_docstring = types.FunctionType.__call__.__doc__
52 _func_call_docstring = types.FunctionType.__call__.__doc__
53 _object_init_docstring = object.__init__.__doc__
53 _object_init_docstring = object.__init__.__doc__
54 _builtin_type_docstrings = {
54 _builtin_type_docstrings = {
55 inspect.getdoc(t) for t in (types.ModuleType, types.MethodType,
55 inspect.getdoc(t) for t in (types.ModuleType, types.MethodType,
56 types.FunctionType, property)
56 types.FunctionType, property)
57 }
57 }
58
58
59 _builtin_func_type = type(all)
59 _builtin_func_type = type(all)
60 _builtin_meth_type = type(str.upper) # Bound methods have the same type as builtin functions
60 _builtin_meth_type = type(str.upper) # Bound methods have the same type as builtin functions
61 #****************************************************************************
61 #****************************************************************************
62 # Builtin color schemes
62 # Builtin color schemes
63
63
64 Colors = TermColors # just a shorthand
64 Colors = TermColors # just a shorthand
65
65
66 InspectColors = PyColorize.ANSICodeColors
66 InspectColors = PyColorize.ANSICodeColors
67
67
68 #****************************************************************************
68 #****************************************************************************
69 # Auxiliary functions and objects
69 # Auxiliary functions and objects
70
70
71 # See the messaging spec for the definition of all these fields. This list
71 # See the messaging spec for the definition of all these fields. This list
72 # effectively defines the order of display
72 # effectively defines the order of display
73 info_fields = ['type_name', 'base_class', 'string_form', 'namespace',
73 info_fields = ['type_name', 'base_class', 'string_form', 'namespace',
74 'length', 'file', 'definition', 'docstring', 'source',
74 'length', 'file', 'definition', 'docstring', 'source',
75 'init_definition', 'class_docstring', 'init_docstring',
75 'init_definition', 'class_docstring', 'init_docstring',
76 'call_def', 'call_docstring',
76 'call_def', 'call_docstring',
77 # These won't be printed but will be used to determine how to
77 # These won't be printed but will be used to determine how to
78 # format the object
78 # format the object
79 'ismagic', 'isalias', 'isclass', 'argspec', 'found', 'name'
79 'ismagic', 'isalias', 'isclass', 'found', 'name'
80 ]
80 ]
81
81
82
82
83 def object_info(**kw):
83 def object_info(**kw):
84 """Make an object info dict with all fields present."""
84 """Make an object info dict with all fields present."""
85 infodict = dict(zip_longest(info_fields, [None]))
85 infodict = dict(zip_longest(info_fields, [None]))
86 infodict.update(kw)
86 infodict.update(kw)
87 return infodict
87 return infodict
88
88
89
89
90 def get_encoding(obj):
90 def get_encoding(obj):
91 """Get encoding for python source file defining obj
91 """Get encoding for python source file defining obj
92
92
93 Returns None if obj is not defined in a sourcefile.
93 Returns None if obj is not defined in a sourcefile.
94 """
94 """
95 ofile = find_file(obj)
95 ofile = find_file(obj)
96 # run contents of file through pager starting at line where the object
96 # run contents of file through pager starting at line where the object
97 # is defined, as long as the file isn't binary and is actually on the
97 # is defined, as long as the file isn't binary and is actually on the
98 # filesystem.
98 # filesystem.
99 if ofile is None:
99 if ofile is None:
100 return None
100 return None
101 elif ofile.endswith(('.so', '.dll', '.pyd')):
101 elif ofile.endswith(('.so', '.dll', '.pyd')):
102 return None
102 return None
103 elif not os.path.isfile(ofile):
103 elif not os.path.isfile(ofile):
104 return None
104 return None
105 else:
105 else:
106 # Print only text files, not extension binaries. Note that
106 # Print only text files, not extension binaries. Note that
107 # getsourcelines returns lineno with 1-offset and page() uses
107 # getsourcelines returns lineno with 1-offset and page() uses
108 # 0-offset, so we must adjust.
108 # 0-offset, so we must adjust.
109 with stdlib_io.open(ofile, 'rb') as buffer: # Tweaked to use io.open for Python 2
109 with stdlib_io.open(ofile, 'rb') as buffer: # Tweaked to use io.open for Python 2
110 encoding, lines = openpy.detect_encoding(buffer.readline)
110 encoding, lines = openpy.detect_encoding(buffer.readline)
111 return encoding
111 return encoding
112
112
113 def getdoc(obj):
113 def getdoc(obj):
114 """Stable wrapper around inspect.getdoc.
114 """Stable wrapper around inspect.getdoc.
115
115
116 This can't crash because of attribute problems.
116 This can't crash because of attribute problems.
117
117
118 It also attempts to call a getdoc() method on the given object. This
118 It also attempts to call a getdoc() method on the given object. This
119 allows objects which provide their docstrings via non-standard mechanisms
119 allows objects which provide their docstrings via non-standard mechanisms
120 (like Pyro proxies) to still be inspected by ipython's ? system.
120 (like Pyro proxies) to still be inspected by ipython's ? system.
121 """
121 """
122 # Allow objects to offer customized documentation via a getdoc method:
122 # Allow objects to offer customized documentation via a getdoc method:
123 try:
123 try:
124 ds = obj.getdoc()
124 ds = obj.getdoc()
125 except Exception:
125 except Exception:
126 pass
126 pass
127 else:
127 else:
128 if isinstance(ds, str):
128 if isinstance(ds, str):
129 return inspect.cleandoc(ds)
129 return inspect.cleandoc(ds)
130 docstr = inspect.getdoc(obj)
130 docstr = inspect.getdoc(obj)
131 encoding = get_encoding(obj)
131 encoding = get_encoding(obj)
132 return py3compat.cast_unicode(docstr, encoding=encoding)
132 return py3compat.cast_unicode(docstr, encoding=encoding)
133
133
134
134
135 def getsource(obj, oname=''):
135 def getsource(obj, oname=''):
136 """Wrapper around inspect.getsource.
136 """Wrapper around inspect.getsource.
137
137
138 This can be modified by other projects to provide customized source
138 This can be modified by other projects to provide customized source
139 extraction.
139 extraction.
140
140
141 Parameters
141 Parameters
142 ----------
142 ----------
143 obj : object
143 obj : object
144 an object whose source code we will attempt to extract
144 an object whose source code we will attempt to extract
145 oname : str
145 oname : str
146 (optional) a name under which the object is known
146 (optional) a name under which the object is known
147
147
148 Returns
148 Returns
149 -------
149 -------
150 src : unicode or None
150 src : unicode or None
151
151
152 """
152 """
153
153
154 if isinstance(obj, property):
154 if isinstance(obj, property):
155 sources = []
155 sources = []
156 for attrname in ['fget', 'fset', 'fdel']:
156 for attrname in ['fget', 'fset', 'fdel']:
157 fn = getattr(obj, attrname)
157 fn = getattr(obj, attrname)
158 if fn is not None:
158 if fn is not None:
159 encoding = get_encoding(fn)
159 encoding = get_encoding(fn)
160 oname_prefix = ('%s.' % oname) if oname else ''
160 oname_prefix = ('%s.' % oname) if oname else ''
161 sources.append(cast_unicode(
161 sources.append(cast_unicode(
162 ''.join(('# ', oname_prefix, attrname)),
162 ''.join(('# ', oname_prefix, attrname)),
163 encoding=encoding))
163 encoding=encoding))
164 if inspect.isfunction(fn):
164 if inspect.isfunction(fn):
165 sources.append(dedent(getsource(fn)))
165 sources.append(dedent(getsource(fn)))
166 else:
166 else:
167 # Default str/repr only prints function name,
167 # Default str/repr only prints function name,
168 # pretty.pretty prints module name too.
168 # pretty.pretty prints module name too.
169 sources.append(cast_unicode(
169 sources.append(cast_unicode(
170 '%s%s = %s\n' % (
170 '%s%s = %s\n' % (
171 oname_prefix, attrname, pretty(fn)),
171 oname_prefix, attrname, pretty(fn)),
172 encoding=encoding))
172 encoding=encoding))
173 if sources:
173 if sources:
174 return '\n'.join(sources)
174 return '\n'.join(sources)
175 else:
175 else:
176 return None
176 return None
177
177
178 else:
178 else:
179 # Get source for non-property objects.
179 # Get source for non-property objects.
180
180
181 obj = _get_wrapped(obj)
181 obj = _get_wrapped(obj)
182
182
183 try:
183 try:
184 src = inspect.getsource(obj)
184 src = inspect.getsource(obj)
185 except TypeError:
185 except TypeError:
186 # The object itself provided no meaningful source, try looking for
186 # The object itself provided no meaningful source, try looking for
187 # its class definition instead.
187 # its class definition instead.
188 if hasattr(obj, '__class__'):
188 if hasattr(obj, '__class__'):
189 try:
189 try:
190 src = inspect.getsource(obj.__class__)
190 src = inspect.getsource(obj.__class__)
191 except TypeError:
191 except TypeError:
192 return None
192 return None
193
193
194 encoding = get_encoding(obj)
194 encoding = get_encoding(obj)
195 return cast_unicode(src, encoding=encoding)
195 return cast_unicode(src, encoding=encoding)
196
196
197
197
198 def is_simple_callable(obj):
198 def is_simple_callable(obj):
199 """True if obj is a function ()"""
199 """True if obj is a function ()"""
200 return (inspect.isfunction(obj) or inspect.ismethod(obj) or \
200 return (inspect.isfunction(obj) or inspect.ismethod(obj) or \
201 isinstance(obj, _builtin_func_type) or isinstance(obj, _builtin_meth_type))
201 isinstance(obj, _builtin_func_type) or isinstance(obj, _builtin_meth_type))
202
202
203
203 @undoc
204 def getargspec(obj):
204 def getargspec(obj):
205 """Wrapper around :func:`inspect.getfullargspec` on Python 3, and
205 """Wrapper around :func:`inspect.getfullargspec` on Python 3, and
206 :func:inspect.getargspec` on Python 2.
206 :func:inspect.getargspec` on Python 2.
207
207
208 In addition to functions and methods, this can also handle objects with a
208 In addition to functions and methods, this can also handle objects with a
209 ``__call__`` attribute.
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 if safe_hasattr(obj, '__call__') and not is_simple_callable(obj):
217 if safe_hasattr(obj, '__call__') and not is_simple_callable(obj):
212 obj = obj.__call__
218 obj = obj.__call__
213
219
214 return inspect.getfullargspec(obj)
220 return inspect.getfullargspec(obj)
215
221
216
222 @undoc
217 def format_argspec(argspec):
223 def format_argspec(argspec):
218 """Format argspect, convenience wrapper around inspect's.
224 """Format argspect, convenience wrapper around inspect's.
219
225
220 This takes a dict instead of ordered arguments and calls
226 This takes a dict instead of ordered arguments and calls
221 inspect.format_argspec with the arguments in the necessary order.
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 return inspect.formatargspec(argspec['args'], argspec['varargs'],
236 return inspect.formatargspec(argspec['args'], argspec['varargs'],
224 argspec['varkw'], argspec['defaults'])
237 argspec['varkw'], argspec['defaults'])
225
238
226 @undoc
239 @undoc
227 def call_tip(oinfo, format_call=True):
240 def call_tip(oinfo, format_call=True):
228 """DEPRECATED. Extract call tip data from an oinfo dict.
241 """DEPRECATED. Extract call tip data from an oinfo dict.
229 """
242 """
230 warnings.warn('`call_tip` function is deprecated as of IPython 6.0'
243 warnings.warn('`call_tip` function is deprecated as of IPython 6.0'
231 'and will be removed in future versions.', DeprecationWarning, stacklevel=2)
244 'and will be removed in future versions.', DeprecationWarning, stacklevel=2)
232 # Get call definition
245 # Get call definition
233 argspec = oinfo.get('argspec')
246 argspec = oinfo.get('argspec')
234 if argspec is None:
247 if argspec is None:
235 call_line = None
248 call_line = None
236 else:
249 else:
237 # Callable objects will have 'self' as their first argument, prune
250 # Callable objects will have 'self' as their first argument, prune
238 # it out if it's there for clarity (since users do *not* pass an
251 # it out if it's there for clarity (since users do *not* pass an
239 # extra first argument explicitly).
252 # extra first argument explicitly).
240 try:
253 try:
241 has_self = argspec['args'][0] == 'self'
254 has_self = argspec['args'][0] == 'self'
242 except (KeyError, IndexError):
255 except (KeyError, IndexError):
243 pass
256 pass
244 else:
257 else:
245 if has_self:
258 if has_self:
246 argspec['args'] = argspec['args'][1:]
259 argspec['args'] = argspec['args'][1:]
247
260
248 call_line = oinfo['name']+format_argspec(argspec)
261 call_line = oinfo['name']+format_argspec(argspec)
249
262
250 # Now get docstring.
263 # Now get docstring.
251 # The priority is: call docstring, constructor docstring, main one.
264 # The priority is: call docstring, constructor docstring, main one.
252 doc = oinfo.get('call_docstring')
265 doc = oinfo.get('call_docstring')
253 if doc is None:
266 if doc is None:
254 doc = oinfo.get('init_docstring')
267 doc = oinfo.get('init_docstring')
255 if doc is None:
268 if doc is None:
256 doc = oinfo.get('docstring','')
269 doc = oinfo.get('docstring','')
257
270
258 return call_line, doc
271 return call_line, doc
259
272
260
273
261 def _get_wrapped(obj):
274 def _get_wrapped(obj):
262 """Get the original object if wrapped in one or more @decorators
275 """Get the original object if wrapped in one or more @decorators
263
276
264 Some objects automatically construct similar objects on any unrecognised
277 Some objects automatically construct similar objects on any unrecognised
265 attribute access (e.g. unittest.mock.call). To protect against infinite loops,
278 attribute access (e.g. unittest.mock.call). To protect against infinite loops,
266 this will arbitrarily cut off after 100 levels of obj.__wrapped__
279 this will arbitrarily cut off after 100 levels of obj.__wrapped__
267 attribute access. --TK, Jan 2016
280 attribute access. --TK, Jan 2016
268 """
281 """
269 orig_obj = obj
282 orig_obj = obj
270 i = 0
283 i = 0
271 while safe_hasattr(obj, '__wrapped__'):
284 while safe_hasattr(obj, '__wrapped__'):
272 obj = obj.__wrapped__
285 obj = obj.__wrapped__
273 i += 1
286 i += 1
274 if i > 100:
287 if i > 100:
275 # __wrapped__ is probably a lie, so return the thing we started with
288 # __wrapped__ is probably a lie, so return the thing we started with
276 return orig_obj
289 return orig_obj
277 return obj
290 return obj
278
291
279 def find_file(obj):
292 def find_file(obj):
280 """Find the absolute path to the file where an object was defined.
293 """Find the absolute path to the file where an object was defined.
281
294
282 This is essentially a robust wrapper around `inspect.getabsfile`.
295 This is essentially a robust wrapper around `inspect.getabsfile`.
283
296
284 Returns None if no file can be found.
297 Returns None if no file can be found.
285
298
286 Parameters
299 Parameters
287 ----------
300 ----------
288 obj : any Python object
301 obj : any Python object
289
302
290 Returns
303 Returns
291 -------
304 -------
292 fname : str
305 fname : str
293 The absolute path to the file where the object was defined.
306 The absolute path to the file where the object was defined.
294 """
307 """
295 obj = _get_wrapped(obj)
308 obj = _get_wrapped(obj)
296
309
297 fname = None
310 fname = None
298 try:
311 try:
299 fname = inspect.getabsfile(obj)
312 fname = inspect.getabsfile(obj)
300 except TypeError:
313 except TypeError:
301 # For an instance, the file that matters is where its class was
314 # For an instance, the file that matters is where its class was
302 # declared.
315 # declared.
303 if hasattr(obj, '__class__'):
316 if hasattr(obj, '__class__'):
304 try:
317 try:
305 fname = inspect.getabsfile(obj.__class__)
318 fname = inspect.getabsfile(obj.__class__)
306 except TypeError:
319 except TypeError:
307 # Can happen for builtins
320 # Can happen for builtins
308 pass
321 pass
309 except:
322 except:
310 pass
323 pass
311 return cast_unicode(fname)
324 return cast_unicode(fname)
312
325
313
326
314 def find_source_lines(obj):
327 def find_source_lines(obj):
315 """Find the line number in a file where an object was defined.
328 """Find the line number in a file where an object was defined.
316
329
317 This is essentially a robust wrapper around `inspect.getsourcelines`.
330 This is essentially a robust wrapper around `inspect.getsourcelines`.
318
331
319 Returns None if no file can be found.
332 Returns None if no file can be found.
320
333
321 Parameters
334 Parameters
322 ----------
335 ----------
323 obj : any Python object
336 obj : any Python object
324
337
325 Returns
338 Returns
326 -------
339 -------
327 lineno : int
340 lineno : int
328 The line number where the object definition starts.
341 The line number where the object definition starts.
329 """
342 """
330 obj = _get_wrapped(obj)
343 obj = _get_wrapped(obj)
331
344
332 try:
345 try:
333 try:
346 try:
334 lineno = inspect.getsourcelines(obj)[1]
347 lineno = inspect.getsourcelines(obj)[1]
335 except TypeError:
348 except TypeError:
336 # For instances, try the class object like getsource() does
349 # For instances, try the class object like getsource() does
337 if hasattr(obj, '__class__'):
350 if hasattr(obj, '__class__'):
338 lineno = inspect.getsourcelines(obj.__class__)[1]
351 lineno = inspect.getsourcelines(obj.__class__)[1]
339 else:
352 else:
340 lineno = None
353 lineno = None
341 except:
354 except:
342 return None
355 return None
343
356
344 return lineno
357 return lineno
345
358
346 class Inspector(Colorable):
359 class Inspector(Colorable):
347
360
348 def __init__(self, color_table=InspectColors,
361 def __init__(self, color_table=InspectColors,
349 code_color_table=PyColorize.ANSICodeColors,
362 code_color_table=PyColorize.ANSICodeColors,
350 scheme=None,
363 scheme=None,
351 str_detail_level=0,
364 str_detail_level=0,
352 parent=None, config=None):
365 parent=None, config=None):
353 super(Inspector, self).__init__(parent=parent, config=config)
366 super(Inspector, self).__init__(parent=parent, config=config)
354 self.color_table = color_table
367 self.color_table = color_table
355 self.parser = PyColorize.Parser(out='str', parent=self, style=scheme)
368 self.parser = PyColorize.Parser(out='str', parent=self, style=scheme)
356 self.format = self.parser.format
369 self.format = self.parser.format
357 self.str_detail_level = str_detail_level
370 self.str_detail_level = str_detail_level
358 self.set_active_scheme(scheme)
371 self.set_active_scheme(scheme)
359
372
360 def _getdef(self,obj,oname=''):
373 def _getdef(self,obj,oname=''):
361 """Return the call signature for any callable object.
374 """Return the call signature for any callable object.
362
375
363 If any exception is generated, None is returned instead and the
376 If any exception is generated, None is returned instead and the
364 exception is suppressed."""
377 exception is suppressed."""
365 try:
378 try:
366 hdef = _render_signature(signature(obj), oname)
379 hdef = _render_signature(signature(obj), oname)
367 return cast_unicode(hdef)
380 return cast_unicode(hdef)
368 except:
381 except:
369 return None
382 return None
370
383
371 def __head(self,h):
384 def __head(self,h):
372 """Return a header string with proper colors."""
385 """Return a header string with proper colors."""
373 return '%s%s%s' % (self.color_table.active_colors.header,h,
386 return '%s%s%s' % (self.color_table.active_colors.header,h,
374 self.color_table.active_colors.normal)
387 self.color_table.active_colors.normal)
375
388
376 def set_active_scheme(self, scheme):
389 def set_active_scheme(self, scheme):
377 if scheme is not None:
390 if scheme is not None:
378 self.color_table.set_active_scheme(scheme)
391 self.color_table.set_active_scheme(scheme)
379 self.parser.color_table.set_active_scheme(scheme)
392 self.parser.color_table.set_active_scheme(scheme)
380
393
381 def noinfo(self, msg, oname):
394 def noinfo(self, msg, oname):
382 """Generic message when no information is found."""
395 """Generic message when no information is found."""
383 print('No %s found' % msg, end=' ')
396 print('No %s found' % msg, end=' ')
384 if oname:
397 if oname:
385 print('for %s' % oname)
398 print('for %s' % oname)
386 else:
399 else:
387 print()
400 print()
388
401
389 def pdef(self, obj, oname=''):
402 def pdef(self, obj, oname=''):
390 """Print the call signature for any callable object.
403 """Print the call signature for any callable object.
391
404
392 If the object is a class, print the constructor information."""
405 If the object is a class, print the constructor information."""
393
406
394 if not callable(obj):
407 if not callable(obj):
395 print('Object is not callable.')
408 print('Object is not callable.')
396 return
409 return
397
410
398 header = ''
411 header = ''
399
412
400 if inspect.isclass(obj):
413 if inspect.isclass(obj):
401 header = self.__head('Class constructor information:\n')
414 header = self.__head('Class constructor information:\n')
402
415
403
416
404 output = self._getdef(obj,oname)
417 output = self._getdef(obj,oname)
405 if output is None:
418 if output is None:
406 self.noinfo('definition header',oname)
419 self.noinfo('definition header',oname)
407 else:
420 else:
408 print(header,self.format(output), end=' ')
421 print(header,self.format(output), end=' ')
409
422
410 # In Python 3, all classes are new-style, so they all have __init__.
423 # In Python 3, all classes are new-style, so they all have __init__.
411 @skip_doctest
424 @skip_doctest
412 def pdoc(self, obj, oname='', formatter=None):
425 def pdoc(self, obj, oname='', formatter=None):
413 """Print the docstring for any object.
426 """Print the docstring for any object.
414
427
415 Optional:
428 Optional:
416 -formatter: a function to run the docstring through for specially
429 -formatter: a function to run the docstring through for specially
417 formatted docstrings.
430 formatted docstrings.
418
431
419 Examples
432 Examples
420 --------
433 --------
421
434
422 In [1]: class NoInit:
435 In [1]: class NoInit:
423 ...: pass
436 ...: pass
424
437
425 In [2]: class NoDoc:
438 In [2]: class NoDoc:
426 ...: def __init__(self):
439 ...: def __init__(self):
427 ...: pass
440 ...: pass
428
441
429 In [3]: %pdoc NoDoc
442 In [3]: %pdoc NoDoc
430 No documentation found for NoDoc
443 No documentation found for NoDoc
431
444
432 In [4]: %pdoc NoInit
445 In [4]: %pdoc NoInit
433 No documentation found for NoInit
446 No documentation found for NoInit
434
447
435 In [5]: obj = NoInit()
448 In [5]: obj = NoInit()
436
449
437 In [6]: %pdoc obj
450 In [6]: %pdoc obj
438 No documentation found for obj
451 No documentation found for obj
439
452
440 In [5]: obj2 = NoDoc()
453 In [5]: obj2 = NoDoc()
441
454
442 In [6]: %pdoc obj2
455 In [6]: %pdoc obj2
443 No documentation found for obj2
456 No documentation found for obj2
444 """
457 """
445
458
446 head = self.__head # For convenience
459 head = self.__head # For convenience
447 lines = []
460 lines = []
448 ds = getdoc(obj)
461 ds = getdoc(obj)
449 if formatter:
462 if formatter:
450 ds = formatter(ds).get('plain/text', ds)
463 ds = formatter(ds).get('plain/text', ds)
451 if ds:
464 if ds:
452 lines.append(head("Class docstring:"))
465 lines.append(head("Class docstring:"))
453 lines.append(indent(ds))
466 lines.append(indent(ds))
454 if inspect.isclass(obj) and hasattr(obj, '__init__'):
467 if inspect.isclass(obj) and hasattr(obj, '__init__'):
455 init_ds = getdoc(obj.__init__)
468 init_ds = getdoc(obj.__init__)
456 if init_ds is not None:
469 if init_ds is not None:
457 lines.append(head("Init docstring:"))
470 lines.append(head("Init docstring:"))
458 lines.append(indent(init_ds))
471 lines.append(indent(init_ds))
459 elif hasattr(obj,'__call__'):
472 elif hasattr(obj,'__call__'):
460 call_ds = getdoc(obj.__call__)
473 call_ds = getdoc(obj.__call__)
461 if call_ds:
474 if call_ds:
462 lines.append(head("Call docstring:"))
475 lines.append(head("Call docstring:"))
463 lines.append(indent(call_ds))
476 lines.append(indent(call_ds))
464
477
465 if not lines:
478 if not lines:
466 self.noinfo('documentation',oname)
479 self.noinfo('documentation',oname)
467 else:
480 else:
468 page.page('\n'.join(lines))
481 page.page('\n'.join(lines))
469
482
470 def psource(self, obj, oname=''):
483 def psource(self, obj, oname=''):
471 """Print the source code for an object."""
484 """Print the source code for an object."""
472
485
473 # Flush the source cache because inspect can return out-of-date source
486 # Flush the source cache because inspect can return out-of-date source
474 linecache.checkcache()
487 linecache.checkcache()
475 try:
488 try:
476 src = getsource(obj, oname=oname)
489 src = getsource(obj, oname=oname)
477 except Exception:
490 except Exception:
478 src = None
491 src = None
479
492
480 if src is None:
493 if src is None:
481 self.noinfo('source', oname)
494 self.noinfo('source', oname)
482 else:
495 else:
483 page.page(self.format(src))
496 page.page(self.format(src))
484
497
485 def pfile(self, obj, oname=''):
498 def pfile(self, obj, oname=''):
486 """Show the whole file where an object was defined."""
499 """Show the whole file where an object was defined."""
487
500
488 lineno = find_source_lines(obj)
501 lineno = find_source_lines(obj)
489 if lineno is None:
502 if lineno is None:
490 self.noinfo('file', oname)
503 self.noinfo('file', oname)
491 return
504 return
492
505
493 ofile = find_file(obj)
506 ofile = find_file(obj)
494 # run contents of file through pager starting at line where the object
507 # run contents of file through pager starting at line where the object
495 # is defined, as long as the file isn't binary and is actually on the
508 # is defined, as long as the file isn't binary and is actually on the
496 # filesystem.
509 # filesystem.
497 if ofile.endswith(('.so', '.dll', '.pyd')):
510 if ofile.endswith(('.so', '.dll', '.pyd')):
498 print('File %r is binary, not printing.' % ofile)
511 print('File %r is binary, not printing.' % ofile)
499 elif not os.path.isfile(ofile):
512 elif not os.path.isfile(ofile):
500 print('File %r does not exist, not printing.' % ofile)
513 print('File %r does not exist, not printing.' % ofile)
501 else:
514 else:
502 # Print only text files, not extension binaries. Note that
515 # Print only text files, not extension binaries. Note that
503 # getsourcelines returns lineno with 1-offset and page() uses
516 # getsourcelines returns lineno with 1-offset and page() uses
504 # 0-offset, so we must adjust.
517 # 0-offset, so we must adjust.
505 page.page(self.format(openpy.read_py_file(ofile, skip_encoding_cookie=False)), lineno - 1)
518 page.page(self.format(openpy.read_py_file(ofile, skip_encoding_cookie=False)), lineno - 1)
506
519
507 def _format_fields(self, fields, title_width=0):
520 def _format_fields(self, fields, title_width=0):
508 """Formats a list of fields for display.
521 """Formats a list of fields for display.
509
522
510 Parameters
523 Parameters
511 ----------
524 ----------
512 fields : list
525 fields : list
513 A list of 2-tuples: (field_title, field_content)
526 A list of 2-tuples: (field_title, field_content)
514 title_width : int
527 title_width : int
515 How many characters to pad titles to. Default to longest title.
528 How many characters to pad titles to. Default to longest title.
516 """
529 """
517 out = []
530 out = []
518 header = self.__head
531 header = self.__head
519 if title_width == 0:
532 if title_width == 0:
520 title_width = max(len(title) + 2 for title, _ in fields)
533 title_width = max(len(title) + 2 for title, _ in fields)
521 for title, content in fields:
534 for title, content in fields:
522 if len(content.splitlines()) > 1:
535 if len(content.splitlines()) > 1:
523 title = header(title + ':') + '\n'
536 title = header(title + ':') + '\n'
524 else:
537 else:
525 title = header((title + ':').ljust(title_width))
538 title = header((title + ':').ljust(title_width))
526 out.append(cast_unicode(title) + cast_unicode(content))
539 out.append(cast_unicode(title) + cast_unicode(content))
527 return "\n".join(out)
540 return "\n".join(out)
528
541
529 def _mime_format(self, text, formatter=None):
542 def _mime_format(self, text, formatter=None):
530 """Return a mime bundle representation of the input text.
543 """Return a mime bundle representation of the input text.
531
544
532 - if `formatter` is None, the returned mime bundle has
545 - if `formatter` is None, the returned mime bundle has
533 a `text/plain` field, with the input text.
546 a `text/plain` field, with the input text.
534 a `text/html` field with a `<pre>` tag containing the input text.
547 a `text/html` field with a `<pre>` tag containing the input text.
535
548
536 - if `formatter` is not None, it must be a callable transforming the
549 - if `formatter` is not None, it must be a callable transforming the
537 input text into a mime bundle. Default values for `text/plain` and
550 input text into a mime bundle. Default values for `text/plain` and
538 `text/html` representations are the ones described above.
551 `text/html` representations are the ones described above.
539
552
540 Note:
553 Note:
541
554
542 Formatters returning strings are supported but this behavior is deprecated.
555 Formatters returning strings are supported but this behavior is deprecated.
543
556
544 """
557 """
545 text = cast_unicode(text)
558 text = cast_unicode(text)
546 defaults = {
559 defaults = {
547 'text/plain': text,
560 'text/plain': text,
548 'text/html': '<pre>' + text + '</pre>'
561 'text/html': '<pre>' + text + '</pre>'
549 }
562 }
550
563
551 if formatter is None:
564 if formatter is None:
552 return defaults
565 return defaults
553 else:
566 else:
554 formatted = formatter(text)
567 formatted = formatter(text)
555
568
556 if not isinstance(formatted, dict):
569 if not isinstance(formatted, dict):
557 # Handle the deprecated behavior of a formatter returning
570 # Handle the deprecated behavior of a formatter returning
558 # a string instead of a mime bundle.
571 # a string instead of a mime bundle.
559 return {
572 return {
560 'text/plain': formatted,
573 'text/plain': formatted,
561 'text/html': '<pre>' + formatted + '</pre>'
574 'text/html': '<pre>' + formatted + '</pre>'
562 }
575 }
563
576
564 else:
577 else:
565 return dict(defaults, **formatted)
578 return dict(defaults, **formatted)
566
579
567
580
568 def format_mime(self, bundle):
581 def format_mime(self, bundle):
569
582
570 text_plain = bundle['text/plain']
583 text_plain = bundle['text/plain']
571
584
572 text = ''
585 text = ''
573 heads, bodies = list(zip(*text_plain))
586 heads, bodies = list(zip(*text_plain))
574 _len = max(len(h) for h in heads)
587 _len = max(len(h) for h in heads)
575
588
576 for head, body in zip(heads, bodies):
589 for head, body in zip(heads, bodies):
577 body = body.strip('\n')
590 body = body.strip('\n')
578 delim = '\n' if '\n' in body else ' '
591 delim = '\n' if '\n' in body else ' '
579 text += self.__head(head+':') + (_len - len(head))*' ' +delim + body +'\n'
592 text += self.__head(head+':') + (_len - len(head))*' ' +delim + body +'\n'
580
593
581 bundle['text/plain'] = text
594 bundle['text/plain'] = text
582 return bundle
595 return bundle
583
596
584 def _get_info(self, obj, oname='', formatter=None, info=None, detail_level=0):
597 def _get_info(self, obj, oname='', formatter=None, info=None, detail_level=0):
585 """Retrieve an info dict and format it.
598 """Retrieve an info dict and format it.
586
599
587 Parameters
600 Parameters
588 ==========
601 ==========
589
602
590 obj: any
603 obj: any
591 Object to inspect and return info from
604 Object to inspect and return info from
592 oname: str (default: ''):
605 oname: str (default: ''):
593 Name of the variable pointing to `obj`.
606 Name of the variable pointing to `obj`.
594 formatter: callable
607 formatter: callable
595 info:
608 info:
596 already computed information
609 already computed information
597 detail_level: integer
610 detail_level: integer
598 Granularity of detail level, if set to 1, give more information.
611 Granularity of detail level, if set to 1, give more information.
599 """
612 """
600
613
601 info = self._info(obj, oname=oname, info=info, detail_level=detail_level)
614 info = self._info(obj, oname=oname, info=info, detail_level=detail_level)
602
615
603 _mime = {
616 _mime = {
604 'text/plain': [],
617 'text/plain': [],
605 'text/html': '',
618 'text/html': '',
606 }
619 }
607
620
608 def append_field(bundle, title, key, formatter=None):
621 def append_field(bundle, title, key, formatter=None):
609 field = info[key]
622 field = info[key]
610 if field is not None:
623 if field is not None:
611 formatted_field = self._mime_format(field, formatter)
624 formatted_field = self._mime_format(field, formatter)
612 bundle['text/plain'].append((title, formatted_field['text/plain']))
625 bundle['text/plain'].append((title, formatted_field['text/plain']))
613 bundle['text/html'] += '<h1>' + title + '</h1>\n' + formatted_field['text/html'] + '\n'
626 bundle['text/html'] += '<h1>' + title + '</h1>\n' + formatted_field['text/html'] + '\n'
614
627
615 def code_formatter(text):
628 def code_formatter(text):
616 return {
629 return {
617 'text/plain': self.format(text),
630 'text/plain': self.format(text),
618 'text/html': pylight(text)
631 'text/html': pylight(text)
619 }
632 }
620
633
621 if info['isalias']:
634 if info['isalias']:
622 append_field(_mime, 'Repr', 'string_form')
635 append_field(_mime, 'Repr', 'string_form')
623
636
624 elif info['ismagic']:
637 elif info['ismagic']:
625 if detail_level > 0:
638 if detail_level > 0:
626 append_field(_mime, 'Source', 'source', code_formatter)
639 append_field(_mime, 'Source', 'source', code_formatter)
627 else:
640 else:
628 append_field(_mime, 'Docstring', 'docstring', formatter)
641 append_field(_mime, 'Docstring', 'docstring', formatter)
629 append_field(_mime, 'File', 'file')
642 append_field(_mime, 'File', 'file')
630
643
631 elif info['isclass'] or is_simple_callable(obj):
644 elif info['isclass'] or is_simple_callable(obj):
632 # Functions, methods, classes
645 # Functions, methods, classes
633 append_field(_mime, 'Signature', 'definition', code_formatter)
646 append_field(_mime, 'Signature', 'definition', code_formatter)
634 append_field(_mime, 'Init signature', 'init_definition', code_formatter)
647 append_field(_mime, 'Init signature', 'init_definition', code_formatter)
635 append_field(_mime, 'Docstring', 'docstring', formatter)
648 append_field(_mime, 'Docstring', 'docstring', formatter)
636 if detail_level > 0 and info['source']:
649 if detail_level > 0 and info['source']:
637 append_field(_mime, 'Source', 'source', code_formatter)
650 append_field(_mime, 'Source', 'source', code_formatter)
638 else:
651 else:
639 append_field(_mime, 'Init docstring', 'init_docstring', formatter)
652 append_field(_mime, 'Init docstring', 'init_docstring', formatter)
640
653
641 append_field(_mime, 'File', 'file')
654 append_field(_mime, 'File', 'file')
642 append_field(_mime, 'Type', 'type_name')
655 append_field(_mime, 'Type', 'type_name')
643 append_field(_mime, 'Subclasses', 'subclasses')
656 append_field(_mime, 'Subclasses', 'subclasses')
644
657
645 else:
658 else:
646 # General Python objects
659 # General Python objects
647 append_field(_mime, 'Signature', 'definition', code_formatter)
660 append_field(_mime, 'Signature', 'definition', code_formatter)
648 append_field(_mime, 'Call signature', 'call_def', code_formatter)
661 append_field(_mime, 'Call signature', 'call_def', code_formatter)
649 append_field(_mime, 'Type', 'type_name')
662 append_field(_mime, 'Type', 'type_name')
650 append_field(_mime, 'String form', 'string_form')
663 append_field(_mime, 'String form', 'string_form')
651
664
652 # Namespace
665 # Namespace
653 if info['namespace'] != 'Interactive':
666 if info['namespace'] != 'Interactive':
654 append_field(_mime, 'Namespace', 'namespace')
667 append_field(_mime, 'Namespace', 'namespace')
655
668
656 append_field(_mime, 'Length', 'length')
669 append_field(_mime, 'Length', 'length')
657 append_field(_mime, 'File', 'file')
670 append_field(_mime, 'File', 'file')
658
671
659 # Source or docstring, depending on detail level and whether
672 # Source or docstring, depending on detail level and whether
660 # source found.
673 # source found.
661 if detail_level > 0 and info['source']:
674 if detail_level > 0 and info['source']:
662 append_field(_mime, 'Source', 'source', code_formatter)
675 append_field(_mime, 'Source', 'source', code_formatter)
663 else:
676 else:
664 append_field(_mime, 'Docstring', 'docstring', formatter)
677 append_field(_mime, 'Docstring', 'docstring', formatter)
665
678
666 append_field(_mime, 'Class docstring', 'class_docstring', formatter)
679 append_field(_mime, 'Class docstring', 'class_docstring', formatter)
667 append_field(_mime, 'Init docstring', 'init_docstring', formatter)
680 append_field(_mime, 'Init docstring', 'init_docstring', formatter)
668 append_field(_mime, 'Call docstring', 'call_docstring', formatter)
681 append_field(_mime, 'Call docstring', 'call_docstring', formatter)
669
682
670
683
671 return self.format_mime(_mime)
684 return self.format_mime(_mime)
672
685
673 def pinfo(self, obj, oname='', formatter=None, info=None, detail_level=0, enable_html_pager=True):
686 def pinfo(self, obj, oname='', formatter=None, info=None, detail_level=0, enable_html_pager=True):
674 """Show detailed information about an object.
687 """Show detailed information about an object.
675
688
676 Optional arguments:
689 Optional arguments:
677
690
678 - oname: name of the variable pointing to the object.
691 - oname: name of the variable pointing to the object.
679
692
680 - formatter: callable (optional)
693 - formatter: callable (optional)
681 A special formatter for docstrings.
694 A special formatter for docstrings.
682
695
683 The formatter is a callable that takes a string as an input
696 The formatter is a callable that takes a string as an input
684 and returns either a formatted string or a mime type bundle
697 and returns either a formatted string or a mime type bundle
685 in the form of a dictionary.
698 in the form of a dictionary.
686
699
687 Although the support of custom formatter returning a string
700 Although the support of custom formatter returning a string
688 instead of a mime type bundle is deprecated.
701 instead of a mime type bundle is deprecated.
689
702
690 - info: a structure with some information fields which may have been
703 - info: a structure with some information fields which may have been
691 precomputed already.
704 precomputed already.
692
705
693 - detail_level: if set to 1, more information is given.
706 - detail_level: if set to 1, more information is given.
694 """
707 """
695 info = self._get_info(obj, oname, formatter, info, detail_level)
708 info = self._get_info(obj, oname, formatter, info, detail_level)
696 if not enable_html_pager:
709 if not enable_html_pager:
697 del info['text/html']
710 del info['text/html']
698 page.page(info)
711 page.page(info)
699
712
700 def info(self, obj, oname='', formatter=None, info=None, detail_level=0):
713 def info(self, obj, oname='', formatter=None, info=None, detail_level=0):
701 """DEPRECATED. Compute a dict with detailed information about an object.
714 """DEPRECATED. Compute a dict with detailed information about an object.
702 """
715 """
703 if formatter is not None:
716 if formatter is not None:
704 warnings.warn('The `formatter` keyword argument to `Inspector.info`'
717 warnings.warn('The `formatter` keyword argument to `Inspector.info`'
705 'is deprecated as of IPython 5.0 and will have no effects.',
718 'is deprecated as of IPython 5.0 and will have no effects.',
706 DeprecationWarning, stacklevel=2)
719 DeprecationWarning, stacklevel=2)
707 return self._info(obj, oname=oname, info=info, detail_level=detail_level)
720 return self._info(obj, oname=oname, info=info, detail_level=detail_level)
708
721
709 def _info(self, obj, oname='', info=None, detail_level=0) -> dict:
722 def _info(self, obj, oname='', info=None, detail_level=0) -> dict:
710 """Compute a dict with detailed information about an object.
723 """Compute a dict with detailed information about an object.
711
724
712 Parameters
725 Parameters
713 ==========
726 ==========
714
727
715 obj: any
728 obj: any
716 An object to find information about
729 An object to find information about
717 oname: str (default: ''):
730 oname: str (default: ''):
718 Name of the variable pointing to `obj`.
731 Name of the variable pointing to `obj`.
719 info: (default: None)
732 info: (default: None)
720 A struct (dict like with attr access) with some information fields
733 A struct (dict like with attr access) with some information fields
721 which may have been precomputed already.
734 which may have been precomputed already.
722 detail_level: int (default:0)
735 detail_level: int (default:0)
723 If set to 1, more information is given.
736 If set to 1, more information is given.
724
737
725 Returns
738 Returns
726 =======
739 =======
727
740
728 An object info dict with known fields from `info_fields`.
741 An object info dict with known fields from `info_fields`.
729 """
742 """
730
743
731 if info is None:
744 if info is None:
732 ismagic = False
745 ismagic = False
733 isalias = False
746 isalias = False
734 ospace = ''
747 ospace = ''
735 else:
748 else:
736 ismagic = info.ismagic
749 ismagic = info.ismagic
737 isalias = info.isalias
750 isalias = info.isalias
738 ospace = info.namespace
751 ospace = info.namespace
739
752
740 # Get docstring, special-casing aliases:
753 # Get docstring, special-casing aliases:
741 if isalias:
754 if isalias:
742 if not callable(obj):
755 if not callable(obj):
743 try:
756 try:
744 ds = "Alias to the system command:\n %s" % obj[1]
757 ds = "Alias to the system command:\n %s" % obj[1]
745 except:
758 except:
746 ds = "Alias: " + str(obj)
759 ds = "Alias: " + str(obj)
747 else:
760 else:
748 ds = "Alias to " + str(obj)
761 ds = "Alias to " + str(obj)
749 if obj.__doc__:
762 if obj.__doc__:
750 ds += "\nDocstring:\n" + obj.__doc__
763 ds += "\nDocstring:\n" + obj.__doc__
751 else:
764 else:
752 ds = getdoc(obj)
765 ds = getdoc(obj)
753 if ds is None:
766 if ds is None:
754 ds = '<no docstring>'
767 ds = '<no docstring>'
755
768
756 # store output in a dict, we initialize it here and fill it as we go
769 # store output in a dict, we initialize it here and fill it as we go
757 out = dict(name=oname, found=True, isalias=isalias, ismagic=ismagic, subclasses=None)
770 out = dict(name=oname, found=True, isalias=isalias, ismagic=ismagic, subclasses=None)
758
771
759 string_max = 200 # max size of strings to show (snipped if longer)
772 string_max = 200 # max size of strings to show (snipped if longer)
760 shalf = int((string_max - 5) / 2)
773 shalf = int((string_max - 5) / 2)
761
774
762 if ismagic:
775 if ismagic:
763 out['type_name'] = 'Magic function'
776 out['type_name'] = 'Magic function'
764 elif isalias:
777 elif isalias:
765 out['type_name'] = 'System alias'
778 out['type_name'] = 'System alias'
766 else:
779 else:
767 out['type_name'] = type(obj).__name__
780 out['type_name'] = type(obj).__name__
768
781
769 try:
782 try:
770 bclass = obj.__class__
783 bclass = obj.__class__
771 out['base_class'] = str(bclass)
784 out['base_class'] = str(bclass)
772 except:
785 except:
773 pass
786 pass
774
787
775 # String form, but snip if too long in ? form (full in ??)
788 # String form, but snip if too long in ? form (full in ??)
776 if detail_level >= self.str_detail_level:
789 if detail_level >= self.str_detail_level:
777 try:
790 try:
778 ostr = str(obj)
791 ostr = str(obj)
779 str_head = 'string_form'
792 str_head = 'string_form'
780 if not detail_level and len(ostr)>string_max:
793 if not detail_level and len(ostr)>string_max:
781 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
794 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
782 ostr = ("\n" + " " * len(str_head.expandtabs())).\
795 ostr = ("\n" + " " * len(str_head.expandtabs())).\
783 join(q.strip() for q in ostr.split("\n"))
796 join(q.strip() for q in ostr.split("\n"))
784 out[str_head] = ostr
797 out[str_head] = ostr
785 except:
798 except:
786 pass
799 pass
787
800
788 if ospace:
801 if ospace:
789 out['namespace'] = ospace
802 out['namespace'] = ospace
790
803
791 # Length (for strings and lists)
804 # Length (for strings and lists)
792 try:
805 try:
793 out['length'] = str(len(obj))
806 out['length'] = str(len(obj))
794 except Exception:
807 except Exception:
795 pass
808 pass
796
809
797 # Filename where object was defined
810 # Filename where object was defined
798 binary_file = False
811 binary_file = False
799 fname = find_file(obj)
812 fname = find_file(obj)
800 if fname is None:
813 if fname is None:
801 # if anything goes wrong, we don't want to show source, so it's as
814 # if anything goes wrong, we don't want to show source, so it's as
802 # if the file was binary
815 # if the file was binary
803 binary_file = True
816 binary_file = True
804 else:
817 else:
805 if fname.endswith(('.so', '.dll', '.pyd')):
818 if fname.endswith(('.so', '.dll', '.pyd')):
806 binary_file = True
819 binary_file = True
807 elif fname.endswith('<string>'):
820 elif fname.endswith('<string>'):
808 fname = 'Dynamically generated function. No source code available.'
821 fname = 'Dynamically generated function. No source code available.'
809 out['file'] = compress_user(fname)
822 out['file'] = compress_user(fname)
810
823
811 # Original source code for a callable, class or property.
824 # Original source code for a callable, class or property.
812 if detail_level:
825 if detail_level:
813 # Flush the source cache because inspect can return out-of-date
826 # Flush the source cache because inspect can return out-of-date
814 # source
827 # source
815 linecache.checkcache()
828 linecache.checkcache()
816 try:
829 try:
817 if isinstance(obj, property) or not binary_file:
830 if isinstance(obj, property) or not binary_file:
818 src = getsource(obj, oname)
831 src = getsource(obj, oname)
819 if src is not None:
832 if src is not None:
820 src = src.rstrip()
833 src = src.rstrip()
821 out['source'] = src
834 out['source'] = src
822
835
823 except Exception:
836 except Exception:
824 pass
837 pass
825
838
826 # Add docstring only if no source is to be shown (avoid repetitions).
839 # Add docstring only if no source is to be shown (avoid repetitions).
827 if ds and not self._source_contains_docstring(out.get('source'), ds):
840 if ds and not self._source_contains_docstring(out.get('source'), ds):
828 out['docstring'] = ds
841 out['docstring'] = ds
829
842
830 # Constructor docstring for classes
843 # Constructor docstring for classes
831 if inspect.isclass(obj):
844 if inspect.isclass(obj):
832 out['isclass'] = True
845 out['isclass'] = True
833
846
834 # get the init signature:
847 # get the init signature:
835 try:
848 try:
836 init_def = self._getdef(obj, oname)
849 init_def = self._getdef(obj, oname)
837 except AttributeError:
850 except AttributeError:
838 init_def = None
851 init_def = None
839
852
840 # get the __init__ docstring
853 # get the __init__ docstring
841 try:
854 try:
842 obj_init = obj.__init__
855 obj_init = obj.__init__
843 except AttributeError:
856 except AttributeError:
844 init_ds = None
857 init_ds = None
845 else:
858 else:
846 if init_def is None:
859 if init_def is None:
847 # Get signature from init if top-level sig failed.
860 # Get signature from init if top-level sig failed.
848 # Can happen for built-in types (list, etc.).
861 # Can happen for built-in types (list, etc.).
849 try:
862 try:
850 init_def = self._getdef(obj_init, oname)
863 init_def = self._getdef(obj_init, oname)
851 except AttributeError:
864 except AttributeError:
852 pass
865 pass
853 init_ds = getdoc(obj_init)
866 init_ds = getdoc(obj_init)
854 # Skip Python's auto-generated docstrings
867 # Skip Python's auto-generated docstrings
855 if init_ds == _object_init_docstring:
868 if init_ds == _object_init_docstring:
856 init_ds = None
869 init_ds = None
857
870
858 if init_def:
871 if init_def:
859 out['init_definition'] = init_def
872 out['init_definition'] = init_def
860
873
861 if init_ds:
874 if init_ds:
862 out['init_docstring'] = init_ds
875 out['init_docstring'] = init_ds
863
876
864 names = [sub.__name__ for sub in type.__subclasses__(obj)]
877 names = [sub.__name__ for sub in type.__subclasses__(obj)]
865 if len(names) < 10:
878 if len(names) < 10:
866 all_names = ', '.join(names)
879 all_names = ', '.join(names)
867 else:
880 else:
868 all_names = ', '.join(names[:10]+['...'])
881 all_names = ', '.join(names[:10]+['...'])
869 out['subclasses'] = all_names
882 out['subclasses'] = all_names
870 # and class docstring for instances:
883 # and class docstring for instances:
871 else:
884 else:
872 # reconstruct the function definition and print it:
885 # reconstruct the function definition and print it:
873 defln = self._getdef(obj, oname)
886 defln = self._getdef(obj, oname)
874 if defln:
887 if defln:
875 out['definition'] = defln
888 out['definition'] = defln
876
889
877 # First, check whether the instance docstring is identical to the
890 # First, check whether the instance docstring is identical to the
878 # class one, and print it separately if they don't coincide. In
891 # class one, and print it separately if they don't coincide. In
879 # most cases they will, but it's nice to print all the info for
892 # most cases they will, but it's nice to print all the info for
880 # objects which use instance-customized docstrings.
893 # objects which use instance-customized docstrings.
881 if ds:
894 if ds:
882 try:
895 try:
883 cls = getattr(obj,'__class__')
896 cls = getattr(obj,'__class__')
884 except:
897 except:
885 class_ds = None
898 class_ds = None
886 else:
899 else:
887 class_ds = getdoc(cls)
900 class_ds = getdoc(cls)
888 # Skip Python's auto-generated docstrings
901 # Skip Python's auto-generated docstrings
889 if class_ds in _builtin_type_docstrings:
902 if class_ds in _builtin_type_docstrings:
890 class_ds = None
903 class_ds = None
891 if class_ds and ds != class_ds:
904 if class_ds and ds != class_ds:
892 out['class_docstring'] = class_ds
905 out['class_docstring'] = class_ds
893
906
894 # Next, try to show constructor docstrings
907 # Next, try to show constructor docstrings
895 try:
908 try:
896 init_ds = getdoc(obj.__init__)
909 init_ds = getdoc(obj.__init__)
897 # Skip Python's auto-generated docstrings
910 # Skip Python's auto-generated docstrings
898 if init_ds == _object_init_docstring:
911 if init_ds == _object_init_docstring:
899 init_ds = None
912 init_ds = None
900 except AttributeError:
913 except AttributeError:
901 init_ds = None
914 init_ds = None
902 if init_ds:
915 if init_ds:
903 out['init_docstring'] = init_ds
916 out['init_docstring'] = init_ds
904
917
905 # Call form docstring for callable instances
918 # Call form docstring for callable instances
906 if safe_hasattr(obj, '__call__') and not is_simple_callable(obj):
919 if safe_hasattr(obj, '__call__') and not is_simple_callable(obj):
907 call_def = self._getdef(obj.__call__, oname)
920 call_def = self._getdef(obj.__call__, oname)
908 if call_def and (call_def != out.get('definition')):
921 if call_def and (call_def != out.get('definition')):
909 # it may never be the case that call def and definition differ,
922 # it may never be the case that call def and definition differ,
910 # but don't include the same signature twice
923 # but don't include the same signature twice
911 out['call_def'] = call_def
924 out['call_def'] = call_def
912 call_ds = getdoc(obj.__call__)
925 call_ds = getdoc(obj.__call__)
913 # Skip Python's auto-generated docstrings
926 # Skip Python's auto-generated docstrings
914 if call_ds == _func_call_docstring:
927 if call_ds == _func_call_docstring:
915 call_ds = None
928 call_ds = None
916 if call_ds:
929 if call_ds:
917 out['call_docstring'] = call_ds
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 return object_info(**out)
932 return object_info(**out)
947
933
948 @staticmethod
934 @staticmethod
949 def _source_contains_docstring(src, doc):
935 def _source_contains_docstring(src, doc):
950 """
936 """
951 Check whether the source *src* contains the docstring *doc*.
937 Check whether the source *src* contains the docstring *doc*.
952
938
953 This is is helper function to skip displaying the docstring if the
939 This is is helper function to skip displaying the docstring if the
954 source already contains it, avoiding repetition of information.
940 source already contains it, avoiding repetition of information.
955 """
941 """
956 try:
942 try:
957 def_node, = ast.parse(dedent(src)).body
943 def_node, = ast.parse(dedent(src)).body
958 return ast.get_docstring(def_node) == doc
944 return ast.get_docstring(def_node) == doc
959 except Exception:
945 except Exception:
960 # The source can become invalid or even non-existent (because it
946 # The source can become invalid or even non-existent (because it
961 # is re-fetched from the source file) so the above code fail in
947 # is re-fetched from the source file) so the above code fail in
962 # arbitrary ways.
948 # arbitrary ways.
963 return False
949 return False
964
950
965 def psearch(self,pattern,ns_table,ns_search=[],
951 def psearch(self,pattern,ns_table,ns_search=[],
966 ignore_case=False,show_all=False, *, list_types=False):
952 ignore_case=False,show_all=False, *, list_types=False):
967 """Search namespaces with wildcards for objects.
953 """Search namespaces with wildcards for objects.
968
954
969 Arguments:
955 Arguments:
970
956
971 - pattern: string containing shell-like wildcards to use in namespace
957 - pattern: string containing shell-like wildcards to use in namespace
972 searches and optionally a type specification to narrow the search to
958 searches and optionally a type specification to narrow the search to
973 objects of that type.
959 objects of that type.
974
960
975 - ns_table: dict of name->namespaces for search.
961 - ns_table: dict of name->namespaces for search.
976
962
977 Optional arguments:
963 Optional arguments:
978
964
979 - ns_search: list of namespace names to include in search.
965 - ns_search: list of namespace names to include in search.
980
966
981 - ignore_case(False): make the search case-insensitive.
967 - ignore_case(False): make the search case-insensitive.
982
968
983 - show_all(False): show all names, including those starting with
969 - show_all(False): show all names, including those starting with
984 underscores.
970 underscores.
985
971
986 - list_types(False): list all available object types for object matching.
972 - list_types(False): list all available object types for object matching.
987 """
973 """
988 #print 'ps pattern:<%r>' % pattern # dbg
974 #print 'ps pattern:<%r>' % pattern # dbg
989
975
990 # defaults
976 # defaults
991 type_pattern = 'all'
977 type_pattern = 'all'
992 filter = ''
978 filter = ''
993
979
994 # list all object types
980 # list all object types
995 if list_types:
981 if list_types:
996 page.page('\n'.join(sorted(typestr2type)))
982 page.page('\n'.join(sorted(typestr2type)))
997 return
983 return
998
984
999 cmds = pattern.split()
985 cmds = pattern.split()
1000 len_cmds = len(cmds)
986 len_cmds = len(cmds)
1001 if len_cmds == 1:
987 if len_cmds == 1:
1002 # Only filter pattern given
988 # Only filter pattern given
1003 filter = cmds[0]
989 filter = cmds[0]
1004 elif len_cmds == 2:
990 elif len_cmds == 2:
1005 # Both filter and type specified
991 # Both filter and type specified
1006 filter,type_pattern = cmds
992 filter,type_pattern = cmds
1007 else:
993 else:
1008 raise ValueError('invalid argument string for psearch: <%s>' %
994 raise ValueError('invalid argument string for psearch: <%s>' %
1009 pattern)
995 pattern)
1010
996
1011 # filter search namespaces
997 # filter search namespaces
1012 for name in ns_search:
998 for name in ns_search:
1013 if name not in ns_table:
999 if name not in ns_table:
1014 raise ValueError('invalid namespace <%s>. Valid names: %s' %
1000 raise ValueError('invalid namespace <%s>. Valid names: %s' %
1015 (name,ns_table.keys()))
1001 (name,ns_table.keys()))
1016
1002
1017 #print 'type_pattern:',type_pattern # dbg
1003 #print 'type_pattern:',type_pattern # dbg
1018 search_result, namespaces_seen = set(), set()
1004 search_result, namespaces_seen = set(), set()
1019 for ns_name in ns_search:
1005 for ns_name in ns_search:
1020 ns = ns_table[ns_name]
1006 ns = ns_table[ns_name]
1021 # Normally, locals and globals are the same, so we just check one.
1007 # Normally, locals and globals are the same, so we just check one.
1022 if id(ns) in namespaces_seen:
1008 if id(ns) in namespaces_seen:
1023 continue
1009 continue
1024 namespaces_seen.add(id(ns))
1010 namespaces_seen.add(id(ns))
1025 tmp_res = list_namespace(ns, type_pattern, filter,
1011 tmp_res = list_namespace(ns, type_pattern, filter,
1026 ignore_case=ignore_case, show_all=show_all)
1012 ignore_case=ignore_case, show_all=show_all)
1027 search_result.update(tmp_res)
1013 search_result.update(tmp_res)
1028
1014
1029 page.page('\n'.join(sorted(search_result)))
1015 page.page('\n'.join(sorted(search_result)))
1030
1016
1031
1017
1032 def _render_signature(obj_signature, obj_name):
1018 def _render_signature(obj_signature, obj_name):
1033 """
1019 """
1034 This was mostly taken from inspect.Signature.__str__.
1020 This was mostly taken from inspect.Signature.__str__.
1035 Look there for the comments.
1021 Look there for the comments.
1036 The only change is to add linebreaks when this gets too long.
1022 The only change is to add linebreaks when this gets too long.
1037 """
1023 """
1038 result = []
1024 result = []
1039 pos_only = False
1025 pos_only = False
1040 kw_only = True
1026 kw_only = True
1041 for param in obj_signature.parameters.values():
1027 for param in obj_signature.parameters.values():
1042 if param.kind == inspect._POSITIONAL_ONLY:
1028 if param.kind == inspect._POSITIONAL_ONLY:
1043 pos_only = True
1029 pos_only = True
1044 elif pos_only:
1030 elif pos_only:
1045 result.append('/')
1031 result.append('/')
1046 pos_only = False
1032 pos_only = False
1047
1033
1048 if param.kind == inspect._VAR_POSITIONAL:
1034 if param.kind == inspect._VAR_POSITIONAL:
1049 kw_only = False
1035 kw_only = False
1050 elif param.kind == inspect._KEYWORD_ONLY and kw_only:
1036 elif param.kind == inspect._KEYWORD_ONLY and kw_only:
1051 result.append('*')
1037 result.append('*')
1052 kw_only = False
1038 kw_only = False
1053
1039
1054 result.append(str(param))
1040 result.append(str(param))
1055
1041
1056 if pos_only:
1042 if pos_only:
1057 result.append('/')
1043 result.append('/')
1058
1044
1059 # add up name, parameters, braces (2), and commas
1045 # add up name, parameters, braces (2), and commas
1060 if len(obj_name) + sum(len(r) + 2 for r in result) > 75:
1046 if len(obj_name) + sum(len(r) + 2 for r in result) > 75:
1061 # This doesn’t fit behind “Signature: ” in an inspect window.
1047 # This doesn’t fit behind “Signature: ” in an inspect window.
1062 rendered = '{}(\n{})'.format(obj_name, ''.join(
1048 rendered = '{}(\n{})'.format(obj_name, ''.join(
1063 ' {},\n'.format(r) for r in result)
1049 ' {},\n'.format(r) for r in result)
1064 )
1050 )
1065 else:
1051 else:
1066 rendered = '{}({})'.format(obj_name, ', '.join(result))
1052 rendered = '{}({})'.format(obj_name, ', '.join(result))
1067
1053
1068 if obj_signature.return_annotation is not inspect._empty:
1054 if obj_signature.return_annotation is not inspect._empty:
1069 anno = inspect.formatannotation(obj_signature.return_annotation)
1055 anno = inspect.formatannotation(obj_signature.return_annotation)
1070 rendered += ' -> {}'.format(anno)
1056 rendered += ' -> {}'.format(anno)
1071
1057
1072 return rendered
1058 return rendered
@@ -1,366 +1,372 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 Paging capabilities for IPython.core
3 Paging capabilities for IPython.core
4
4
5 Notes
5 Notes
6 -----
6 -----
7
7
8 For now this uses IPython hooks, so it can't be in IPython.utils. If we can get
8 For now this uses IPython hooks, so it can't be in IPython.utils. If we can get
9 rid of that dependency, we could move it there.
9 rid of that dependency, we could move it there.
10 -----
10 -----
11 """
11 """
12
12
13 # Copyright (c) IPython Development Team.
13 # Copyright (c) IPython Development Team.
14 # Distributed under the terms of the Modified BSD License.
14 # Distributed under the terms of the Modified BSD License.
15
15
16
16
17 import os
17 import os
18 import io
18 import re
19 import re
19 import sys
20 import sys
20 import tempfile
21 import tempfile
22 import subprocess
21
23
22 from io import UnsupportedOperation
24 from io import UnsupportedOperation
23
25
24 from IPython import get_ipython
26 from IPython import get_ipython
25 from IPython.core.display import display
27 from IPython.core.display import display
26 from IPython.core.error import TryNext
28 from IPython.core.error import TryNext
27 from IPython.utils.data import chop
29 from IPython.utils.data import chop
28 from IPython.utils.process import system
30 from IPython.utils.process import system
29 from IPython.utils.terminal import get_terminal_size
31 from IPython.utils.terminal import get_terminal_size
30 from IPython.utils import py3compat
32 from IPython.utils import py3compat
31
33
32
34
33 def display_page(strng, start=0, screen_lines=25):
35 def display_page(strng, start=0, screen_lines=25):
34 """Just display, no paging. screen_lines is ignored."""
36 """Just display, no paging. screen_lines is ignored."""
35 if isinstance(strng, dict):
37 if isinstance(strng, dict):
36 data = strng
38 data = strng
37 else:
39 else:
38 if start:
40 if start:
39 strng = u'\n'.join(strng.splitlines()[start:])
41 strng = u'\n'.join(strng.splitlines()[start:])
40 data = { 'text/plain': strng }
42 data = { 'text/plain': strng }
41 display(data, raw=True)
43 display(data, raw=True)
42
44
43
45
44 def as_hook(page_func):
46 def as_hook(page_func):
45 """Wrap a pager func to strip the `self` arg
47 """Wrap a pager func to strip the `self` arg
46
48
47 so it can be called as a hook.
49 so it can be called as a hook.
48 """
50 """
49 return lambda self, *args, **kwargs: page_func(*args, **kwargs)
51 return lambda self, *args, **kwargs: page_func(*args, **kwargs)
50
52
51
53
52 esc_re = re.compile(r"(\x1b[^m]+m)")
54 esc_re = re.compile(r"(\x1b[^m]+m)")
53
55
54 def page_dumb(strng, start=0, screen_lines=25):
56 def page_dumb(strng, start=0, screen_lines=25):
55 """Very dumb 'pager' in Python, for when nothing else works.
57 """Very dumb 'pager' in Python, for when nothing else works.
56
58
57 Only moves forward, same interface as page(), except for pager_cmd and
59 Only moves forward, same interface as page(), except for pager_cmd and
58 mode.
60 mode.
59 """
61 """
60 if isinstance(strng, dict):
62 if isinstance(strng, dict):
61 strng = strng.get('text/plain', '')
63 strng = strng.get('text/plain', '')
62 out_ln = strng.splitlines()[start:]
64 out_ln = strng.splitlines()[start:]
63 screens = chop(out_ln,screen_lines-1)
65 screens = chop(out_ln,screen_lines-1)
64 if len(screens) == 1:
66 if len(screens) == 1:
65 print(os.linesep.join(screens[0]))
67 print(os.linesep.join(screens[0]))
66 else:
68 else:
67 last_escape = ""
69 last_escape = ""
68 for scr in screens[0:-1]:
70 for scr in screens[0:-1]:
69 hunk = os.linesep.join(scr)
71 hunk = os.linesep.join(scr)
70 print(last_escape + hunk)
72 print(last_escape + hunk)
71 if not page_more():
73 if not page_more():
72 return
74 return
73 esc_list = esc_re.findall(hunk)
75 esc_list = esc_re.findall(hunk)
74 if len(esc_list) > 0:
76 if len(esc_list) > 0:
75 last_escape = esc_list[-1]
77 last_escape = esc_list[-1]
76 print(last_escape + os.linesep.join(screens[-1]))
78 print(last_escape + os.linesep.join(screens[-1]))
77
79
78 def _detect_screen_size(screen_lines_def):
80 def _detect_screen_size(screen_lines_def):
79 """Attempt to work out the number of lines on the screen.
81 """Attempt to work out the number of lines on the screen.
80
82
81 This is called by page(). It can raise an error (e.g. when run in the
83 This is called by page(). It can raise an error (e.g. when run in the
82 test suite), so it's separated out so it can easily be called in a try block.
84 test suite), so it's separated out so it can easily be called in a try block.
83 """
85 """
84 TERM = os.environ.get('TERM',None)
86 TERM = os.environ.get('TERM',None)
85 if not((TERM=='xterm' or TERM=='xterm-color') and sys.platform != 'sunos5'):
87 if not((TERM=='xterm' or TERM=='xterm-color') and sys.platform != 'sunos5'):
86 # curses causes problems on many terminals other than xterm, and
88 # curses causes problems on many terminals other than xterm, and
87 # some termios calls lock up on Sun OS5.
89 # some termios calls lock up on Sun OS5.
88 return screen_lines_def
90 return screen_lines_def
89
91
90 try:
92 try:
91 import termios
93 import termios
92 import curses
94 import curses
93 except ImportError:
95 except ImportError:
94 return screen_lines_def
96 return screen_lines_def
95
97
96 # There is a bug in curses, where *sometimes* it fails to properly
98 # There is a bug in curses, where *sometimes* it fails to properly
97 # initialize, and then after the endwin() call is made, the
99 # initialize, and then after the endwin() call is made, the
98 # terminal is left in an unusable state. Rather than trying to
100 # terminal is left in an unusable state. Rather than trying to
99 # check every time for this (by requesting and comparing termios
101 # check every time for this (by requesting and comparing termios
100 # flags each time), we just save the initial terminal state and
102 # flags each time), we just save the initial terminal state and
101 # unconditionally reset it every time. It's cheaper than making
103 # unconditionally reset it every time. It's cheaper than making
102 # the checks.
104 # the checks.
103 try:
105 try:
104 term_flags = termios.tcgetattr(sys.stdout)
106 term_flags = termios.tcgetattr(sys.stdout)
105 except termios.error as err:
107 except termios.error as err:
106 # can fail on Linux 2.6, pager_page will catch the TypeError
108 # can fail on Linux 2.6, pager_page will catch the TypeError
107 raise TypeError('termios error: {0}'.format(err))
109 raise TypeError('termios error: {0}'.format(err))
108
110
109 try:
111 try:
110 scr = curses.initscr()
112 scr = curses.initscr()
111 except AttributeError:
113 except AttributeError:
112 # Curses on Solaris may not be complete, so we can't use it there
114 # Curses on Solaris may not be complete, so we can't use it there
113 return screen_lines_def
115 return screen_lines_def
114
116
115 screen_lines_real,screen_cols = scr.getmaxyx()
117 screen_lines_real,screen_cols = scr.getmaxyx()
116 curses.endwin()
118 curses.endwin()
117
119
118 # Restore terminal state in case endwin() didn't.
120 # Restore terminal state in case endwin() didn't.
119 termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags)
121 termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags)
120 # Now we have what we needed: the screen size in rows/columns
122 # Now we have what we needed: the screen size in rows/columns
121 return screen_lines_real
123 return screen_lines_real
122 #print '***Screen size:',screen_lines_real,'lines x',\
124 #print '***Screen size:',screen_lines_real,'lines x',\
123 #screen_cols,'columns.' # dbg
125 #screen_cols,'columns.' # dbg
124
126
125 def pager_page(strng, start=0, screen_lines=0, pager_cmd=None):
127 def pager_page(strng, start=0, screen_lines=0, pager_cmd=None):
126 """Display a string, piping through a pager after a certain length.
128 """Display a string, piping through a pager after a certain length.
127
129
128 strng can be a mime-bundle dict, supplying multiple representations,
130 strng can be a mime-bundle dict, supplying multiple representations,
129 keyed by mime-type.
131 keyed by mime-type.
130
132
131 The screen_lines parameter specifies the number of *usable* lines of your
133 The screen_lines parameter specifies the number of *usable* lines of your
132 terminal screen (total lines minus lines you need to reserve to show other
134 terminal screen (total lines minus lines you need to reserve to show other
133 information).
135 information).
134
136
135 If you set screen_lines to a number <=0, page() will try to auto-determine
137 If you set screen_lines to a number <=0, page() will try to auto-determine
136 your screen size and will only use up to (screen_size+screen_lines) for
138 your screen size and will only use up to (screen_size+screen_lines) for
137 printing, paging after that. That is, if you want auto-detection but need
139 printing, paging after that. That is, if you want auto-detection but need
138 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
140 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
139 auto-detection without any lines reserved simply use screen_lines = 0.
141 auto-detection without any lines reserved simply use screen_lines = 0.
140
142
141 If a string won't fit in the allowed lines, it is sent through the
143 If a string won't fit in the allowed lines, it is sent through the
142 specified pager command. If none given, look for PAGER in the environment,
144 specified pager command. If none given, look for PAGER in the environment,
143 and ultimately default to less.
145 and ultimately default to less.
144
146
145 If no system pager works, the string is sent through a 'dumb pager'
147 If no system pager works, the string is sent through a 'dumb pager'
146 written in python, very simplistic.
148 written in python, very simplistic.
147 """
149 """
148
150
149 # for compatibility with mime-bundle form:
151 # for compatibility with mime-bundle form:
150 if isinstance(strng, dict):
152 if isinstance(strng, dict):
151 strng = strng['text/plain']
153 strng = strng['text/plain']
152
154
153 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
155 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
154 TERM = os.environ.get('TERM','dumb')
156 TERM = os.environ.get('TERM','dumb')
155 if TERM in ['dumb','emacs'] and os.name != 'nt':
157 if TERM in ['dumb','emacs'] and os.name != 'nt':
156 print(strng)
158 print(strng)
157 return
159 return
158 # chop off the topmost part of the string we don't want to see
160 # chop off the topmost part of the string we don't want to see
159 str_lines = strng.splitlines()[start:]
161 str_lines = strng.splitlines()[start:]
160 str_toprint = os.linesep.join(str_lines)
162 str_toprint = os.linesep.join(str_lines)
161 num_newlines = len(str_lines)
163 num_newlines = len(str_lines)
162 len_str = len(str_toprint)
164 len_str = len(str_toprint)
163
165
164 # Dumb heuristics to guesstimate number of on-screen lines the string
166 # Dumb heuristics to guesstimate number of on-screen lines the string
165 # takes. Very basic, but good enough for docstrings in reasonable
167 # takes. Very basic, but good enough for docstrings in reasonable
166 # terminals. If someone later feels like refining it, it's not hard.
168 # terminals. If someone later feels like refining it, it's not hard.
167 numlines = max(num_newlines,int(len_str/80)+1)
169 numlines = max(num_newlines,int(len_str/80)+1)
168
170
169 screen_lines_def = get_terminal_size()[1]
171 screen_lines_def = get_terminal_size()[1]
170
172
171 # auto-determine screen size
173 # auto-determine screen size
172 if screen_lines <= 0:
174 if screen_lines <= 0:
173 try:
175 try:
174 screen_lines += _detect_screen_size(screen_lines_def)
176 screen_lines += _detect_screen_size(screen_lines_def)
175 except (TypeError, UnsupportedOperation):
177 except (TypeError, UnsupportedOperation):
176 print(str_toprint)
178 print(str_toprint)
177 return
179 return
178
180
179 #print 'numlines',numlines,'screenlines',screen_lines # dbg
181 #print 'numlines',numlines,'screenlines',screen_lines # dbg
180 if numlines <= screen_lines :
182 if numlines <= screen_lines :
181 #print '*** normal print' # dbg
183 #print '*** normal print' # dbg
182 print(str_toprint)
184 print(str_toprint)
183 else:
185 else:
184 # Try to open pager and default to internal one if that fails.
186 # Try to open pager and default to internal one if that fails.
185 # All failure modes are tagged as 'retval=1', to match the return
187 # All failure modes are tagged as 'retval=1', to match the return
186 # value of a failed system command. If any intermediate attempt
188 # value of a failed system command. If any intermediate attempt
187 # sets retval to 1, at the end we resort to our own page_dumb() pager.
189 # sets retval to 1, at the end we resort to our own page_dumb() pager.
188 pager_cmd = get_pager_cmd(pager_cmd)
190 pager_cmd = get_pager_cmd(pager_cmd)
189 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
191 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
190 if os.name == 'nt':
192 if os.name == 'nt':
191 if pager_cmd.startswith('type'):
193 if pager_cmd.startswith('type'):
192 # The default WinXP 'type' command is failing on complex strings.
194 # The default WinXP 'type' command is failing on complex strings.
193 retval = 1
195 retval = 1
194 else:
196 else:
195 fd, tmpname = tempfile.mkstemp('.txt')
197 fd, tmpname = tempfile.mkstemp('.txt')
196 try:
198 try:
197 os.close(fd)
199 os.close(fd)
198 with open(tmpname, 'wt') as tmpfile:
200 with open(tmpname, 'wt') as tmpfile:
199 tmpfile.write(strng)
201 tmpfile.write(strng)
200 cmd = "%s < %s" % (pager_cmd, tmpname)
202 cmd = "%s < %s" % (pager_cmd, tmpname)
201 # tmpfile needs to be closed for windows
203 # tmpfile needs to be closed for windows
202 if os.system(cmd):
204 if os.system(cmd):
203 retval = 1
205 retval = 1
204 else:
206 else:
205 retval = None
207 retval = None
206 finally:
208 finally:
207 os.remove(tmpname)
209 os.remove(tmpname)
208 else:
210 else:
209 try:
211 try:
210 retval = None
212 retval = None
211 # if I use popen4, things hang. No idea why.
213 # Emulate os.popen, but redirect stderr
212 #pager,shell_out = os.popen4(pager_cmd)
214 proc = subprocess.Popen(pager_cmd,
213 pager = os.popen(pager_cmd, 'w')
215 shell=True,
216 stdin=subprocess.PIPE,
217 stderr=subprocess.DEVNULL
218 )
219 pager = os._wrap_close(io.TextIOWrapper(proc.stdin), proc)
214 try:
220 try:
215 pager_encoding = pager.encoding or sys.stdout.encoding
221 pager_encoding = pager.encoding or sys.stdout.encoding
216 pager.write(strng)
222 pager.write(strng)
217 finally:
223 finally:
218 retval = pager.close()
224 retval = pager.close()
219 except IOError as msg: # broken pipe when user quits
225 except IOError as msg: # broken pipe when user quits
220 if msg.args == (32, 'Broken pipe'):
226 if msg.args == (32, 'Broken pipe'):
221 retval = None
227 retval = None
222 else:
228 else:
223 retval = 1
229 retval = 1
224 except OSError:
230 except OSError:
225 # Other strange problems, sometimes seen in Win2k/cygwin
231 # Other strange problems, sometimes seen in Win2k/cygwin
226 retval = 1
232 retval = 1
227 if retval is not None:
233 if retval is not None:
228 page_dumb(strng,screen_lines=screen_lines)
234 page_dumb(strng,screen_lines=screen_lines)
229
235
230
236
231 def page(data, start=0, screen_lines=0, pager_cmd=None):
237 def page(data, start=0, screen_lines=0, pager_cmd=None):
232 """Display content in a pager, piping through a pager after a certain length.
238 """Display content in a pager, piping through a pager after a certain length.
233
239
234 data can be a mime-bundle dict, supplying multiple representations,
240 data can be a mime-bundle dict, supplying multiple representations,
235 keyed by mime-type, or text.
241 keyed by mime-type, or text.
236
242
237 Pager is dispatched via the `show_in_pager` IPython hook.
243 Pager is dispatched via the `show_in_pager` IPython hook.
238 If no hook is registered, `pager_page` will be used.
244 If no hook is registered, `pager_page` will be used.
239 """
245 """
240 # Some routines may auto-compute start offsets incorrectly and pass a
246 # Some routines may auto-compute start offsets incorrectly and pass a
241 # negative value. Offset to 0 for robustness.
247 # negative value. Offset to 0 for robustness.
242 start = max(0, start)
248 start = max(0, start)
243
249
244 # first, try the hook
250 # first, try the hook
245 ip = get_ipython()
251 ip = get_ipython()
246 if ip:
252 if ip:
247 try:
253 try:
248 ip.hooks.show_in_pager(data, start=start, screen_lines=screen_lines)
254 ip.hooks.show_in_pager(data, start=start, screen_lines=screen_lines)
249 return
255 return
250 except TryNext:
256 except TryNext:
251 pass
257 pass
252
258
253 # fallback on default pager
259 # fallback on default pager
254 return pager_page(data, start, screen_lines, pager_cmd)
260 return pager_page(data, start, screen_lines, pager_cmd)
255
261
256
262
257 def page_file(fname, start=0, pager_cmd=None):
263 def page_file(fname, start=0, pager_cmd=None):
258 """Page a file, using an optional pager command and starting line.
264 """Page a file, using an optional pager command and starting line.
259 """
265 """
260
266
261 pager_cmd = get_pager_cmd(pager_cmd)
267 pager_cmd = get_pager_cmd(pager_cmd)
262 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
268 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
263
269
264 try:
270 try:
265 if os.environ['TERM'] in ['emacs','dumb']:
271 if os.environ['TERM'] in ['emacs','dumb']:
266 raise EnvironmentError
272 raise EnvironmentError
267 system(pager_cmd + ' ' + fname)
273 system(pager_cmd + ' ' + fname)
268 except:
274 except:
269 try:
275 try:
270 if start > 0:
276 if start > 0:
271 start -= 1
277 start -= 1
272 page(open(fname).read(),start)
278 page(open(fname).read(),start)
273 except:
279 except:
274 print('Unable to show file',repr(fname))
280 print('Unable to show file',repr(fname))
275
281
276
282
277 def get_pager_cmd(pager_cmd=None):
283 def get_pager_cmd(pager_cmd=None):
278 """Return a pager command.
284 """Return a pager command.
279
285
280 Makes some attempts at finding an OS-correct one.
286 Makes some attempts at finding an OS-correct one.
281 """
287 """
282 if os.name == 'posix':
288 if os.name == 'posix':
283 default_pager_cmd = 'less -R' # -R for color control sequences
289 default_pager_cmd = 'less -R' # -R for color control sequences
284 elif os.name in ['nt','dos']:
290 elif os.name in ['nt','dos']:
285 default_pager_cmd = 'type'
291 default_pager_cmd = 'type'
286
292
287 if pager_cmd is None:
293 if pager_cmd is None:
288 try:
294 try:
289 pager_cmd = os.environ['PAGER']
295 pager_cmd = os.environ['PAGER']
290 except:
296 except:
291 pager_cmd = default_pager_cmd
297 pager_cmd = default_pager_cmd
292
298
293 if pager_cmd == 'less' and '-r' not in os.environ.get('LESS', '').lower():
299 if pager_cmd == 'less' and '-r' not in os.environ.get('LESS', '').lower():
294 pager_cmd += ' -R'
300 pager_cmd += ' -R'
295
301
296 return pager_cmd
302 return pager_cmd
297
303
298
304
299 def get_pager_start(pager, start):
305 def get_pager_start(pager, start):
300 """Return the string for paging files with an offset.
306 """Return the string for paging files with an offset.
301
307
302 This is the '+N' argument which less and more (under Unix) accept.
308 This is the '+N' argument which less and more (under Unix) accept.
303 """
309 """
304
310
305 if pager in ['less','more']:
311 if pager in ['less','more']:
306 if start:
312 if start:
307 start_string = '+' + str(start)
313 start_string = '+' + str(start)
308 else:
314 else:
309 start_string = ''
315 start_string = ''
310 else:
316 else:
311 start_string = ''
317 start_string = ''
312 return start_string
318 return start_string
313
319
314
320
315 # (X)emacs on win32 doesn't like to be bypassed with msvcrt.getch()
321 # (X)emacs on win32 doesn't like to be bypassed with msvcrt.getch()
316 if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
322 if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
317 import msvcrt
323 import msvcrt
318 def page_more():
324 def page_more():
319 """ Smart pausing between pages
325 """ Smart pausing between pages
320
326
321 @return: True if need print more lines, False if quit
327 @return: True if need print more lines, False if quit
322 """
328 """
323 sys.stdout.write('---Return to continue, q to quit--- ')
329 sys.stdout.write('---Return to continue, q to quit--- ')
324 ans = msvcrt.getwch()
330 ans = msvcrt.getwch()
325 if ans in ("q", "Q"):
331 if ans in ("q", "Q"):
326 result = False
332 result = False
327 else:
333 else:
328 result = True
334 result = True
329 sys.stdout.write("\b"*37 + " "*37 + "\b"*37)
335 sys.stdout.write("\b"*37 + " "*37 + "\b"*37)
330 return result
336 return result
331 else:
337 else:
332 def page_more():
338 def page_more():
333 ans = py3compat.input('---Return to continue, q to quit--- ')
339 ans = py3compat.input('---Return to continue, q to quit--- ')
334 if ans.lower().startswith('q'):
340 if ans.lower().startswith('q'):
335 return False
341 return False
336 else:
342 else:
337 return True
343 return True
338
344
339
345
340 def snip_print(str,width = 75,print_full = 0,header = ''):
346 def snip_print(str,width = 75,print_full = 0,header = ''):
341 """Print a string snipping the midsection to fit in width.
347 """Print a string snipping the midsection to fit in width.
342
348
343 print_full: mode control:
349 print_full: mode control:
344
350
345 - 0: only snip long strings
351 - 0: only snip long strings
346 - 1: send to page() directly.
352 - 1: send to page() directly.
347 - 2: snip long strings and ask for full length viewing with page()
353 - 2: snip long strings and ask for full length viewing with page()
348
354
349 Return 1 if snipping was necessary, 0 otherwise."""
355 Return 1 if snipping was necessary, 0 otherwise."""
350
356
351 if print_full == 1:
357 if print_full == 1:
352 page(header+str)
358 page(header+str)
353 return 0
359 return 0
354
360
355 print(header, end=' ')
361 print(header, end=' ')
356 if len(str) < width:
362 if len(str) < width:
357 print(str)
363 print(str)
358 snip = 0
364 snip = 0
359 else:
365 else:
360 whalf = int((width -5)/2)
366 whalf = int((width -5)/2)
361 print(str[:whalf] + ' <...> ' + str[-whalf:])
367 print(str[:whalf] + ' <...> ' + str[-whalf:])
362 snip = 1
368 snip = 1
363 if snip and print_full == 2:
369 if snip and print_full == 2:
364 if py3compat.input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
370 if py3compat.input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
365 page(str)
371 page(str)
366 return snip
372 return snip
@@ -1,119 +1,119 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Release data for the IPython project."""
2 """Release data for the IPython project."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (c) 2008, IPython Development Team.
5 # Copyright (c) 2008, IPython Development Team.
6 # Copyright (c) 2001, Fernando Perez <fernando.perez@colorado.edu>
6 # Copyright (c) 2001, Fernando Perez <fernando.perez@colorado.edu>
7 # Copyright (c) 2001, Janko Hauser <jhauser@zscout.de>
7 # Copyright (c) 2001, Janko Hauser <jhauser@zscout.de>
8 # Copyright (c) 2001, Nathaniel Gray <n8gray@caltech.edu>
8 # Copyright (c) 2001, Nathaniel Gray <n8gray@caltech.edu>
9 #
9 #
10 # Distributed under the terms of the Modified BSD License.
10 # Distributed under the terms of the Modified BSD License.
11 #
11 #
12 # The full license is in the file COPYING.txt, distributed with this software.
12 # The full license is in the file COPYING.txt, distributed with this software.
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 # Name of the package for release purposes. This is the name which labels
15 # Name of the package for release purposes. This is the name which labels
16 # the tarballs and RPMs made by distutils, so it's best to lowercase it.
16 # the tarballs and RPMs made by distutils, so it's best to lowercase it.
17 name = 'ipython'
17 name = 'ipython'
18
18
19 # IPython version information. An empty _version_extra corresponds to a full
19 # IPython version information. An empty _version_extra corresponds to a full
20 # release. 'dev' as a _version_extra string means this is a development
20 # release. 'dev' as a _version_extra string means this is a development
21 # version
21 # version
22 _version_major = 7
22 _version_major = 7
23 _version_minor = 10
23 _version_minor = 11
24 _version_patch = 0
24 _version_patch = 0
25 _version_extra = '.dev'
25 _version_extra = '.dev'
26 # _version_extra = 'b1'
26 # _version_extra = 'b1'
27 # _version_extra = '' # Uncomment this for full releases
27 # _version_extra = '' # Uncomment this for full releases
28
28
29 # Construct full version string from these.
29 # Construct full version string from these.
30 _ver = [_version_major, _version_minor, _version_patch]
30 _ver = [_version_major, _version_minor, _version_patch]
31
31
32 __version__ = '.'.join(map(str, _ver))
32 __version__ = '.'.join(map(str, _ver))
33 if _version_extra:
33 if _version_extra:
34 __version__ = __version__ + _version_extra
34 __version__ = __version__ + _version_extra
35
35
36 version = __version__ # backwards compatibility name
36 version = __version__ # backwards compatibility name
37 version_info = (_version_major, _version_minor, _version_patch, _version_extra)
37 version_info = (_version_major, _version_minor, _version_patch, _version_extra)
38
38
39 # Change this when incrementing the kernel protocol version
39 # Change this when incrementing the kernel protocol version
40 kernel_protocol_version_info = (5, 0)
40 kernel_protocol_version_info = (5, 0)
41 kernel_protocol_version = "%i.%i" % kernel_protocol_version_info
41 kernel_protocol_version = "%i.%i" % kernel_protocol_version_info
42
42
43 description = "IPython: Productive Interactive Computing"
43 description = "IPython: Productive Interactive Computing"
44
44
45 long_description = \
45 long_description = \
46 """
46 """
47 IPython provides a rich toolkit to help you make the most out of using Python
47 IPython provides a rich toolkit to help you make the most out of using Python
48 interactively. Its main components are:
48 interactively. Its main components are:
49
49
50 * A powerful interactive Python shell
50 * A powerful interactive Python shell
51 * A `Jupyter <https://jupyter.org/>`_ kernel to work with Python code in Jupyter
51 * A `Jupyter <https://jupyter.org/>`_ kernel to work with Python code in Jupyter
52 notebooks and other interactive frontends.
52 notebooks and other interactive frontends.
53
53
54 The enhanced interactive Python shells have the following main features:
54 The enhanced interactive Python shells have the following main features:
55
55
56 * Comprehensive object introspection.
56 * Comprehensive object introspection.
57
57
58 * Input history, persistent across sessions.
58 * Input history, persistent across sessions.
59
59
60 * Caching of output results during a session with automatically generated
60 * Caching of output results during a session with automatically generated
61 references.
61 references.
62
62
63 * Extensible tab completion, with support by default for completion of python
63 * Extensible tab completion, with support by default for completion of python
64 variables and keywords, filenames and function keywords.
64 variables and keywords, filenames and function keywords.
65
65
66 * Extensible system of 'magic' commands for controlling the environment and
66 * Extensible system of 'magic' commands for controlling the environment and
67 performing many tasks related either to IPython or the operating system.
67 performing many tasks related either to IPython or the operating system.
68
68
69 * A rich configuration system with easy switching between different setups
69 * A rich configuration system with easy switching between different setups
70 (simpler than changing $PYTHONSTARTUP environment variables every time).
70 (simpler than changing $PYTHONSTARTUP environment variables every time).
71
71
72 * Session logging and reloading.
72 * Session logging and reloading.
73
73
74 * Extensible syntax processing for special purpose situations.
74 * Extensible syntax processing for special purpose situations.
75
75
76 * Access to the system shell with user-extensible alias system.
76 * Access to the system shell with user-extensible alias system.
77
77
78 * Easily embeddable in other Python programs and GUIs.
78 * Easily embeddable in other Python programs and GUIs.
79
79
80 * Integrated access to the pdb debugger and the Python profiler.
80 * Integrated access to the pdb debugger and the Python profiler.
81
81
82 The latest development version is always available from IPython's `GitHub
82 The latest development version is always available from IPython's `GitHub
83 site <http://github.com/ipython>`_.
83 site <http://github.com/ipython>`_.
84 """
84 """
85
85
86 license = 'BSD'
86 license = 'BSD'
87
87
88 authors = {'Fernando' : ('Fernando Perez','fperez.net@gmail.com'),
88 authors = {'Fernando' : ('Fernando Perez','fperez.net@gmail.com'),
89 'Janko' : ('Janko Hauser','jhauser@zscout.de'),
89 'Janko' : ('Janko Hauser','jhauser@zscout.de'),
90 'Nathan' : ('Nathaniel Gray','n8gray@caltech.edu'),
90 'Nathan' : ('Nathaniel Gray','n8gray@caltech.edu'),
91 'Ville' : ('Ville Vainio','vivainio@gmail.com'),
91 'Ville' : ('Ville Vainio','vivainio@gmail.com'),
92 'Brian' : ('Brian E Granger', 'ellisonbg@gmail.com'),
92 'Brian' : ('Brian E Granger', 'ellisonbg@gmail.com'),
93 'Min' : ('Min Ragan-Kelley', 'benjaminrk@gmail.com'),
93 'Min' : ('Min Ragan-Kelley', 'benjaminrk@gmail.com'),
94 'Thomas' : ('Thomas A. Kluyver', 'takowl@gmail.com'),
94 'Thomas' : ('Thomas A. Kluyver', 'takowl@gmail.com'),
95 'Jorgen' : ('Jorgen Stenarson', 'jorgen.stenarson@bostream.nu'),
95 'Jorgen' : ('Jorgen Stenarson', 'jorgen.stenarson@bostream.nu'),
96 'Matthias' : ('Matthias Bussonnier', 'bussonniermatthias@gmail.com'),
96 'Matthias' : ('Matthias Bussonnier', 'bussonniermatthias@gmail.com'),
97 }
97 }
98
98
99 author = 'The IPython Development Team'
99 author = 'The IPython Development Team'
100
100
101 author_email = 'ipython-dev@python.org'
101 author_email = 'ipython-dev@python.org'
102
102
103 url = 'https://ipython.org'
103 url = 'https://ipython.org'
104
104
105
105
106 platforms = ['Linux','Mac OSX','Windows']
106 platforms = ['Linux','Mac OSX','Windows']
107
107
108 keywords = ['Interactive','Interpreter','Shell', 'Embedding']
108 keywords = ['Interactive','Interpreter','Shell', 'Embedding']
109
109
110 classifiers = [
110 classifiers = [
111 'Framework :: IPython',
111 'Framework :: IPython',
112 'Intended Audience :: Developers',
112 'Intended Audience :: Developers',
113 'Intended Audience :: Science/Research',
113 'Intended Audience :: Science/Research',
114 'License :: OSI Approved :: BSD License',
114 'License :: OSI Approved :: BSD License',
115 'Programming Language :: Python',
115 'Programming Language :: Python',
116 'Programming Language :: Python :: 3',
116 'Programming Language :: Python :: 3',
117 'Programming Language :: Python :: 3 :: Only',
117 'Programming Language :: Python :: 3 :: Only',
118 'Topic :: System :: Shells'
118 'Topic :: System :: Shells'
119 ]
119 ]
@@ -1,67 +1,66 b''
1 """These kinds of tests are less than ideal, but at least they run.
1 """These kinds of tests are less than ideal, but at least they run.
2
2
3 This was an old test that was being run interactively in the top-level tests/
3 This was an old test that was being run interactively in the top-level tests/
4 directory, which we are removing. For now putting this here ensures at least
4 directory, which we are removing. For now putting this here ensures at least
5 we do run the test, though ultimately this functionality should all be tested
5 we do run the test, though ultimately this functionality should all be tested
6 with better-isolated tests that don't rely on the global instance in iptest.
6 with better-isolated tests that don't rely on the global instance in iptest.
7 """
7 """
8 from IPython.core.splitinput import LineInfo
8 from IPython.core.splitinput import LineInfo
9 from IPython.core.prefilter import AutocallChecker
9 from IPython.core.prefilter import AutocallChecker
10 from IPython.utils import py3compat
11
10
12 def doctest_autocall():
11 def doctest_autocall():
13 """
12 """
14 In [1]: def f1(a,b,c):
13 In [1]: def f1(a,b,c):
15 ...: return a+b+c
14 ...: return a+b+c
16 ...:
15 ...:
17
16
18 In [2]: def f2(a):
17 In [2]: def f2(a):
19 ...: return a + a
18 ...: return a + a
20 ...:
19 ...:
21
20
22 In [3]: def r(x):
21 In [3]: def r(x):
23 ...: return True
22 ...: return True
24 ...:
23 ...:
25
24
26 In [4]: ;f2 a b c
25 In [4]: ;f2 a b c
27 Out[4]: 'a b ca b c'
26 Out[4]: 'a b ca b c'
28
27
29 In [5]: assert _ == "a b ca b c"
28 In [5]: assert _ == "a b ca b c"
30
29
31 In [6]: ,f1 a b c
30 In [6]: ,f1 a b c
32 Out[6]: 'abc'
31 Out[6]: 'abc'
33
32
34 In [7]: assert _ == 'abc'
33 In [7]: assert _ == 'abc'
35
34
36 In [8]: print(_)
35 In [8]: print(_)
37 abc
36 abc
38
37
39 In [9]: /f1 1,2,3
38 In [9]: /f1 1,2,3
40 Out[9]: 6
39 Out[9]: 6
41
40
42 In [10]: assert _ == 6
41 In [10]: assert _ == 6
43
42
44 In [11]: /f2 4
43 In [11]: /f2 4
45 Out[11]: 8
44 Out[11]: 8
46
45
47 In [12]: assert _ == 8
46 In [12]: assert _ == 8
48
47
49 In [12]: del f1, f2
48 In [12]: del f1, f2
50
49
51 In [13]: ,r a
50 In [13]: ,r a
52 Out[13]: True
51 Out[13]: True
53
52
54 In [14]: assert _ == True
53 In [14]: assert _ == True
55
54
56 In [15]: r'a'
55 In [15]: r'a'
57 Out[15]: 'a'
56 Out[15]: 'a'
58
57
59 In [16]: assert _ == 'a'
58 In [16]: assert _ == 'a'
60 """
59 """
61
60
62
61
63 def test_autocall_should_ignore_raw_strings():
62 def test_autocall_should_ignore_raw_strings():
64 line_info = LineInfo("r'a'")
63 line_info = LineInfo("r'a'")
65 pm = ip.prefilter_manager
64 pm = ip.prefilter_manager
66 ac = AutocallChecker(shell=pm.shell, prefilter_manager=pm, config=pm.config)
65 ac = AutocallChecker(shell=pm.shell, prefilter_manager=pm, config=pm.config)
67 assert ac.check(line_info) is None
66 assert ac.check(line_info) is None
@@ -1,95 +1,95 b''
1 """Tests for input handlers.
1 """Tests for input handlers.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Module imports
4 # Module imports
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6
6
7 # third party
7 # third party
8 import nose.tools as nt
8 import nose.tools as nt
9
9
10 # our own packages
10 # our own packages
11 from IPython.core import autocall
11 from IPython.core import autocall
12 from IPython.testing import tools as tt
12 from IPython.testing import tools as tt
13 from IPython.utils import py3compat
13 from IPython.utils import py3compat
14
14
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 # Globals
16 # Globals
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 # Get the public instance of IPython
19 # Get the public instance of IPython
20
20
21 failures = []
21 failures = []
22 num_tests = 0
22 num_tests = 0
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Test functions
25 # Test functions
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27
27
28 class CallableIndexable(object):
28 class CallableIndexable(object):
29 def __getitem__(self, idx): return True
29 def __getitem__(self, idx): return True
30 def __call__(self, *args, **kws): return True
30 def __call__(self, *args, **kws): return True
31
31
32
32
33 class Autocallable(autocall.IPyAutocall):
33 class Autocallable(autocall.IPyAutocall):
34 def __call__(self):
34 def __call__(self):
35 return "called"
35 return "called"
36
36
37
37
38 def run(tests):
38 def run(tests):
39 """Loop through a list of (pre, post) inputs, where pre is the string
39 """Loop through a list of (pre, post) inputs, where pre is the string
40 handed to ipython, and post is how that string looks after it's been
40 handed to ipython, and post is how that string looks after it's been
41 transformed (i.e. ipython's notion of _i)"""
41 transformed (i.e. ipython's notion of _i)"""
42 tt.check_pairs(ip.prefilter_manager.prefilter_lines, tests)
42 tt.check_pairs(ip.prefilter_manager.prefilter_lines, tests)
43
43
44
44
45 def test_handlers():
45 def test_handlers():
46 call_idx = CallableIndexable()
46 call_idx = CallableIndexable()
47 ip.user_ns['call_idx'] = call_idx
47 ip.user_ns['call_idx'] = call_idx
48
48
49 # For many of the below, we're also checking that leading whitespace
49 # For many of the below, we're also checking that leading whitespace
50 # turns off the esc char, which it should unless there is a continuation
50 # turns off the esc char, which it should unless there is a continuation
51 # line.
51 # line.
52 run([(i,py3compat.u_format(o)) for i,o in \
52 run(
53 [('"no change"', '"no change"'), # normal
53 [('"no change"', '"no change"'), # normal
54 (u"lsmagic", "get_ipython().run_line_magic('lsmagic', '')"), # magic
54 (u"lsmagic", "get_ipython().run_line_magic('lsmagic', '')"), # magic
55 #("a = b # PYTHON-MODE", '_i'), # emacs -- avoids _in cache
55 #("a = b # PYTHON-MODE", '_i'), # emacs -- avoids _in cache
56 ]])
56 ])
57
57
58 # Objects which are instances of IPyAutocall are *always* autocalled
58 # Objects which are instances of IPyAutocall are *always* autocalled
59 autocallable = Autocallable()
59 autocallable = Autocallable()
60 ip.user_ns['autocallable'] = autocallable
60 ip.user_ns['autocallable'] = autocallable
61
61
62 # auto
62 # auto
63 ip.magic('autocall 0')
63 ip.magic('autocall 0')
64 # Only explicit escapes or instances of IPyAutocallable should get
64 # Only explicit escapes or instances of IPyAutocallable should get
65 # expanded
65 # expanded
66 run([
66 run([
67 ('len "abc"', 'len "abc"'),
67 ('len "abc"', 'len "abc"'),
68 ('autocallable', 'autocallable()'),
68 ('autocallable', 'autocallable()'),
69 # Don't add extra brackets (gh-1117)
69 # Don't add extra brackets (gh-1117)
70 ('autocallable()', 'autocallable()'),
70 ('autocallable()', 'autocallable()'),
71 ])
71 ])
72 ip.magic('autocall 1')
72 ip.magic('autocall 1')
73 run([
73 run([
74 ('len "abc"', 'len("abc")'),
74 ('len "abc"', 'len("abc")'),
75 ('len "abc";', 'len("abc");'), # ; is special -- moves out of parens
75 ('len "abc";', 'len("abc");'), # ; is special -- moves out of parens
76 # Autocall is turned off if first arg is [] and the object
76 # Autocall is turned off if first arg is [] and the object
77 # is both callable and indexable. Like so:
77 # is both callable and indexable. Like so:
78 ('len [1,2]', 'len([1,2])'), # len doesn't support __getitem__...
78 ('len [1,2]', 'len([1,2])'), # len doesn't support __getitem__...
79 ('call_idx [1]', 'call_idx [1]'), # call_idx *does*..
79 ('call_idx [1]', 'call_idx [1]'), # call_idx *does*..
80 ('call_idx 1', 'call_idx(1)'),
80 ('call_idx 1', 'call_idx(1)'),
81 ('len', 'len'), # only at 2 does it auto-call on single args
81 ('len', 'len'), # only at 2 does it auto-call on single args
82 ])
82 ])
83 ip.magic('autocall 2')
83 ip.magic('autocall 2')
84 run([
84 run([
85 ('len "abc"', 'len("abc")'),
85 ('len "abc"', 'len("abc")'),
86 ('len "abc";', 'len("abc");'),
86 ('len "abc";', 'len("abc");'),
87 ('len [1,2]', 'len([1,2])'),
87 ('len [1,2]', 'len([1,2])'),
88 ('call_idx [1]', 'call_idx [1]'),
88 ('call_idx [1]', 'call_idx [1]'),
89 ('call_idx 1', 'call_idx(1)'),
89 ('call_idx 1', 'call_idx(1)'),
90 # This is what's different:
90 # This is what's different:
91 ('len', 'len()'), # only at 2 does it auto-call on single args
91 ('len', 'len()'), # only at 2 does it auto-call on single args
92 ])
92 ])
93 ip.magic('autocall 1')
93 ip.magic('autocall 1')
94
94
95 nt.assert_equal(failures, [])
95 nt.assert_equal(failures, [])
@@ -1,559 +1,588 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Tests for code execution (%run and related), which is particularly tricky.
2 """Tests for code execution (%run and related), which is particularly tricky.
3
3
4 Because of how %run manages namespaces, and the fact that we are trying here to
4 Because of how %run manages namespaces, and the fact that we are trying here to
5 verify subtle object deletion and reference counting issues, the %run tests
5 verify subtle object deletion and reference counting issues, the %run tests
6 will be kept in this separate file. This makes it easier to aggregate in one
6 will be kept in this separate file. This makes it easier to aggregate in one
7 place the tricks needed to handle it; most other magics are much easier to test
7 place the tricks needed to handle it; most other magics are much easier to test
8 and we do so in a common test_magic file.
8 and we do so in a common test_magic file.
9
9
10 Note that any test using `run -i` should make sure to do a `reset` afterwards,
10 Note that any test using `run -i` should make sure to do a `reset` afterwards,
11 as otherwise it may influence later tests.
11 as otherwise it may influence later tests.
12 """
12 """
13
13
14 # Copyright (c) IPython Development Team.
14 # Copyright (c) IPython Development Team.
15 # Distributed under the terms of the Modified BSD License.
15 # Distributed under the terms of the Modified BSD License.
16
16
17
17
18
18
19 import functools
19 import functools
20 import os
20 import os
21 from os.path import join as pjoin
21 from os.path import join as pjoin
22 import random
22 import random
23 import string
23 import string
24 import sys
24 import sys
25 import textwrap
25 import textwrap
26 import unittest
26 import unittest
27 from unittest.mock import patch
27 from unittest.mock import patch
28
28
29 import nose.tools as nt
29 import nose.tools as nt
30 from nose import SkipTest
30 from nose import SkipTest
31
31
32 from IPython.testing import decorators as dec
32 from IPython.testing import decorators as dec
33 from IPython.testing import tools as tt
33 from IPython.testing import tools as tt
34 from IPython.utils.io import capture_output
34 from IPython.utils.io import capture_output
35 from IPython.utils.tempdir import TemporaryDirectory
35 from IPython.utils.tempdir import TemporaryDirectory
36 from IPython.core import debugger
36 from IPython.core import debugger
37
37
38 def doctest_refbug():
38 def doctest_refbug():
39 """Very nasty problem with references held by multiple runs of a script.
39 """Very nasty problem with references held by multiple runs of a script.
40 See: https://github.com/ipython/ipython/issues/141
40 See: https://github.com/ipython/ipython/issues/141
41
41
42 In [1]: _ip.clear_main_mod_cache()
42 In [1]: _ip.clear_main_mod_cache()
43 # random
43 # random
44
44
45 In [2]: %run refbug
45 In [2]: %run refbug
46
46
47 In [3]: call_f()
47 In [3]: call_f()
48 lowercased: hello
48 lowercased: hello
49
49
50 In [4]: %run refbug
50 In [4]: %run refbug
51
51
52 In [5]: call_f()
52 In [5]: call_f()
53 lowercased: hello
53 lowercased: hello
54 lowercased: hello
54 lowercased: hello
55 """
55 """
56
56
57
57
58 def doctest_run_builtins():
58 def doctest_run_builtins():
59 r"""Check that %run doesn't damage __builtins__.
59 r"""Check that %run doesn't damage __builtins__.
60
60
61 In [1]: import tempfile
61 In [1]: import tempfile
62
62
63 In [2]: bid1 = id(__builtins__)
63 In [2]: bid1 = id(__builtins__)
64
64
65 In [3]: fname = tempfile.mkstemp('.py')[1]
65 In [3]: fname = tempfile.mkstemp('.py')[1]
66
66
67 In [3]: f = open(fname,'w')
67 In [3]: f = open(fname,'w')
68
68
69 In [4]: dummy= f.write('pass\n')
69 In [4]: dummy= f.write('pass\n')
70
70
71 In [5]: f.flush()
71 In [5]: f.flush()
72
72
73 In [6]: t1 = type(__builtins__)
73 In [6]: t1 = type(__builtins__)
74
74
75 In [7]: %run $fname
75 In [7]: %run $fname
76
76
77 In [7]: f.close()
77 In [7]: f.close()
78
78
79 In [8]: bid2 = id(__builtins__)
79 In [8]: bid2 = id(__builtins__)
80
80
81 In [9]: t2 = type(__builtins__)
81 In [9]: t2 = type(__builtins__)
82
82
83 In [10]: t1 == t2
83 In [10]: t1 == t2
84 Out[10]: True
84 Out[10]: True
85
85
86 In [10]: bid1 == bid2
86 In [10]: bid1 == bid2
87 Out[10]: True
87 Out[10]: True
88
88
89 In [12]: try:
89 In [12]: try:
90 ....: os.unlink(fname)
90 ....: os.unlink(fname)
91 ....: except:
91 ....: except:
92 ....: pass
92 ....: pass
93 ....:
93 ....:
94 """
94 """
95
95
96
96
97 def doctest_run_option_parser():
97 def doctest_run_option_parser():
98 r"""Test option parser in %run.
98 r"""Test option parser in %run.
99
99
100 In [1]: %run print_argv.py
100 In [1]: %run print_argv.py
101 []
101 []
102
102
103 In [2]: %run print_argv.py print*.py
103 In [2]: %run print_argv.py print*.py
104 ['print_argv.py']
104 ['print_argv.py']
105
105
106 In [3]: %run -G print_argv.py print*.py
106 In [3]: %run -G print_argv.py print*.py
107 ['print*.py']
107 ['print*.py']
108
108
109 """
109 """
110
110
111
111
112 @dec.skip_win32
112 @dec.skip_win32
113 def doctest_run_option_parser_for_posix():
113 def doctest_run_option_parser_for_posix():
114 r"""Test option parser in %run (Linux/OSX specific).
114 r"""Test option parser in %run (Linux/OSX specific).
115
115
116 You need double quote to escape glob in POSIX systems:
116 You need double quote to escape glob in POSIX systems:
117
117
118 In [1]: %run print_argv.py print\\*.py
118 In [1]: %run print_argv.py print\\*.py
119 ['print*.py']
119 ['print*.py']
120
120
121 You can't use quote to escape glob in POSIX systems:
121 You can't use quote to escape glob in POSIX systems:
122
122
123 In [2]: %run print_argv.py 'print*.py'
123 In [2]: %run print_argv.py 'print*.py'
124 ['print_argv.py']
124 ['print_argv.py']
125
125
126 """
126 """
127
127
128
128
129 @dec.skip_if_not_win32
129 @dec.skip_if_not_win32
130 def doctest_run_option_parser_for_windows():
130 def doctest_run_option_parser_for_windows():
131 r"""Test option parser in %run (Windows specific).
131 r"""Test option parser in %run (Windows specific).
132
132
133 In Windows, you can't escape ``*` `by backslash:
133 In Windows, you can't escape ``*` `by backslash:
134
134
135 In [1]: %run print_argv.py print\\*.py
135 In [1]: %run print_argv.py print\\*.py
136 ['print\\*.py']
136 ['print\\*.py']
137
137
138 You can use quote to escape glob:
138 You can use quote to escape glob:
139
139
140 In [2]: %run print_argv.py 'print*.py'
140 In [2]: %run print_argv.py 'print*.py'
141 ['print*.py']
141 ['print*.py']
142
142
143 """
143 """
144
144
145
145
146 def doctest_reset_del():
146 def doctest_reset_del():
147 """Test that resetting doesn't cause errors in __del__ methods.
147 """Test that resetting doesn't cause errors in __del__ methods.
148
148
149 In [2]: class A(object):
149 In [2]: class A(object):
150 ...: def __del__(self):
150 ...: def __del__(self):
151 ...: print(str("Hi"))
151 ...: print(str("Hi"))
152 ...:
152 ...:
153
153
154 In [3]: a = A()
154 In [3]: a = A()
155
155
156 In [4]: get_ipython().reset()
156 In [4]: get_ipython().reset()
157 Hi
157 Hi
158
158
159 In [5]: 1+1
159 In [5]: 1+1
160 Out[5]: 2
160 Out[5]: 2
161 """
161 """
162
162
163 # For some tests, it will be handy to organize them in a class with a common
163 # For some tests, it will be handy to organize them in a class with a common
164 # setup that makes a temp file
164 # setup that makes a temp file
165
165
166 class TestMagicRunPass(tt.TempFileMixin):
166 class TestMagicRunPass(tt.TempFileMixin):
167
167
168 def setUp(self):
168 def setUp(self):
169 content = "a = [1,2,3]\nb = 1"
169 content = "a = [1,2,3]\nb = 1"
170 self.mktmp(content)
170 self.mktmp(content)
171
171
172 def run_tmpfile(self):
172 def run_tmpfile(self):
173 _ip = get_ipython()
173 _ip = get_ipython()
174 # This fails on Windows if self.tmpfile.name has spaces or "~" in it.
174 # This fails on Windows if self.tmpfile.name has spaces or "~" in it.
175 # See below and ticket https://bugs.launchpad.net/bugs/366353
175 # See below and ticket https://bugs.launchpad.net/bugs/366353
176 _ip.magic('run %s' % self.fname)
176 _ip.magic('run %s' % self.fname)
177
177
178 def run_tmpfile_p(self):
178 def run_tmpfile_p(self):
179 _ip = get_ipython()
179 _ip = get_ipython()
180 # This fails on Windows if self.tmpfile.name has spaces or "~" in it.
180 # This fails on Windows if self.tmpfile.name has spaces or "~" in it.
181 # See below and ticket https://bugs.launchpad.net/bugs/366353
181 # See below and ticket https://bugs.launchpad.net/bugs/366353
182 _ip.magic('run -p %s' % self.fname)
182 _ip.magic('run -p %s' % self.fname)
183
183
184 def test_builtins_id(self):
184 def test_builtins_id(self):
185 """Check that %run doesn't damage __builtins__ """
185 """Check that %run doesn't damage __builtins__ """
186 _ip = get_ipython()
186 _ip = get_ipython()
187 # Test that the id of __builtins__ is not modified by %run
187 # Test that the id of __builtins__ is not modified by %run
188 bid1 = id(_ip.user_ns['__builtins__'])
188 bid1 = id(_ip.user_ns['__builtins__'])
189 self.run_tmpfile()
189 self.run_tmpfile()
190 bid2 = id(_ip.user_ns['__builtins__'])
190 bid2 = id(_ip.user_ns['__builtins__'])
191 nt.assert_equal(bid1, bid2)
191 nt.assert_equal(bid1, bid2)
192
192
193 def test_builtins_type(self):
193 def test_builtins_type(self):
194 """Check that the type of __builtins__ doesn't change with %run.
194 """Check that the type of __builtins__ doesn't change with %run.
195
195
196 However, the above could pass if __builtins__ was already modified to
196 However, the above could pass if __builtins__ was already modified to
197 be a dict (it should be a module) by a previous use of %run. So we
197 be a dict (it should be a module) by a previous use of %run. So we
198 also check explicitly that it really is a module:
198 also check explicitly that it really is a module:
199 """
199 """
200 _ip = get_ipython()
200 _ip = get_ipython()
201 self.run_tmpfile()
201 self.run_tmpfile()
202 nt.assert_equal(type(_ip.user_ns['__builtins__']),type(sys))
202 nt.assert_equal(type(_ip.user_ns['__builtins__']),type(sys))
203
203
204 def test_run_profile( self ):
204 def test_run_profile( self ):
205 """Test that the option -p, which invokes the profiler, do not
205 """Test that the option -p, which invokes the profiler, do not
206 crash by invoking execfile"""
206 crash by invoking execfile"""
207 self.run_tmpfile_p()
207 self.run_tmpfile_p()
208
208
209 def test_run_debug_twice(self):
209 def test_run_debug_twice(self):
210 # https://github.com/ipython/ipython/issues/10028
210 # https://github.com/ipython/ipython/issues/10028
211 _ip = get_ipython()
211 _ip = get_ipython()
212 with tt.fake_input(['c']):
212 with tt.fake_input(['c']):
213 _ip.magic('run -d %s' % self.fname)
213 _ip.magic('run -d %s' % self.fname)
214 with tt.fake_input(['c']):
214 with tt.fake_input(['c']):
215 _ip.magic('run -d %s' % self.fname)
215 _ip.magic('run -d %s' % self.fname)
216
216
217 def test_run_debug_twice_with_breakpoint(self):
217 def test_run_debug_twice_with_breakpoint(self):
218 """Make a valid python temp file."""
218 """Make a valid python temp file."""
219 _ip = get_ipython()
219 _ip = get_ipython()
220 with tt.fake_input(['b 2', 'c', 'c']):
220 with tt.fake_input(['b 2', 'c', 'c']):
221 _ip.magic('run -d %s' % self.fname)
221 _ip.magic('run -d %s' % self.fname)
222
222
223 with tt.fake_input(['c']):
223 with tt.fake_input(['c']):
224 with tt.AssertNotPrints('KeyError'):
224 with tt.AssertNotPrints('KeyError'):
225 _ip.magic('run -d %s' % self.fname)
225 _ip.magic('run -d %s' % self.fname)
226
226
227
227
228 class TestMagicRunSimple(tt.TempFileMixin):
228 class TestMagicRunSimple(tt.TempFileMixin):
229
229
230 def test_simpledef(self):
230 def test_simpledef(self):
231 """Test that simple class definitions work."""
231 """Test that simple class definitions work."""
232 src = ("class foo: pass\n"
232 src = ("class foo: pass\n"
233 "def f(): return foo()")
233 "def f(): return foo()")
234 self.mktmp(src)
234 self.mktmp(src)
235 _ip.magic('run %s' % self.fname)
235 _ip.magic('run %s' % self.fname)
236 _ip.run_cell('t = isinstance(f(), foo)')
236 _ip.run_cell('t = isinstance(f(), foo)')
237 nt.assert_true(_ip.user_ns['t'])
237 nt.assert_true(_ip.user_ns['t'])
238
238
239 def test_obj_del(self):
239 def test_obj_del(self):
240 """Test that object's __del__ methods are called on exit."""
240 """Test that object's __del__ methods are called on exit."""
241 if sys.platform == 'win32':
241 if sys.platform == 'win32':
242 try:
242 try:
243 import win32api
243 import win32api
244 except ImportError:
244 except ImportError:
245 raise SkipTest("Test requires pywin32")
245 raise SkipTest("Test requires pywin32")
246 src = ("class A(object):\n"
246 src = ("class A(object):\n"
247 " def __del__(self):\n"
247 " def __del__(self):\n"
248 " print('object A deleted')\n"
248 " print('object A deleted')\n"
249 "a = A()\n")
249 "a = A()\n")
250 self.mktmp(src)
250 self.mktmp(src)
251 if dec.module_not_available('sqlite3'):
251 if dec.module_not_available('sqlite3'):
252 err = 'WARNING: IPython History requires SQLite, your history will not be saved\n'
252 err = 'WARNING: IPython History requires SQLite, your history will not be saved\n'
253 else:
253 else:
254 err = None
254 err = None
255 tt.ipexec_validate(self.fname, 'object A deleted', err)
255 tt.ipexec_validate(self.fname, 'object A deleted', err)
256
256
257 def test_aggressive_namespace_cleanup(self):
257 def test_aggressive_namespace_cleanup(self):
258 """Test that namespace cleanup is not too aggressive GH-238
258 """Test that namespace cleanup is not too aggressive GH-238
259
259
260 Returning from another run magic deletes the namespace"""
260 Returning from another run magic deletes the namespace"""
261 # see ticket https://github.com/ipython/ipython/issues/238
261 # see ticket https://github.com/ipython/ipython/issues/238
262
262
263 with tt.TempFileMixin() as empty:
263 with tt.TempFileMixin() as empty:
264 empty.mktmp('')
264 empty.mktmp('')
265 # On Windows, the filename will have \users in it, so we need to use the
265 # On Windows, the filename will have \users in it, so we need to use the
266 # repr so that the \u becomes \\u.
266 # repr so that the \u becomes \\u.
267 src = ("ip = get_ipython()\n"
267 src = ("ip = get_ipython()\n"
268 "for i in range(5):\n"
268 "for i in range(5):\n"
269 " try:\n"
269 " try:\n"
270 " ip.magic(%r)\n"
270 " ip.magic(%r)\n"
271 " except NameError as e:\n"
271 " except NameError as e:\n"
272 " print(i)\n"
272 " print(i)\n"
273 " break\n" % ('run ' + empty.fname))
273 " break\n" % ('run ' + empty.fname))
274 self.mktmp(src)
274 self.mktmp(src)
275 _ip.magic('run %s' % self.fname)
275 _ip.magic('run %s' % self.fname)
276 _ip.run_cell('ip == get_ipython()')
276 _ip.run_cell('ip == get_ipython()')
277 nt.assert_equal(_ip.user_ns['i'], 4)
277 nt.assert_equal(_ip.user_ns['i'], 4)
278
278
279 def test_run_second(self):
279 def test_run_second(self):
280 """Test that running a second file doesn't clobber the first, gh-3547
280 """Test that running a second file doesn't clobber the first, gh-3547
281 """
281 """
282 self.mktmp("avar = 1\n"
282 self.mktmp("avar = 1\n"
283 "def afunc():\n"
283 "def afunc():\n"
284 " return avar\n")
284 " return avar\n")
285
285
286 with tt.TempFileMixin() as empty:
286 with tt.TempFileMixin() as empty:
287 empty.mktmp("")
287 empty.mktmp("")
288
288
289 _ip.magic('run %s' % self.fname)
289 _ip.magic('run %s' % self.fname)
290 _ip.magic('run %s' % empty.fname)
290 _ip.magic('run %s' % empty.fname)
291 nt.assert_equal(_ip.user_ns['afunc'](), 1)
291 nt.assert_equal(_ip.user_ns['afunc'](), 1)
292
292
293 @dec.skip_win32
293 @dec.skip_win32
294 def test_tclass(self):
294 def test_tclass(self):
295 mydir = os.path.dirname(__file__)
295 mydir = os.path.dirname(__file__)
296 tc = os.path.join(mydir, 'tclass')
296 tc = os.path.join(mydir, 'tclass')
297 src = ("%%run '%s' C-first\n"
297 src = ("%%run '%s' C-first\n"
298 "%%run '%s' C-second\n"
298 "%%run '%s' C-second\n"
299 "%%run '%s' C-third\n") % (tc, tc, tc)
299 "%%run '%s' C-third\n") % (tc, tc, tc)
300 self.mktmp(src, '.ipy')
300 self.mktmp(src, '.ipy')
301 out = """\
301 out = """\
302 ARGV 1-: ['C-first']
302 ARGV 1-: ['C-first']
303 ARGV 1-: ['C-second']
303 ARGV 1-: ['C-second']
304 tclass.py: deleting object: C-first
304 tclass.py: deleting object: C-first
305 ARGV 1-: ['C-third']
305 ARGV 1-: ['C-third']
306 tclass.py: deleting object: C-second
306 tclass.py: deleting object: C-second
307 tclass.py: deleting object: C-third
307 tclass.py: deleting object: C-third
308 """
308 """
309 if dec.module_not_available('sqlite3'):
309 if dec.module_not_available('sqlite3'):
310 err = 'WARNING: IPython History requires SQLite, your history will not be saved\n'
310 err = 'WARNING: IPython History requires SQLite, your history will not be saved\n'
311 else:
311 else:
312 err = None
312 err = None
313 tt.ipexec_validate(self.fname, out, err)
313 tt.ipexec_validate(self.fname, out, err)
314
314
315 def test_run_i_after_reset(self):
315 def test_run_i_after_reset(self):
316 """Check that %run -i still works after %reset (gh-693)"""
316 """Check that %run -i still works after %reset (gh-693)"""
317 src = "yy = zz\n"
317 src = "yy = zz\n"
318 self.mktmp(src)
318 self.mktmp(src)
319 _ip.run_cell("zz = 23")
319 _ip.run_cell("zz = 23")
320 try:
320 try:
321 _ip.magic('run -i %s' % self.fname)
321 _ip.magic('run -i %s' % self.fname)
322 nt.assert_equal(_ip.user_ns['yy'], 23)
322 nt.assert_equal(_ip.user_ns['yy'], 23)
323 finally:
323 finally:
324 _ip.magic('reset -f')
324 _ip.magic('reset -f')
325
325
326 _ip.run_cell("zz = 23")
326 _ip.run_cell("zz = 23")
327 try:
327 try:
328 _ip.magic('run -i %s' % self.fname)
328 _ip.magic('run -i %s' % self.fname)
329 nt.assert_equal(_ip.user_ns['yy'], 23)
329 nt.assert_equal(_ip.user_ns['yy'], 23)
330 finally:
330 finally:
331 _ip.magic('reset -f')
331 _ip.magic('reset -f')
332
332
333 def test_unicode(self):
333 def test_unicode(self):
334 """Check that files in odd encodings are accepted."""
334 """Check that files in odd encodings are accepted."""
335 mydir = os.path.dirname(__file__)
335 mydir = os.path.dirname(__file__)
336 na = os.path.join(mydir, 'nonascii.py')
336 na = os.path.join(mydir, 'nonascii.py')
337 _ip.magic('run "%s"' % na)
337 _ip.magic('run "%s"' % na)
338 nt.assert_equal(_ip.user_ns['u'], u'Ўт№Ф')
338 nt.assert_equal(_ip.user_ns['u'], u'Ўт№Ф')
339
339
340 def test_run_py_file_attribute(self):
340 def test_run_py_file_attribute(self):
341 """Test handling of `__file__` attribute in `%run <file>.py`."""
341 """Test handling of `__file__` attribute in `%run <file>.py`."""
342 src = "t = __file__\n"
342 src = "t = __file__\n"
343 self.mktmp(src)
343 self.mktmp(src)
344 _missing = object()
344 _missing = object()
345 file1 = _ip.user_ns.get('__file__', _missing)
345 file1 = _ip.user_ns.get('__file__', _missing)
346 _ip.magic('run %s' % self.fname)
346 _ip.magic('run %s' % self.fname)
347 file2 = _ip.user_ns.get('__file__', _missing)
347 file2 = _ip.user_ns.get('__file__', _missing)
348
348
349 # Check that __file__ was equal to the filename in the script's
349 # Check that __file__ was equal to the filename in the script's
350 # namespace.
350 # namespace.
351 nt.assert_equal(_ip.user_ns['t'], self.fname)
351 nt.assert_equal(_ip.user_ns['t'], self.fname)
352
352
353 # Check that __file__ was not leaked back into user_ns.
353 # Check that __file__ was not leaked back into user_ns.
354 nt.assert_equal(file1, file2)
354 nt.assert_equal(file1, file2)
355
355
356 def test_run_ipy_file_attribute(self):
356 def test_run_ipy_file_attribute(self):
357 """Test handling of `__file__` attribute in `%run <file.ipy>`."""
357 """Test handling of `__file__` attribute in `%run <file.ipy>`."""
358 src = "t = __file__\n"
358 src = "t = __file__\n"
359 self.mktmp(src, ext='.ipy')
359 self.mktmp(src, ext='.ipy')
360 _missing = object()
360 _missing = object()
361 file1 = _ip.user_ns.get('__file__', _missing)
361 file1 = _ip.user_ns.get('__file__', _missing)
362 _ip.magic('run %s' % self.fname)
362 _ip.magic('run %s' % self.fname)
363 file2 = _ip.user_ns.get('__file__', _missing)
363 file2 = _ip.user_ns.get('__file__', _missing)
364
364
365 # Check that __file__ was equal to the filename in the script's
365 # Check that __file__ was equal to the filename in the script's
366 # namespace.
366 # namespace.
367 nt.assert_equal(_ip.user_ns['t'], self.fname)
367 nt.assert_equal(_ip.user_ns['t'], self.fname)
368
368
369 # Check that __file__ was not leaked back into user_ns.
369 # Check that __file__ was not leaked back into user_ns.
370 nt.assert_equal(file1, file2)
370 nt.assert_equal(file1, file2)
371
371
372 def test_run_formatting(self):
372 def test_run_formatting(self):
373 """ Test that %run -t -N<N> does not raise a TypeError for N > 1."""
373 """ Test that %run -t -N<N> does not raise a TypeError for N > 1."""
374 src = "pass"
374 src = "pass"
375 self.mktmp(src)
375 self.mktmp(src)
376 _ip.magic('run -t -N 1 %s' % self.fname)
376 _ip.magic('run -t -N 1 %s' % self.fname)
377 _ip.magic('run -t -N 10 %s' % self.fname)
377 _ip.magic('run -t -N 10 %s' % self.fname)
378
378
379 def test_ignore_sys_exit(self):
379 def test_ignore_sys_exit(self):
380 """Test the -e option to ignore sys.exit()"""
380 """Test the -e option to ignore sys.exit()"""
381 src = "import sys; sys.exit(1)"
381 src = "import sys; sys.exit(1)"
382 self.mktmp(src)
382 self.mktmp(src)
383 with tt.AssertPrints('SystemExit'):
383 with tt.AssertPrints('SystemExit'):
384 _ip.magic('run %s' % self.fname)
384 _ip.magic('run %s' % self.fname)
385
385
386 with tt.AssertNotPrints('SystemExit'):
386 with tt.AssertNotPrints('SystemExit'):
387 _ip.magic('run -e %s' % self.fname)
387 _ip.magic('run -e %s' % self.fname)
388
388
389 def test_run_nb(self):
389 def test_run_nb(self):
390 """Test %run notebook.ipynb"""
390 """Test %run notebook.ipynb"""
391 from nbformat import v4, writes
391 from nbformat import v4, writes
392 nb = v4.new_notebook(
392 nb = v4.new_notebook(
393 cells=[
393 cells=[
394 v4.new_markdown_cell("The Ultimate Question of Everything"),
394 v4.new_markdown_cell("The Ultimate Question of Everything"),
395 v4.new_code_cell("answer=42")
395 v4.new_code_cell("answer=42")
396 ]
396 ]
397 )
397 )
398 src = writes(nb, version=4)
398 src = writes(nb, version=4)
399 self.mktmp(src, ext='.ipynb')
399 self.mktmp(src, ext='.ipynb')
400
400
401 _ip.magic("run %s" % self.fname)
401 _ip.magic("run %s" % self.fname)
402
402
403 nt.assert_equal(_ip.user_ns['answer'], 42)
403 nt.assert_equal(_ip.user_ns['answer'], 42)
404
404
405 def test_file_options(self):
405 def test_file_options(self):
406 src = ('import sys\n'
406 src = ('import sys\n'
407 'a = " ".join(sys.argv[1:])\n')
407 'a = " ".join(sys.argv[1:])\n')
408 self.mktmp(src)
408 self.mktmp(src)
409 test_opts = '-x 3 --verbose'
409 test_opts = '-x 3 --verbose'
410 _ip.run_line_magic("run", '{0} {1}'.format(self.fname, test_opts))
410 _ip.run_line_magic("run", '{0} {1}'.format(self.fname, test_opts))
411 nt.assert_equal(_ip.user_ns['a'], test_opts)
411 nt.assert_equal(_ip.user_ns['a'], test_opts)
412
412
413
413
414 class TestMagicRunWithPackage(unittest.TestCase):
414 class TestMagicRunWithPackage(unittest.TestCase):
415
415
416 def writefile(self, name, content):
416 def writefile(self, name, content):
417 path = os.path.join(self.tempdir.name, name)
417 path = os.path.join(self.tempdir.name, name)
418 d = os.path.dirname(path)
418 d = os.path.dirname(path)
419 if not os.path.isdir(d):
419 if not os.path.isdir(d):
420 os.makedirs(d)
420 os.makedirs(d)
421 with open(path, 'w') as f:
421 with open(path, 'w') as f:
422 f.write(textwrap.dedent(content))
422 f.write(textwrap.dedent(content))
423
423
424 def setUp(self):
424 def setUp(self):
425 self.package = package = 'tmp{0}'.format(''.join([random.choice(string.ascii_letters) for i in range(10)]))
425 self.package = package = 'tmp{0}'.format(''.join([random.choice(string.ascii_letters) for i in range(10)]))
426 """Temporary (probably) valid python package name."""
426 """Temporary (probably) valid python package name."""
427
427
428 self.value = int(random.random() * 10000)
428 self.value = int(random.random() * 10000)
429
429
430 self.tempdir = TemporaryDirectory()
430 self.tempdir = TemporaryDirectory()
431 self.__orig_cwd = os.getcwd()
431 self.__orig_cwd = os.getcwd()
432 sys.path.insert(0, self.tempdir.name)
432 sys.path.insert(0, self.tempdir.name)
433
433
434 self.writefile(os.path.join(package, '__init__.py'), '')
434 self.writefile(os.path.join(package, '__init__.py'), '')
435 self.writefile(os.path.join(package, 'sub.py'), """
435 self.writefile(os.path.join(package, 'sub.py'), """
436 x = {0!r}
436 x = {0!r}
437 """.format(self.value))
437 """.format(self.value))
438 self.writefile(os.path.join(package, 'relative.py'), """
438 self.writefile(os.path.join(package, 'relative.py'), """
439 from .sub import x
439 from .sub import x
440 """)
440 """)
441 self.writefile(os.path.join(package, 'absolute.py'), """
441 self.writefile(os.path.join(package, 'absolute.py'), """
442 from {0}.sub import x
442 from {0}.sub import x
443 """.format(package))
443 """.format(package))
444 self.writefile(os.path.join(package, 'args.py'), """
444 self.writefile(os.path.join(package, 'args.py'), """
445 import sys
445 import sys
446 a = " ".join(sys.argv[1:])
446 a = " ".join(sys.argv[1:])
447 """.format(package))
447 """.format(package))
448
448
449 def tearDown(self):
449 def tearDown(self):
450 os.chdir(self.__orig_cwd)
450 os.chdir(self.__orig_cwd)
451 sys.path[:] = [p for p in sys.path if p != self.tempdir.name]
451 sys.path[:] = [p for p in sys.path if p != self.tempdir.name]
452 self.tempdir.cleanup()
452 self.tempdir.cleanup()
453
453
454 def check_run_submodule(self, submodule, opts=''):
454 def check_run_submodule(self, submodule, opts=''):
455 _ip.user_ns.pop('x', None)
455 _ip.user_ns.pop('x', None)
456 _ip.magic('run {2} -m {0}.{1}'.format(self.package, submodule, opts))
456 _ip.magic('run {2} -m {0}.{1}'.format(self.package, submodule, opts))
457 self.assertEqual(_ip.user_ns['x'], self.value,
457 self.assertEqual(_ip.user_ns['x'], self.value,
458 'Variable `x` is not loaded from module `{0}`.'
458 'Variable `x` is not loaded from module `{0}`.'
459 .format(submodule))
459 .format(submodule))
460
460
461 def test_run_submodule_with_absolute_import(self):
461 def test_run_submodule_with_absolute_import(self):
462 self.check_run_submodule('absolute')
462 self.check_run_submodule('absolute')
463
463
464 def test_run_submodule_with_relative_import(self):
464 def test_run_submodule_with_relative_import(self):
465 """Run submodule that has a relative import statement (#2727)."""
465 """Run submodule that has a relative import statement (#2727)."""
466 self.check_run_submodule('relative')
466 self.check_run_submodule('relative')
467
467
468 def test_prun_submodule_with_absolute_import(self):
468 def test_prun_submodule_with_absolute_import(self):
469 self.check_run_submodule('absolute', '-p')
469 self.check_run_submodule('absolute', '-p')
470
470
471 def test_prun_submodule_with_relative_import(self):
471 def test_prun_submodule_with_relative_import(self):
472 self.check_run_submodule('relative', '-p')
472 self.check_run_submodule('relative', '-p')
473
473
474 def with_fake_debugger(func):
474 def with_fake_debugger(func):
475 @functools.wraps(func)
475 @functools.wraps(func)
476 def wrapper(*args, **kwds):
476 def wrapper(*args, **kwds):
477 with patch.object(debugger.Pdb, 'run', staticmethod(eval)):
477 with patch.object(debugger.Pdb, 'run', staticmethod(eval)):
478 return func(*args, **kwds)
478 return func(*args, **kwds)
479 return wrapper
479 return wrapper
480
480
481 @with_fake_debugger
481 @with_fake_debugger
482 def test_debug_run_submodule_with_absolute_import(self):
482 def test_debug_run_submodule_with_absolute_import(self):
483 self.check_run_submodule('absolute', '-d')
483 self.check_run_submodule('absolute', '-d')
484
484
485 @with_fake_debugger
485 @with_fake_debugger
486 def test_debug_run_submodule_with_relative_import(self):
486 def test_debug_run_submodule_with_relative_import(self):
487 self.check_run_submodule('relative', '-d')
487 self.check_run_submodule('relative', '-d')
488
488
489 def test_module_options(self):
489 def test_module_options(self):
490 _ip.user_ns.pop('a', None)
490 _ip.user_ns.pop('a', None)
491 test_opts = '-x abc -m test'
491 test_opts = '-x abc -m test'
492 _ip.run_line_magic('run', '-m {0}.args {1}'.format(self.package, test_opts))
492 _ip.run_line_magic('run', '-m {0}.args {1}'.format(self.package, test_opts))
493 nt.assert_equal(_ip.user_ns['a'], test_opts)
493 nt.assert_equal(_ip.user_ns['a'], test_opts)
494
494
495 def test_module_options_with_separator(self):
495 def test_module_options_with_separator(self):
496 _ip.user_ns.pop('a', None)
496 _ip.user_ns.pop('a', None)
497 test_opts = '-x abc -m test'
497 test_opts = '-x abc -m test'
498 _ip.run_line_magic('run', '-m {0}.args -- {1}'.format(self.package, test_opts))
498 _ip.run_line_magic('run', '-m {0}.args -- {1}'.format(self.package, test_opts))
499 nt.assert_equal(_ip.user_ns['a'], test_opts)
499 nt.assert_equal(_ip.user_ns['a'], test_opts)
500
500
501 def test_run__name__():
501 def test_run__name__():
502 with TemporaryDirectory() as td:
502 with TemporaryDirectory() as td:
503 path = pjoin(td, 'foo.py')
503 path = pjoin(td, 'foo.py')
504 with open(path, 'w') as f:
504 with open(path, 'w') as f:
505 f.write("q = __name__")
505 f.write("q = __name__")
506
506
507 _ip.user_ns.pop('q', None)
507 _ip.user_ns.pop('q', None)
508 _ip.magic('run {}'.format(path))
508 _ip.magic('run {}'.format(path))
509 nt.assert_equal(_ip.user_ns.pop('q'), '__main__')
509 nt.assert_equal(_ip.user_ns.pop('q'), '__main__')
510
510
511 _ip.magic('run -n {}'.format(path))
511 _ip.magic('run -n {}'.format(path))
512 nt.assert_equal(_ip.user_ns.pop('q'), 'foo')
512 nt.assert_equal(_ip.user_ns.pop('q'), 'foo')
513
513
514 try:
514 try:
515 _ip.magic('run -i -n {}'.format(path))
515 _ip.magic('run -i -n {}'.format(path))
516 nt.assert_equal(_ip.user_ns.pop('q'), 'foo')
516 nt.assert_equal(_ip.user_ns.pop('q'), 'foo')
517 finally:
517 finally:
518 _ip.magic('reset -f')
518 _ip.magic('reset -f')
519
519
520
520
521 def test_run_tb():
521 def test_run_tb():
522 """Test traceback offset in %run"""
522 """Test traceback offset in %run"""
523 with TemporaryDirectory() as td:
523 with TemporaryDirectory() as td:
524 path = pjoin(td, 'foo.py')
524 path = pjoin(td, 'foo.py')
525 with open(path, 'w') as f:
525 with open(path, 'w') as f:
526 f.write('\n'.join([
526 f.write('\n'.join([
527 "def foo():",
527 "def foo():",
528 " return bar()",
528 " return bar()",
529 "def bar():",
529 "def bar():",
530 " raise RuntimeError('hello!')",
530 " raise RuntimeError('hello!')",
531 "foo()",
531 "foo()",
532 ]))
532 ]))
533 with capture_output() as io:
533 with capture_output() as io:
534 _ip.magic('run {}'.format(path))
534 _ip.magic('run {}'.format(path))
535 out = io.stdout
535 out = io.stdout
536 nt.assert_not_in("execfile", out)
536 nt.assert_not_in("execfile", out)
537 nt.assert_in("RuntimeError", out)
537 nt.assert_in("RuntimeError", out)
538 nt.assert_equal(out.count("---->"), 3)
538 nt.assert_equal(out.count("---->"), 3)
539 del ip.user_ns['bar']
539 del ip.user_ns['bar']
540 del ip.user_ns['foo']
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 @dec.knownfailureif(sys.platform == 'win32', "writes to io.stdout aren't captured on Windows")
571 @dec.knownfailureif(sys.platform == 'win32', "writes to io.stdout aren't captured on Windows")
543 def test_script_tb():
572 def test_script_tb():
544 """Test traceback offset in `ipython script.py`"""
573 """Test traceback offset in `ipython script.py`"""
545 with TemporaryDirectory() as td:
574 with TemporaryDirectory() as td:
546 path = pjoin(td, 'foo.py')
575 path = pjoin(td, 'foo.py')
547 with open(path, 'w') as f:
576 with open(path, 'w') as f:
548 f.write('\n'.join([
577 f.write('\n'.join([
549 "def foo():",
578 "def foo():",
550 " return bar()",
579 " return bar()",
551 "def bar():",
580 "def bar():",
552 " raise RuntimeError('hello!')",
581 " raise RuntimeError('hello!')",
553 "foo()",
582 "foo()",
554 ]))
583 ]))
555 out, err = tt.ipexec(path)
584 out, err = tt.ipexec(path)
556 nt.assert_not_in("execfile", out)
585 nt.assert_not_in("execfile", out)
557 nt.assert_in("RuntimeError", out)
586 nt.assert_in("RuntimeError", out)
558 nt.assert_equal(out.count("---->"), 3)
587 nt.assert_equal(out.count("---->"), 3)
559
588
@@ -1,440 +1,459 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Tests for IPython.core.ultratb
2 """Tests for IPython.core.ultratb
3 """
3 """
4 import io
4 import io
5 import logging
5 import logging
6 import sys
6 import sys
7 import os.path
7 import os.path
8 from textwrap import dedent
8 from textwrap import dedent
9 import traceback
9 import traceback
10 import unittest
10 import unittest
11 from unittest import mock
11 from unittest import mock
12
12
13 import IPython.core.ultratb as ultratb
13 import IPython.core.ultratb as ultratb
14 from IPython.core.ultratb import ColorTB, VerboseTB, find_recursion
14 from IPython.core.ultratb import ColorTB, VerboseTB, find_recursion
15
15
16
16
17 from IPython.testing import tools as tt
17 from IPython.testing import tools as tt
18 from IPython.testing.decorators import onlyif_unicode_paths
18 from IPython.testing.decorators import onlyif_unicode_paths
19 from IPython.utils.syspathcontext import prepended_to_syspath
19 from IPython.utils.syspathcontext import prepended_to_syspath
20 from IPython.utils.tempdir import TemporaryDirectory
20 from IPython.utils.tempdir import TemporaryDirectory
21
21
22 file_1 = """1
22 file_1 = """1
23 2
23 2
24 3
24 3
25 def f():
25 def f():
26 1/0
26 1/0
27 """
27 """
28
28
29 file_2 = """def f():
29 file_2 = """def f():
30 1/0
30 1/0
31 """
31 """
32
32
33
33
34 def recursionlimit(frames):
34 def recursionlimit(frames):
35 """
35 """
36 decorator to set the recursion limit temporarily
36 decorator to set the recursion limit temporarily
37 """
37 """
38
38
39 def inner(test_function):
39 def inner(test_function):
40 def wrapper(*args, **kwargs):
40 def wrapper(*args, **kwargs):
41 _orig_rec_limit = ultratb._FRAME_RECURSION_LIMIT
41 _orig_rec_limit = ultratb._FRAME_RECURSION_LIMIT
42 ultratb._FRAME_RECURSION_LIMIT = 50
42 ultratb._FRAME_RECURSION_LIMIT = 50
43
43
44 rl = sys.getrecursionlimit()
44 rl = sys.getrecursionlimit()
45 sys.setrecursionlimit(frames)
45 sys.setrecursionlimit(frames)
46 try:
46 try:
47 return test_function(*args, **kwargs)
47 return test_function(*args, **kwargs)
48 finally:
48 finally:
49 sys.setrecursionlimit(rl)
49 sys.setrecursionlimit(rl)
50 ultratb._FRAME_RECURSION_LIMIT = _orig_rec_limit
50 ultratb._FRAME_RECURSION_LIMIT = _orig_rec_limit
51
51
52 return wrapper
52 return wrapper
53
53
54 return inner
54 return inner
55
55
56
56
57 class ChangedPyFileTest(unittest.TestCase):
57 class ChangedPyFileTest(unittest.TestCase):
58 def test_changing_py_file(self):
58 def test_changing_py_file(self):
59 """Traceback produced if the line where the error occurred is missing?
59 """Traceback produced if the line where the error occurred is missing?
60
60
61 https://github.com/ipython/ipython/issues/1456
61 https://github.com/ipython/ipython/issues/1456
62 """
62 """
63 with TemporaryDirectory() as td:
63 with TemporaryDirectory() as td:
64 fname = os.path.join(td, "foo.py")
64 fname = os.path.join(td, "foo.py")
65 with open(fname, "w") as f:
65 with open(fname, "w") as f:
66 f.write(file_1)
66 f.write(file_1)
67
67
68 with prepended_to_syspath(td):
68 with prepended_to_syspath(td):
69 ip.run_cell("import foo")
69 ip.run_cell("import foo")
70
70
71 with tt.AssertPrints("ZeroDivisionError"):
71 with tt.AssertPrints("ZeroDivisionError"):
72 ip.run_cell("foo.f()")
72 ip.run_cell("foo.f()")
73
73
74 # Make the file shorter, so the line of the error is missing.
74 # Make the file shorter, so the line of the error is missing.
75 with open(fname, "w") as f:
75 with open(fname, "w") as f:
76 f.write(file_2)
76 f.write(file_2)
77
77
78 # For some reason, this was failing on the *second* call after
78 # For some reason, this was failing on the *second* call after
79 # changing the file, so we call f() twice.
79 # changing the file, so we call f() twice.
80 with tt.AssertNotPrints("Internal Python error", channel='stderr'):
80 with tt.AssertNotPrints("Internal Python error", channel='stderr'):
81 with tt.AssertPrints("ZeroDivisionError"):
81 with tt.AssertPrints("ZeroDivisionError"):
82 ip.run_cell("foo.f()")
82 ip.run_cell("foo.f()")
83 with tt.AssertPrints("ZeroDivisionError"):
83 with tt.AssertPrints("ZeroDivisionError"):
84 ip.run_cell("foo.f()")
84 ip.run_cell("foo.f()")
85
85
86 iso_8859_5_file = u'''# coding: iso-8859-5
86 iso_8859_5_file = u'''# coding: iso-8859-5
87
87
88 def fail():
88 def fail():
89 """дбИЖ"""
89 """дбИЖ"""
90 1/0 # дбИЖ
90 1/0 # дбИЖ
91 '''
91 '''
92
92
93 class NonAsciiTest(unittest.TestCase):
93 class NonAsciiTest(unittest.TestCase):
94 @onlyif_unicode_paths
94 @onlyif_unicode_paths
95 def test_nonascii_path(self):
95 def test_nonascii_path(self):
96 # Non-ascii directory name as well.
96 # Non-ascii directory name as well.
97 with TemporaryDirectory(suffix=u'é') as td:
97 with TemporaryDirectory(suffix=u'é') as td:
98 fname = os.path.join(td, u"fooé.py")
98 fname = os.path.join(td, u"fooé.py")
99 with open(fname, "w") as f:
99 with open(fname, "w") as f:
100 f.write(file_1)
100 f.write(file_1)
101
101
102 with prepended_to_syspath(td):
102 with prepended_to_syspath(td):
103 ip.run_cell("import foo")
103 ip.run_cell("import foo")
104
104
105 with tt.AssertPrints("ZeroDivisionError"):
105 with tt.AssertPrints("ZeroDivisionError"):
106 ip.run_cell("foo.f()")
106 ip.run_cell("foo.f()")
107
107
108 def test_iso8859_5(self):
108 def test_iso8859_5(self):
109 with TemporaryDirectory() as td:
109 with TemporaryDirectory() as td:
110 fname = os.path.join(td, 'dfghjkl.py')
110 fname = os.path.join(td, 'dfghjkl.py')
111
111
112 with io.open(fname, 'w', encoding='iso-8859-5') as f:
112 with io.open(fname, 'w', encoding='iso-8859-5') as f:
113 f.write(iso_8859_5_file)
113 f.write(iso_8859_5_file)
114
114
115 with prepended_to_syspath(td):
115 with prepended_to_syspath(td):
116 ip.run_cell("from dfghjkl import fail")
116 ip.run_cell("from dfghjkl import fail")
117
117
118 with tt.AssertPrints("ZeroDivisionError"):
118 with tt.AssertPrints("ZeroDivisionError"):
119 with tt.AssertPrints(u'дбИЖ', suppress=False):
119 with tt.AssertPrints(u'дбИЖ', suppress=False):
120 ip.run_cell('fail()')
120 ip.run_cell('fail()')
121
121
122 def test_nonascii_msg(self):
122 def test_nonascii_msg(self):
123 cell = u"raise Exception('é')"
123 cell = u"raise Exception('é')"
124 expected = u"Exception('é')"
124 expected = u"Exception('é')"
125 ip.run_cell("%xmode plain")
125 ip.run_cell("%xmode plain")
126 with tt.AssertPrints(expected):
126 with tt.AssertPrints(expected):
127 ip.run_cell(cell)
127 ip.run_cell(cell)
128
128
129 ip.run_cell("%xmode verbose")
129 ip.run_cell("%xmode verbose")
130 with tt.AssertPrints(expected):
130 with tt.AssertPrints(expected):
131 ip.run_cell(cell)
131 ip.run_cell(cell)
132
132
133 ip.run_cell("%xmode context")
133 ip.run_cell("%xmode context")
134 with tt.AssertPrints(expected):
134 with tt.AssertPrints(expected):
135 ip.run_cell(cell)
135 ip.run_cell(cell)
136
136
137 ip.run_cell("%xmode minimal")
137 ip.run_cell("%xmode minimal")
138 with tt.AssertPrints(u"Exception: é"):
138 with tt.AssertPrints(u"Exception: é"):
139 ip.run_cell(cell)
139 ip.run_cell(cell)
140
140
141 # Put this back into Context mode for later tests.
141 # Put this back into Context mode for later tests.
142 ip.run_cell("%xmode context")
142 ip.run_cell("%xmode context")
143
143
144 class NestedGenExprTestCase(unittest.TestCase):
144 class NestedGenExprTestCase(unittest.TestCase):
145 """
145 """
146 Regression test for the following issues:
146 Regression test for the following issues:
147 https://github.com/ipython/ipython/issues/8293
147 https://github.com/ipython/ipython/issues/8293
148 https://github.com/ipython/ipython/issues/8205
148 https://github.com/ipython/ipython/issues/8205
149 """
149 """
150 def test_nested_genexpr(self):
150 def test_nested_genexpr(self):
151 code = dedent(
151 code = dedent(
152 """\
152 """\
153 class SpecificException(Exception):
153 class SpecificException(Exception):
154 pass
154 pass
155
155
156 def foo(x):
156 def foo(x):
157 raise SpecificException("Success!")
157 raise SpecificException("Success!")
158
158
159 sum(sum(foo(x) for _ in [0]) for x in [0])
159 sum(sum(foo(x) for _ in [0]) for x in [0])
160 """
160 """
161 )
161 )
162 with tt.AssertPrints('SpecificException: Success!', suppress=False):
162 with tt.AssertPrints('SpecificException: Success!', suppress=False):
163 ip.run_cell(code)
163 ip.run_cell(code)
164
164
165
165
166 indentationerror_file = """if True:
166 indentationerror_file = """if True:
167 zoon()
167 zoon()
168 """
168 """
169
169
170 class IndentationErrorTest(unittest.TestCase):
170 class IndentationErrorTest(unittest.TestCase):
171 def test_indentationerror_shows_line(self):
171 def test_indentationerror_shows_line(self):
172 # See issue gh-2398
172 # See issue gh-2398
173 with tt.AssertPrints("IndentationError"):
173 with tt.AssertPrints("IndentationError"):
174 with tt.AssertPrints("zoon()", suppress=False):
174 with tt.AssertPrints("zoon()", suppress=False):
175 ip.run_cell(indentationerror_file)
175 ip.run_cell(indentationerror_file)
176
176
177 with TemporaryDirectory() as td:
177 with TemporaryDirectory() as td:
178 fname = os.path.join(td, "foo.py")
178 fname = os.path.join(td, "foo.py")
179 with open(fname, "w") as f:
179 with open(fname, "w") as f:
180 f.write(indentationerror_file)
180 f.write(indentationerror_file)
181
181
182 with tt.AssertPrints("IndentationError"):
182 with tt.AssertPrints("IndentationError"):
183 with tt.AssertPrints("zoon()", suppress=False):
183 with tt.AssertPrints("zoon()", suppress=False):
184 ip.magic('run %s' % fname)
184 ip.magic('run %s' % fname)
185
185
186 se_file_1 = """1
186 se_file_1 = """1
187 2
187 2
188 7/
188 7/
189 """
189 """
190
190
191 se_file_2 = """7/
191 se_file_2 = """7/
192 """
192 """
193
193
194 class SyntaxErrorTest(unittest.TestCase):
194 class SyntaxErrorTest(unittest.TestCase):
195 def test_syntaxerror_without_lineno(self):
195 def test_syntaxerror_without_lineno(self):
196 with tt.AssertNotPrints("TypeError"):
196 with tt.AssertNotPrints("TypeError"):
197 with tt.AssertPrints("line unknown"):
197 with tt.AssertPrints("line unknown"):
198 ip.run_cell("raise SyntaxError()")
198 ip.run_cell("raise SyntaxError()")
199
199
200 def test_syntaxerror_no_stacktrace_at_compile_time(self):
200 def test_syntaxerror_no_stacktrace_at_compile_time(self):
201 syntax_error_at_compile_time = """
201 syntax_error_at_compile_time = """
202 def foo():
202 def foo():
203 ..
203 ..
204 """
204 """
205 with tt.AssertPrints("SyntaxError"):
205 with tt.AssertPrints("SyntaxError"):
206 ip.run_cell(syntax_error_at_compile_time)
206 ip.run_cell(syntax_error_at_compile_time)
207
207
208 with tt.AssertNotPrints("foo()"):
208 with tt.AssertNotPrints("foo()"):
209 ip.run_cell(syntax_error_at_compile_time)
209 ip.run_cell(syntax_error_at_compile_time)
210
210
211 def test_syntaxerror_stacktrace_when_running_compiled_code(self):
211 def test_syntaxerror_stacktrace_when_running_compiled_code(self):
212 syntax_error_at_runtime = """
212 syntax_error_at_runtime = """
213 def foo():
213 def foo():
214 eval("..")
214 eval("..")
215
215
216 def bar():
216 def bar():
217 foo()
217 foo()
218
218
219 bar()
219 bar()
220 """
220 """
221 with tt.AssertPrints("SyntaxError"):
221 with tt.AssertPrints("SyntaxError"):
222 ip.run_cell(syntax_error_at_runtime)
222 ip.run_cell(syntax_error_at_runtime)
223 # Assert syntax error during runtime generate stacktrace
223 # Assert syntax error during runtime generate stacktrace
224 with tt.AssertPrints(["foo()", "bar()"]):
224 with tt.AssertPrints(["foo()", "bar()"]):
225 ip.run_cell(syntax_error_at_runtime)
225 ip.run_cell(syntax_error_at_runtime)
226 del ip.user_ns['bar']
226 del ip.user_ns['bar']
227 del ip.user_ns['foo']
227 del ip.user_ns['foo']
228
228
229 def test_changing_py_file(self):
229 def test_changing_py_file(self):
230 with TemporaryDirectory() as td:
230 with TemporaryDirectory() as td:
231 fname = os.path.join(td, "foo.py")
231 fname = os.path.join(td, "foo.py")
232 with open(fname, 'w') as f:
232 with open(fname, 'w') as f:
233 f.write(se_file_1)
233 f.write(se_file_1)
234
234
235 with tt.AssertPrints(["7/", "SyntaxError"]):
235 with tt.AssertPrints(["7/", "SyntaxError"]):
236 ip.magic("run " + fname)
236 ip.magic("run " + fname)
237
237
238 # Modify the file
238 # Modify the file
239 with open(fname, 'w') as f:
239 with open(fname, 'w') as f:
240 f.write(se_file_2)
240 f.write(se_file_2)
241
241
242 # The SyntaxError should point to the correct line
242 # The SyntaxError should point to the correct line
243 with tt.AssertPrints(["7/", "SyntaxError"]):
243 with tt.AssertPrints(["7/", "SyntaxError"]):
244 ip.magic("run " + fname)
244 ip.magic("run " + fname)
245
245
246 def test_non_syntaxerror(self):
246 def test_non_syntaxerror(self):
247 # SyntaxTB may be called with an error other than a SyntaxError
247 # SyntaxTB may be called with an error other than a SyntaxError
248 # See e.g. gh-4361
248 # See e.g. gh-4361
249 try:
249 try:
250 raise ValueError('QWERTY')
250 raise ValueError('QWERTY')
251 except ValueError:
251 except ValueError:
252 with tt.AssertPrints('QWERTY'):
252 with tt.AssertPrints('QWERTY'):
253 ip.showsyntaxerror()
253 ip.showsyntaxerror()
254
254
255
255
256 class Python3ChainedExceptionsTest(unittest.TestCase):
256 class Python3ChainedExceptionsTest(unittest.TestCase):
257 DIRECT_CAUSE_ERROR_CODE = """
257 DIRECT_CAUSE_ERROR_CODE = """
258 try:
258 try:
259 x = 1 + 2
259 x = 1 + 2
260 print(not_defined_here)
260 print(not_defined_here)
261 except Exception as e:
261 except Exception as e:
262 x += 55
262 x += 55
263 x - 1
263 x - 1
264 y = {}
264 y = {}
265 raise KeyError('uh') from e
265 raise KeyError('uh') from e
266 """
266 """
267
267
268 EXCEPTION_DURING_HANDLING_CODE = """
268 EXCEPTION_DURING_HANDLING_CODE = """
269 try:
269 try:
270 x = 1 + 2
270 x = 1 + 2
271 print(not_defined_here)
271 print(not_defined_here)
272 except Exception as e:
272 except Exception as e:
273 x += 55
273 x += 55
274 x - 1
274 x - 1
275 y = {}
275 y = {}
276 raise KeyError('uh')
276 raise KeyError('uh')
277 """
277 """
278
278
279 SUPPRESS_CHAINING_CODE = """
279 SUPPRESS_CHAINING_CODE = """
280 try:
280 try:
281 1/0
281 1/0
282 except Exception:
282 except Exception:
283 raise ValueError("Yikes") from None
283 raise ValueError("Yikes") from None
284 """
284 """
285
285
286 def test_direct_cause_error(self):
286 def test_direct_cause_error(self):
287 with tt.AssertPrints(["KeyError", "NameError", "direct cause"]):
287 with tt.AssertPrints(["KeyError", "NameError", "direct cause"]):
288 ip.run_cell(self.DIRECT_CAUSE_ERROR_CODE)
288 ip.run_cell(self.DIRECT_CAUSE_ERROR_CODE)
289
289
290 def test_exception_during_handling_error(self):
290 def test_exception_during_handling_error(self):
291 with tt.AssertPrints(["KeyError", "NameError", "During handling"]):
291 with tt.AssertPrints(["KeyError", "NameError", "During handling"]):
292 ip.run_cell(self.EXCEPTION_DURING_HANDLING_CODE)
292 ip.run_cell(self.EXCEPTION_DURING_HANDLING_CODE)
293
293
294 def test_suppress_exception_chaining(self):
294 def test_suppress_exception_chaining(self):
295 with tt.AssertNotPrints("ZeroDivisionError"), \
295 with tt.AssertNotPrints("ZeroDivisionError"), \
296 tt.AssertPrints("ValueError", suppress=False):
296 tt.AssertPrints("ValueError", suppress=False):
297 ip.run_cell(self.SUPPRESS_CHAINING_CODE)
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 class RecursionTest(unittest.TestCase):
319 class RecursionTest(unittest.TestCase):
301 DEFINITIONS = """
320 DEFINITIONS = """
302 def non_recurs():
321 def non_recurs():
303 1/0
322 1/0
304
323
305 def r1():
324 def r1():
306 r1()
325 r1()
307
326
308 def r3a():
327 def r3a():
309 r3b()
328 r3b()
310
329
311 def r3b():
330 def r3b():
312 r3c()
331 r3c()
313
332
314 def r3c():
333 def r3c():
315 r3a()
334 r3a()
316
335
317 def r3o1():
336 def r3o1():
318 r3a()
337 r3a()
319
338
320 def r3o2():
339 def r3o2():
321 r3o1()
340 r3o1()
322 """
341 """
323 def setUp(self):
342 def setUp(self):
324 ip.run_cell(self.DEFINITIONS)
343 ip.run_cell(self.DEFINITIONS)
325
344
326 def test_no_recursion(self):
345 def test_no_recursion(self):
327 with tt.AssertNotPrints("frames repeated"):
346 with tt.AssertNotPrints("frames repeated"):
328 ip.run_cell("non_recurs()")
347 ip.run_cell("non_recurs()")
329
348
330 @recursionlimit(150)
349 @recursionlimit(150)
331 def test_recursion_one_frame(self):
350 def test_recursion_one_frame(self):
332 with tt.AssertPrints("1 frames repeated"):
351 with tt.AssertPrints("1 frames repeated"):
333 ip.run_cell("r1()")
352 ip.run_cell("r1()")
334
353
335 @recursionlimit(150)
354 @recursionlimit(150)
336 def test_recursion_three_frames(self):
355 def test_recursion_three_frames(self):
337 with tt.AssertPrints("3 frames repeated"):
356 with tt.AssertPrints("3 frames repeated"):
338 ip.run_cell("r3o2()")
357 ip.run_cell("r3o2()")
339
358
340 @recursionlimit(150)
359 @recursionlimit(150)
341 def test_find_recursion(self):
360 def test_find_recursion(self):
342 captured = []
361 captured = []
343 def capture_exc(*args, **kwargs):
362 def capture_exc(*args, **kwargs):
344 captured.append(sys.exc_info())
363 captured.append(sys.exc_info())
345 with mock.patch.object(ip, 'showtraceback', capture_exc):
364 with mock.patch.object(ip, 'showtraceback', capture_exc):
346 ip.run_cell("r3o2()")
365 ip.run_cell("r3o2()")
347
366
348 self.assertEqual(len(captured), 1)
367 self.assertEqual(len(captured), 1)
349 etype, evalue, tb = captured[0]
368 etype, evalue, tb = captured[0]
350 self.assertIn("recursion", str(evalue))
369 self.assertIn("recursion", str(evalue))
351
370
352 records = ip.InteractiveTB.get_records(tb, 3, ip.InteractiveTB.tb_offset)
371 records = ip.InteractiveTB.get_records(tb, 3, ip.InteractiveTB.tb_offset)
353 for r in records[:10]:
372 for r in records[:10]:
354 print(r[1:4])
373 print(r[1:4])
355
374
356 # The outermost frames should be:
375 # The outermost frames should be:
357 # 0: the 'cell' that was running when the exception came up
376 # 0: the 'cell' that was running when the exception came up
358 # 1: r3o2()
377 # 1: r3o2()
359 # 2: r3o1()
378 # 2: r3o1()
360 # 3: r3a()
379 # 3: r3a()
361 # Then repeating r3b, r3c, r3a
380 # Then repeating r3b, r3c, r3a
362 last_unique, repeat_length = find_recursion(etype, evalue, records)
381 last_unique, repeat_length = find_recursion(etype, evalue, records)
363 self.assertEqual(last_unique, 2)
382 self.assertEqual(last_unique, 2)
364 self.assertEqual(repeat_length, 3)
383 self.assertEqual(repeat_length, 3)
365
384
366
385
367 #----------------------------------------------------------------------------
386 #----------------------------------------------------------------------------
368
387
369 # module testing (minimal)
388 # module testing (minimal)
370 def test_handlers():
389 def test_handlers():
371 def spam(c, d_e):
390 def spam(c, d_e):
372 (d, e) = d_e
391 (d, e) = d_e
373 x = c + d
392 x = c + d
374 y = c * d
393 y = c * d
375 foo(x, y)
394 foo(x, y)
376
395
377 def foo(a, b, bar=1):
396 def foo(a, b, bar=1):
378 eggs(a, b + bar)
397 eggs(a, b + bar)
379
398
380 def eggs(f, g, z=globals()):
399 def eggs(f, g, z=globals()):
381 h = f + g
400 h = f + g
382 i = f - g
401 i = f - g
383 return h / i
402 return h / i
384
403
385 buff = io.StringIO()
404 buff = io.StringIO()
386
405
387 buff.write('')
406 buff.write('')
388 buff.write('*** Before ***')
407 buff.write('*** Before ***')
389 try:
408 try:
390 buff.write(spam(1, (2, 3)))
409 buff.write(spam(1, (2, 3)))
391 except:
410 except:
392 traceback.print_exc(file=buff)
411 traceback.print_exc(file=buff)
393
412
394 handler = ColorTB(ostream=buff)
413 handler = ColorTB(ostream=buff)
395 buff.write('*** ColorTB ***')
414 buff.write('*** ColorTB ***')
396 try:
415 try:
397 buff.write(spam(1, (2, 3)))
416 buff.write(spam(1, (2, 3)))
398 except:
417 except:
399 handler(*sys.exc_info())
418 handler(*sys.exc_info())
400 buff.write('')
419 buff.write('')
401
420
402 handler = VerboseTB(ostream=buff)
421 handler = VerboseTB(ostream=buff)
403 buff.write('*** VerboseTB ***')
422 buff.write('*** VerboseTB ***')
404 try:
423 try:
405 buff.write(spam(1, (2, 3)))
424 buff.write(spam(1, (2, 3)))
406 except:
425 except:
407 handler(*sys.exc_info())
426 handler(*sys.exc_info())
408 buff.write('')
427 buff.write('')
409
428
410 from IPython.testing.decorators import skipif
429 from IPython.testing.decorators import skipif
411
430
412 class TokenizeFailureTest(unittest.TestCase):
431 class TokenizeFailureTest(unittest.TestCase):
413 """Tests related to https://github.com/ipython/ipython/issues/6864."""
432 """Tests related to https://github.com/ipython/ipython/issues/6864."""
414
433
415 # that appear to test that we are handling an exception that can be thrown
434 # that appear to test that we are handling an exception that can be thrown
416 # by the tokenizer due to a bug that seem to have been fixed in 3.8, though
435 # by the tokenizer due to a bug that seem to have been fixed in 3.8, though
417 # I'm unsure if other sequences can make it raise this error. Let's just
436 # I'm unsure if other sequences can make it raise this error. Let's just
418 # skip in 3.8 for now
437 # skip in 3.8 for now
419 @skipif(sys.version_info > (3,8))
438 @skipif(sys.version_info > (3,8))
420 def testLogging(self):
439 def testLogging(self):
421 message = "An unexpected error occurred while tokenizing input"
440 message = "An unexpected error occurred while tokenizing input"
422 cell = 'raise ValueError("""a\nb""")'
441 cell = 'raise ValueError("""a\nb""")'
423
442
424 stream = io.StringIO()
443 stream = io.StringIO()
425 handler = logging.StreamHandler(stream)
444 handler = logging.StreamHandler(stream)
426 logger = logging.getLogger()
445 logger = logging.getLogger()
427 loglevel = logger.level
446 loglevel = logger.level
428 logger.addHandler(handler)
447 logger.addHandler(handler)
429 self.addCleanup(lambda: logger.removeHandler(handler))
448 self.addCleanup(lambda: logger.removeHandler(handler))
430 self.addCleanup(lambda: logger.setLevel(loglevel))
449 self.addCleanup(lambda: logger.setLevel(loglevel))
431
450
432 logger.setLevel(logging.INFO)
451 logger.setLevel(logging.INFO)
433 with tt.AssertNotPrints(message):
452 with tt.AssertNotPrints(message):
434 ip.run_cell(cell)
453 ip.run_cell(cell)
435 self.assertNotIn(message, stream.getvalue())
454 self.assertNotIn(message, stream.getvalue())
436
455
437 logger.setLevel(logging.DEBUG)
456 logger.setLevel(logging.DEBUG)
438 with tt.AssertNotPrints(message):
457 with tt.AssertNotPrints(message):
439 ip.run_cell(cell)
458 ip.run_cell(cell)
440 self.assertIn(message, stream.getvalue())
459 self.assertIn(message, stream.getvalue())
@@ -1,1473 +1,1502 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Verbose and colourful traceback formatting.
3 Verbose and colourful traceback formatting.
4
4
5 **ColorTB**
5 **ColorTB**
6
6
7 I've always found it a bit hard to visually parse tracebacks in Python. The
7 I've always found it a bit hard to visually parse tracebacks in Python. The
8 ColorTB class is a solution to that problem. It colors the different parts of a
8 ColorTB class is a solution to that problem. It colors the different parts of a
9 traceback in a manner similar to what you would expect from a syntax-highlighting
9 traceback in a manner similar to what you would expect from a syntax-highlighting
10 text editor.
10 text editor.
11
11
12 Installation instructions for ColorTB::
12 Installation instructions for ColorTB::
13
13
14 import sys,ultratb
14 import sys,ultratb
15 sys.excepthook = ultratb.ColorTB()
15 sys.excepthook = ultratb.ColorTB()
16
16
17 **VerboseTB**
17 **VerboseTB**
18
18
19 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
19 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
20 of useful info when a traceback occurs. Ping originally had it spit out HTML
20 of useful info when a traceback occurs. Ping originally had it spit out HTML
21 and intended it for CGI programmers, but why should they have all the fun? I
21 and intended it for CGI programmers, but why should they have all the fun? I
22 altered it to spit out colored text to the terminal. It's a bit overwhelming,
22 altered it to spit out colored text to the terminal. It's a bit overwhelming,
23 but kind of neat, and maybe useful for long-running programs that you believe
23 but kind of neat, and maybe useful for long-running programs that you believe
24 are bug-free. If a crash *does* occur in that type of program you want details.
24 are bug-free. If a crash *does* occur in that type of program you want details.
25 Give it a shot--you'll love it or you'll hate it.
25 Give it a shot--you'll love it or you'll hate it.
26
26
27 .. note::
27 .. note::
28
28
29 The Verbose mode prints the variables currently visible where the exception
29 The Verbose mode prints the variables currently visible where the exception
30 happened (shortening their strings if too long). This can potentially be
30 happened (shortening their strings if too long). This can potentially be
31 very slow, if you happen to have a huge data structure whose string
31 very slow, if you happen to have a huge data structure whose string
32 representation is complex to compute. Your computer may appear to freeze for
32 representation is complex to compute. Your computer may appear to freeze for
33 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
33 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
34 with Ctrl-C (maybe hitting it more than once).
34 with Ctrl-C (maybe hitting it more than once).
35
35
36 If you encounter this kind of situation often, you may want to use the
36 If you encounter this kind of situation often, you may want to use the
37 Verbose_novars mode instead of the regular Verbose, which avoids formatting
37 Verbose_novars mode instead of the regular Verbose, which avoids formatting
38 variables (but otherwise includes the information and context given by
38 variables (but otherwise includes the information and context given by
39 Verbose).
39 Verbose).
40
40
41 .. note::
41 .. note::
42
42
43 The verbose mode print all variables in the stack, which means it can
43 The verbose mode print all variables in the stack, which means it can
44 potentially leak sensitive information like access keys, or unencrypted
44 potentially leak sensitive information like access keys, or unencrypted
45 password.
45 password.
46
46
47 Installation instructions for VerboseTB::
47 Installation instructions for VerboseTB::
48
48
49 import sys,ultratb
49 import sys,ultratb
50 sys.excepthook = ultratb.VerboseTB()
50 sys.excepthook = ultratb.VerboseTB()
51
51
52 Note: Much of the code in this module was lifted verbatim from the standard
52 Note: Much of the code in this module was lifted verbatim from the standard
53 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
53 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
54
54
55 Color schemes
55 Color schemes
56 -------------
56 -------------
57
57
58 The colors are defined in the class TBTools through the use of the
58 The colors are defined in the class TBTools through the use of the
59 ColorSchemeTable class. Currently the following exist:
59 ColorSchemeTable class. Currently the following exist:
60
60
61 - NoColor: allows all of this module to be used in any terminal (the color
61 - NoColor: allows all of this module to be used in any terminal (the color
62 escapes are just dummy blank strings).
62 escapes are just dummy blank strings).
63
63
64 - Linux: is meant to look good in a terminal like the Linux console (black
64 - Linux: is meant to look good in a terminal like the Linux console (black
65 or very dark background).
65 or very dark background).
66
66
67 - LightBG: similar to Linux but swaps dark/light colors to be more readable
67 - LightBG: similar to Linux but swaps dark/light colors to be more readable
68 in light background terminals.
68 in light background terminals.
69
69
70 - Neutral: a neutral color scheme that should be readable on both light and
70 - Neutral: a neutral color scheme that should be readable on both light and
71 dark background
71 dark background
72
72
73 You can implement other color schemes easily, the syntax is fairly
73 You can implement other color schemes easily, the syntax is fairly
74 self-explanatory. Please send back new schemes you develop to the author for
74 self-explanatory. Please send back new schemes you develop to the author for
75 possible inclusion in future releases.
75 possible inclusion in future releases.
76
76
77 Inheritance diagram:
77 Inheritance diagram:
78
78
79 .. inheritance-diagram:: IPython.core.ultratb
79 .. inheritance-diagram:: IPython.core.ultratb
80 :parts: 3
80 :parts: 3
81 """
81 """
82
82
83 #*****************************************************************************
83 #*****************************************************************************
84 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
84 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
85 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
85 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
86 #
86 #
87 # Distributed under the terms of the BSD License. The full license is in
87 # Distributed under the terms of the BSD License. The full license is in
88 # the file COPYING, distributed as part of this software.
88 # the file COPYING, distributed as part of this software.
89 #*****************************************************************************
89 #*****************************************************************************
90
90
91
91
92 import dis
92 import dis
93 import inspect
93 import inspect
94 import keyword
94 import keyword
95 import linecache
95 import linecache
96 import os
96 import os
97 import pydoc
97 import pydoc
98 import re
98 import re
99 import sys
99 import sys
100 import time
100 import time
101 import tokenize
101 import tokenize
102 import traceback
102 import traceback
103
103
104 try: # Python 2
104 try: # Python 2
105 generate_tokens = tokenize.generate_tokens
105 generate_tokens = tokenize.generate_tokens
106 except AttributeError: # Python 3
106 except AttributeError: # Python 3
107 generate_tokens = tokenize.tokenize
107 generate_tokens = tokenize.tokenize
108
108
109 # For purposes of monkeypatching inspect to fix a bug in it.
109 # For purposes of monkeypatching inspect to fix a bug in it.
110 from inspect import getsourcefile, getfile, getmodule, \
110 from inspect import getsourcefile, getfile, getmodule, \
111 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
111 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
112
112
113 # IPython's own modules
113 # IPython's own modules
114 from IPython import get_ipython
114 from IPython import get_ipython
115 from IPython.core import debugger
115 from IPython.core import debugger
116 from IPython.core.display_trap import DisplayTrap
116 from IPython.core.display_trap import DisplayTrap
117 from IPython.core.excolors import exception_colors
117 from IPython.core.excolors import exception_colors
118 from IPython.utils import PyColorize
118 from IPython.utils import PyColorize
119 from IPython.utils import path as util_path
119 from IPython.utils import path as util_path
120 from IPython.utils import py3compat
120 from IPython.utils import py3compat
121 from IPython.utils.data import uniq_stable
121 from IPython.utils.data import uniq_stable
122 from IPython.utils.terminal import get_terminal_size
122 from IPython.utils.terminal import get_terminal_size
123
123
124 from logging import info, error, debug
124 from logging import info, error, debug
125
125
126 from importlib.util import source_from_cache
126 from importlib.util import source_from_cache
127
127
128 import IPython.utils.colorable as colorable
128 import IPython.utils.colorable as colorable
129
129
130 # Globals
130 # Globals
131 # amount of space to put line numbers before verbose tracebacks
131 # amount of space to put line numbers before verbose tracebacks
132 INDENT_SIZE = 8
132 INDENT_SIZE = 8
133
133
134 # Default color scheme. This is used, for example, by the traceback
134 # Default color scheme. This is used, for example, by the traceback
135 # formatter. When running in an actual IPython instance, the user's rc.colors
135 # formatter. When running in an actual IPython instance, the user's rc.colors
136 # value is used, but having a module global makes this functionality available
136 # value is used, but having a module global makes this functionality available
137 # to users of ultratb who are NOT running inside ipython.
137 # to users of ultratb who are NOT running inside ipython.
138 DEFAULT_SCHEME = 'NoColor'
138 DEFAULT_SCHEME = 'NoColor'
139
139
140
140
141 # Number of frame above which we are likely to have a recursion and will
141 # Number of frame above which we are likely to have a recursion and will
142 # **attempt** to detect it. Made modifiable mostly to speedup test suite
142 # **attempt** to detect it. Made modifiable mostly to speedup test suite
143 # as detecting recursion is one of our slowest test
143 # as detecting recursion is one of our slowest test
144 _FRAME_RECURSION_LIMIT = 500
144 _FRAME_RECURSION_LIMIT = 500
145
145
146 # ---------------------------------------------------------------------------
146 # ---------------------------------------------------------------------------
147 # Code begins
147 # Code begins
148
148
149 # Utility functions
149 # Utility functions
150 def inspect_error():
150 def inspect_error():
151 """Print a message about internal inspect errors.
151 """Print a message about internal inspect errors.
152
152
153 These are unfortunately quite common."""
153 These are unfortunately quite common."""
154
154
155 error('Internal Python error in the inspect module.\n'
155 error('Internal Python error in the inspect module.\n'
156 'Below is the traceback from this internal error.\n')
156 'Below is the traceback from this internal error.\n')
157
157
158
158
159 # This function is a monkeypatch we apply to the Python inspect module. We have
159 # This function is a monkeypatch we apply to the Python inspect module. We have
160 # now found when it's needed (see discussion on issue gh-1456), and we have a
160 # now found when it's needed (see discussion on issue gh-1456), and we have a
161 # test case (IPython.core.tests.test_ultratb.ChangedPyFileTest) that fails if
161 # test case (IPython.core.tests.test_ultratb.ChangedPyFileTest) that fails if
162 # the monkeypatch is not applied. TK, Aug 2012.
162 # the monkeypatch is not applied. TK, Aug 2012.
163 def findsource(object):
163 def findsource(object):
164 """Return the entire source file and starting line number for an object.
164 """Return the entire source file and starting line number for an object.
165
165
166 The argument may be a module, class, method, function, traceback, frame,
166 The argument may be a module, class, method, function, traceback, frame,
167 or code object. The source code is returned as a list of all the lines
167 or code object. The source code is returned as a list of all the lines
168 in the file and the line number indexes a line in that list. An IOError
168 in the file and the line number indexes a line in that list. An IOError
169 is raised if the source code cannot be retrieved.
169 is raised if the source code cannot be retrieved.
170
170
171 FIXED version with which we monkeypatch the stdlib to work around a bug."""
171 FIXED version with which we monkeypatch the stdlib to work around a bug."""
172
172
173 file = getsourcefile(object) or getfile(object)
173 file = getsourcefile(object) or getfile(object)
174 # If the object is a frame, then trying to get the globals dict from its
174 # If the object is a frame, then trying to get the globals dict from its
175 # module won't work. Instead, the frame object itself has the globals
175 # module won't work. Instead, the frame object itself has the globals
176 # dictionary.
176 # dictionary.
177 globals_dict = None
177 globals_dict = None
178 if inspect.isframe(object):
178 if inspect.isframe(object):
179 # XXX: can this ever be false?
179 # XXX: can this ever be false?
180 globals_dict = object.f_globals
180 globals_dict = object.f_globals
181 else:
181 else:
182 module = getmodule(object, file)
182 module = getmodule(object, file)
183 if module:
183 if module:
184 globals_dict = module.__dict__
184 globals_dict = module.__dict__
185 lines = linecache.getlines(file, globals_dict)
185 lines = linecache.getlines(file, globals_dict)
186 if not lines:
186 if not lines:
187 raise IOError('could not get source code')
187 raise IOError('could not get source code')
188
188
189 if ismodule(object):
189 if ismodule(object):
190 return lines, 0
190 return lines, 0
191
191
192 if isclass(object):
192 if isclass(object):
193 name = object.__name__
193 name = object.__name__
194 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
194 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
195 # make some effort to find the best matching class definition:
195 # make some effort to find the best matching class definition:
196 # use the one with the least indentation, which is the one
196 # use the one with the least indentation, which is the one
197 # that's most probably not inside a function definition.
197 # that's most probably not inside a function definition.
198 candidates = []
198 candidates = []
199 for i, line in enumerate(lines):
199 for i, line in enumerate(lines):
200 match = pat.match(line)
200 match = pat.match(line)
201 if match:
201 if match:
202 # if it's at toplevel, it's already the best one
202 # if it's at toplevel, it's already the best one
203 if line[0] == 'c':
203 if line[0] == 'c':
204 return lines, i
204 return lines, i
205 # else add whitespace to candidate list
205 # else add whitespace to candidate list
206 candidates.append((match.group(1), i))
206 candidates.append((match.group(1), i))
207 if candidates:
207 if candidates:
208 # this will sort by whitespace, and by line number,
208 # this will sort by whitespace, and by line number,
209 # less whitespace first
209 # less whitespace first
210 candidates.sort()
210 candidates.sort()
211 return lines, candidates[0][1]
211 return lines, candidates[0][1]
212 else:
212 else:
213 raise IOError('could not find class definition')
213 raise IOError('could not find class definition')
214
214
215 if ismethod(object):
215 if ismethod(object):
216 object = object.__func__
216 object = object.__func__
217 if isfunction(object):
217 if isfunction(object):
218 object = object.__code__
218 object = object.__code__
219 if istraceback(object):
219 if istraceback(object):
220 object = object.tb_frame
220 object = object.tb_frame
221 if isframe(object):
221 if isframe(object):
222 object = object.f_code
222 object = object.f_code
223 if iscode(object):
223 if iscode(object):
224 if not hasattr(object, 'co_firstlineno'):
224 if not hasattr(object, 'co_firstlineno'):
225 raise IOError('could not find function definition')
225 raise IOError('could not find function definition')
226 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
226 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
227 pmatch = pat.match
227 pmatch = pat.match
228 # fperez - fix: sometimes, co_firstlineno can give a number larger than
228 # fperez - fix: sometimes, co_firstlineno can give a number larger than
229 # the length of lines, which causes an error. Safeguard against that.
229 # the length of lines, which causes an error. Safeguard against that.
230 lnum = min(object.co_firstlineno, len(lines)) - 1
230 lnum = min(object.co_firstlineno, len(lines)) - 1
231 while lnum > 0:
231 while lnum > 0:
232 if pmatch(lines[lnum]):
232 if pmatch(lines[lnum]):
233 break
233 break
234 lnum -= 1
234 lnum -= 1
235
235
236 return lines, lnum
236 return lines, lnum
237 raise IOError('could not find code object')
237 raise IOError('could not find code object')
238
238
239
239
240 # This is a patched version of inspect.getargs that applies the (unmerged)
240 # This is a patched version of inspect.getargs that applies the (unmerged)
241 # patch for http://bugs.python.org/issue14611 by Stefano Taschini. This fixes
241 # patch for http://bugs.python.org/issue14611 by Stefano Taschini. This fixes
242 # https://github.com/ipython/ipython/issues/8205 and
242 # https://github.com/ipython/ipython/issues/8205 and
243 # https://github.com/ipython/ipython/issues/8293
243 # https://github.com/ipython/ipython/issues/8293
244 def getargs(co):
244 def getargs(co):
245 """Get information about the arguments accepted by a code object.
245 """Get information about the arguments accepted by a code object.
246
246
247 Three things are returned: (args, varargs, varkw), where 'args' is
247 Three things are returned: (args, varargs, varkw), where 'args' is
248 a list of argument names (possibly containing nested lists), and
248 a list of argument names (possibly containing nested lists), and
249 'varargs' and 'varkw' are the names of the * and ** arguments or None."""
249 'varargs' and 'varkw' are the names of the * and ** arguments or None."""
250 if not iscode(co):
250 if not iscode(co):
251 raise TypeError('{!r} is not a code object'.format(co))
251 raise TypeError('{!r} is not a code object'.format(co))
252
252
253 nargs = co.co_argcount
253 nargs = co.co_argcount
254 names = co.co_varnames
254 names = co.co_varnames
255 args = list(names[:nargs])
255 args = list(names[:nargs])
256 step = 0
256 step = 0
257
257
258 # The following acrobatics are for anonymous (tuple) arguments.
258 # The following acrobatics are for anonymous (tuple) arguments.
259 for i in range(nargs):
259 for i in range(nargs):
260 if args[i][:1] in ('', '.'):
260 if args[i][:1] in ('', '.'):
261 stack, remain, count = [], [], []
261 stack, remain, count = [], [], []
262 while step < len(co.co_code):
262 while step < len(co.co_code):
263 op = ord(co.co_code[step])
263 op = ord(co.co_code[step])
264 step = step + 1
264 step = step + 1
265 if op >= dis.HAVE_ARGUMENT:
265 if op >= dis.HAVE_ARGUMENT:
266 opname = dis.opname[op]
266 opname = dis.opname[op]
267 value = ord(co.co_code[step]) + ord(co.co_code[step+1])*256
267 value = ord(co.co_code[step]) + ord(co.co_code[step+1])*256
268 step = step + 2
268 step = step + 2
269 if opname in ('UNPACK_TUPLE', 'UNPACK_SEQUENCE'):
269 if opname in ('UNPACK_TUPLE', 'UNPACK_SEQUENCE'):
270 remain.append(value)
270 remain.append(value)
271 count.append(value)
271 count.append(value)
272 elif opname in ('STORE_FAST', 'STORE_DEREF'):
272 elif opname in ('STORE_FAST', 'STORE_DEREF'):
273 if op in dis.haslocal:
273 if op in dis.haslocal:
274 stack.append(co.co_varnames[value])
274 stack.append(co.co_varnames[value])
275 elif op in dis.hasfree:
275 elif op in dis.hasfree:
276 stack.append((co.co_cellvars + co.co_freevars)[value])
276 stack.append((co.co_cellvars + co.co_freevars)[value])
277 # Special case for sublists of length 1: def foo((bar))
277 # Special case for sublists of length 1: def foo((bar))
278 # doesn't generate the UNPACK_TUPLE bytecode, so if
278 # doesn't generate the UNPACK_TUPLE bytecode, so if
279 # `remain` is empty here, we have such a sublist.
279 # `remain` is empty here, we have such a sublist.
280 if not remain:
280 if not remain:
281 stack[0] = [stack[0]]
281 stack[0] = [stack[0]]
282 break
282 break
283 else:
283 else:
284 remain[-1] = remain[-1] - 1
284 remain[-1] = remain[-1] - 1
285 while remain[-1] == 0:
285 while remain[-1] == 0:
286 remain.pop()
286 remain.pop()
287 size = count.pop()
287 size = count.pop()
288 stack[-size:] = [stack[-size:]]
288 stack[-size:] = [stack[-size:]]
289 if not remain:
289 if not remain:
290 break
290 break
291 remain[-1] = remain[-1] - 1
291 remain[-1] = remain[-1] - 1
292 if not remain:
292 if not remain:
293 break
293 break
294 args[i] = stack[0]
294 args[i] = stack[0]
295
295
296 varargs = None
296 varargs = None
297 if co.co_flags & inspect.CO_VARARGS:
297 if co.co_flags & inspect.CO_VARARGS:
298 varargs = co.co_varnames[nargs]
298 varargs = co.co_varnames[nargs]
299 nargs = nargs + 1
299 nargs = nargs + 1
300 varkw = None
300 varkw = None
301 if co.co_flags & inspect.CO_VARKEYWORDS:
301 if co.co_flags & inspect.CO_VARKEYWORDS:
302 varkw = co.co_varnames[nargs]
302 varkw = co.co_varnames[nargs]
303 return inspect.Arguments(args, varargs, varkw)
303 return inspect.Arguments(args, varargs, varkw)
304
304
305
305
306 # Monkeypatch inspect to apply our bugfix.
306 # Monkeypatch inspect to apply our bugfix.
307 def with_patch_inspect(f):
307 def with_patch_inspect(f):
308 """
308 """
309 Deprecated since IPython 6.0
309 Deprecated since IPython 6.0
310 decorator for monkeypatching inspect.findsource
310 decorator for monkeypatching inspect.findsource
311 """
311 """
312
312
313 def wrapped(*args, **kwargs):
313 def wrapped(*args, **kwargs):
314 save_findsource = inspect.findsource
314 save_findsource = inspect.findsource
315 save_getargs = inspect.getargs
315 save_getargs = inspect.getargs
316 inspect.findsource = findsource
316 inspect.findsource = findsource
317 inspect.getargs = getargs
317 inspect.getargs = getargs
318 try:
318 try:
319 return f(*args, **kwargs)
319 return f(*args, **kwargs)
320 finally:
320 finally:
321 inspect.findsource = save_findsource
321 inspect.findsource = save_findsource
322 inspect.getargs = save_getargs
322 inspect.getargs = save_getargs
323
323
324 return wrapped
324 return wrapped
325
325
326
326
327 def fix_frame_records_filenames(records):
327 def fix_frame_records_filenames(records):
328 """Try to fix the filenames in each record from inspect.getinnerframes().
328 """Try to fix the filenames in each record from inspect.getinnerframes().
329
329
330 Particularly, modules loaded from within zip files have useless filenames
330 Particularly, modules loaded from within zip files have useless filenames
331 attached to their code object, and inspect.getinnerframes() just uses it.
331 attached to their code object, and inspect.getinnerframes() just uses it.
332 """
332 """
333 fixed_records = []
333 fixed_records = []
334 for frame, filename, line_no, func_name, lines, index in records:
334 for frame, filename, line_no, func_name, lines, index in records:
335 # Look inside the frame's globals dictionary for __file__,
335 # Look inside the frame's globals dictionary for __file__,
336 # which should be better. However, keep Cython filenames since
336 # which should be better. However, keep Cython filenames since
337 # we prefer the source filenames over the compiled .so file.
337 # we prefer the source filenames over the compiled .so file.
338 if not filename.endswith(('.pyx', '.pxd', '.pxi')):
338 if not filename.endswith(('.pyx', '.pxd', '.pxi')):
339 better_fn = frame.f_globals.get('__file__', None)
339 better_fn = frame.f_globals.get('__file__', None)
340 if isinstance(better_fn, str):
340 if isinstance(better_fn, str):
341 # Check the type just in case someone did something weird with
341 # Check the type just in case someone did something weird with
342 # __file__. It might also be None if the error occurred during
342 # __file__. It might also be None if the error occurred during
343 # import.
343 # import.
344 filename = better_fn
344 filename = better_fn
345 fixed_records.append((frame, filename, line_no, func_name, lines, index))
345 fixed_records.append((frame, filename, line_no, func_name, lines, index))
346 return fixed_records
346 return fixed_records
347
347
348
348
349 @with_patch_inspect
349 @with_patch_inspect
350 def _fixed_getinnerframes(etb, context=1, tb_offset=0):
350 def _fixed_getinnerframes(etb, context=1, tb_offset=0):
351 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
351 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
352
352
353 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
353 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
354 # If the error is at the console, don't build any context, since it would
354 # If the error is at the console, don't build any context, since it would
355 # otherwise produce 5 blank lines printed out (there is no file at the
355 # otherwise produce 5 blank lines printed out (there is no file at the
356 # console)
356 # console)
357 rec_check = records[tb_offset:]
357 rec_check = records[tb_offset:]
358 try:
358 try:
359 rname = rec_check[0][1]
359 rname = rec_check[0][1]
360 if rname == '<ipython console>' or rname.endswith('<string>'):
360 if rname == '<ipython console>' or rname.endswith('<string>'):
361 return rec_check
361 return rec_check
362 except IndexError:
362 except IndexError:
363 pass
363 pass
364
364
365 aux = traceback.extract_tb(etb)
365 aux = traceback.extract_tb(etb)
366 assert len(records) == len(aux)
366 assert len(records) == len(aux)
367 for i, (file, lnum, _, _) in enumerate(aux):
367 for i, (file, lnum, _, _) in enumerate(aux):
368 maybeStart = lnum - 1 - context // 2
368 maybeStart = lnum - 1 - context // 2
369 start = max(maybeStart, 0)
369 start = max(maybeStart, 0)
370 end = start + context
370 end = start + context
371 lines = linecache.getlines(file)[start:end]
371 lines = linecache.getlines(file)[start:end]
372 buf = list(records[i])
372 buf = list(records[i])
373 buf[LNUM_POS] = lnum
373 buf[LNUM_POS] = lnum
374 buf[INDEX_POS] = lnum - 1 - start
374 buf[INDEX_POS] = lnum - 1 - start
375 buf[LINES_POS] = lines
375 buf[LINES_POS] = lines
376 records[i] = tuple(buf)
376 records[i] = tuple(buf)
377 return records[tb_offset:]
377 return records[tb_offset:]
378
378
379 # Helper function -- largely belongs to VerboseTB, but we need the same
379 # Helper function -- largely belongs to VerboseTB, but we need the same
380 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
380 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
381 # can be recognized properly by ipython.el's py-traceback-line-re
381 # can be recognized properly by ipython.el's py-traceback-line-re
382 # (SyntaxErrors have to be treated specially because they have no traceback)
382 # (SyntaxErrors have to be treated specially because they have no traceback)
383
383
384
384
385 def _format_traceback_lines(lnum, index, lines, Colors, lvals, _line_format):
385 def _format_traceback_lines(lnum, index, lines, Colors, lvals, _line_format):
386 """
386 """
387 Format tracebacks lines with pointing arrow, leading numbers...
387 Format tracebacks lines with pointing arrow, leading numbers...
388
388
389 Parameters
389 Parameters
390 ==========
390 ==========
391
391
392 lnum: int
392 lnum: int
393 index: int
393 index: int
394 lines: list[string]
394 lines: list[string]
395 Colors:
395 Colors:
396 ColorScheme used.
396 ColorScheme used.
397 lvals: bytes
397 lvals: bytes
398 Values of local variables, already colored, to inject just after the error line.
398 Values of local variables, already colored, to inject just after the error line.
399 _line_format: f (str) -> (str, bool)
399 _line_format: f (str) -> (str, bool)
400 return (colorized version of str, failure to do so)
400 return (colorized version of str, failure to do so)
401 """
401 """
402 numbers_width = INDENT_SIZE - 1
402 numbers_width = INDENT_SIZE - 1
403 res = []
403 res = []
404
404
405 for i,line in enumerate(lines, lnum-index):
405 for i,line in enumerate(lines, lnum-index):
406 line = py3compat.cast_unicode(line)
406 line = py3compat.cast_unicode(line)
407
407
408 new_line, err = _line_format(line, 'str')
408 new_line, err = _line_format(line, 'str')
409 if not err:
409 if not err:
410 line = new_line
410 line = new_line
411
411
412 if i == lnum:
412 if i == lnum:
413 # This is the line with the error
413 # This is the line with the error
414 pad = numbers_width - len(str(i))
414 pad = numbers_width - len(str(i))
415 num = '%s%s' % (debugger.make_arrow(pad), str(lnum))
415 num = '%s%s' % (debugger.make_arrow(pad), str(lnum))
416 line = '%s%s%s %s%s' % (Colors.linenoEm, num,
416 line = '%s%s%s %s%s' % (Colors.linenoEm, num,
417 Colors.line, line, Colors.Normal)
417 Colors.line, line, Colors.Normal)
418 else:
418 else:
419 num = '%*s' % (numbers_width, i)
419 num = '%*s' % (numbers_width, i)
420 line = '%s%s%s %s' % (Colors.lineno, num,
420 line = '%s%s%s %s' % (Colors.lineno, num,
421 Colors.Normal, line)
421 Colors.Normal, line)
422
422
423 res.append(line)
423 res.append(line)
424 if lvals and i == lnum:
424 if lvals and i == lnum:
425 res.append(lvals + '\n')
425 res.append(lvals + '\n')
426 return res
426 return res
427
427
428 def is_recursion_error(etype, value, records):
428 def is_recursion_error(etype, value, records):
429 try:
429 try:
430 # RecursionError is new in Python 3.5
430 # RecursionError is new in Python 3.5
431 recursion_error_type = RecursionError
431 recursion_error_type = RecursionError
432 except NameError:
432 except NameError:
433 recursion_error_type = RuntimeError
433 recursion_error_type = RuntimeError
434
434
435 # The default recursion limit is 1000, but some of that will be taken up
435 # The default recursion limit is 1000, but some of that will be taken up
436 # by stack frames in IPython itself. >500 frames probably indicates
436 # by stack frames in IPython itself. >500 frames probably indicates
437 # a recursion error.
437 # a recursion error.
438 return (etype is recursion_error_type) \
438 return (etype is recursion_error_type) \
439 and "recursion" in str(value).lower() \
439 and "recursion" in str(value).lower() \
440 and len(records) > _FRAME_RECURSION_LIMIT
440 and len(records) > _FRAME_RECURSION_LIMIT
441
441
442 def find_recursion(etype, value, records):
442 def find_recursion(etype, value, records):
443 """Identify the repeating stack frames from a RecursionError traceback
443 """Identify the repeating stack frames from a RecursionError traceback
444
444
445 'records' is a list as returned by VerboseTB.get_records()
445 'records' is a list as returned by VerboseTB.get_records()
446
446
447 Returns (last_unique, repeat_length)
447 Returns (last_unique, repeat_length)
448 """
448 """
449 # This involves a bit of guesswork - we want to show enough of the traceback
449 # This involves a bit of guesswork - we want to show enough of the traceback
450 # to indicate where the recursion is occurring. We guess that the innermost
450 # to indicate where the recursion is occurring. We guess that the innermost
451 # quarter of the traceback (250 frames by default) is repeats, and find the
451 # quarter of the traceback (250 frames by default) is repeats, and find the
452 # first frame (from in to out) that looks different.
452 # first frame (from in to out) that looks different.
453 if not is_recursion_error(etype, value, records):
453 if not is_recursion_error(etype, value, records):
454 return len(records), 0
454 return len(records), 0
455
455
456 # Select filename, lineno, func_name to track frames with
456 # Select filename, lineno, func_name to track frames with
457 records = [r[1:4] for r in records]
457 records = [r[1:4] for r in records]
458 inner_frames = records[-(len(records)//4):]
458 inner_frames = records[-(len(records)//4):]
459 frames_repeated = set(inner_frames)
459 frames_repeated = set(inner_frames)
460
460
461 last_seen_at = {}
461 last_seen_at = {}
462 longest_repeat = 0
462 longest_repeat = 0
463 i = len(records)
463 i = len(records)
464 for frame in reversed(records):
464 for frame in reversed(records):
465 i -= 1
465 i -= 1
466 if frame not in frames_repeated:
466 if frame not in frames_repeated:
467 last_unique = i
467 last_unique = i
468 break
468 break
469
469
470 if frame in last_seen_at:
470 if frame in last_seen_at:
471 distance = last_seen_at[frame] - i
471 distance = last_seen_at[frame] - i
472 longest_repeat = max(longest_repeat, distance)
472 longest_repeat = max(longest_repeat, distance)
473
473
474 last_seen_at[frame] = i
474 last_seen_at[frame] = i
475 else:
475 else:
476 last_unique = 0 # The whole traceback was recursion
476 last_unique = 0 # The whole traceback was recursion
477
477
478 return last_unique, longest_repeat
478 return last_unique, longest_repeat
479
479
480 #---------------------------------------------------------------------------
480 #---------------------------------------------------------------------------
481 # Module classes
481 # Module classes
482 class TBTools(colorable.Colorable):
482 class TBTools(colorable.Colorable):
483 """Basic tools used by all traceback printer classes."""
483 """Basic tools used by all traceback printer classes."""
484
484
485 # Number of frames to skip when reporting tracebacks
485 # Number of frames to skip when reporting tracebacks
486 tb_offset = 0
486 tb_offset = 0
487
487
488 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
488 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
489 # Whether to call the interactive pdb debugger after printing
489 # Whether to call the interactive pdb debugger after printing
490 # tracebacks or not
490 # tracebacks or not
491 super(TBTools, self).__init__(parent=parent, config=config)
491 super(TBTools, self).__init__(parent=parent, config=config)
492 self.call_pdb = call_pdb
492 self.call_pdb = call_pdb
493
493
494 # Output stream to write to. Note that we store the original value in
494 # Output stream to write to. Note that we store the original value in
495 # a private attribute and then make the public ostream a property, so
495 # a private attribute and then make the public ostream a property, so
496 # that we can delay accessing sys.stdout until runtime. The way
496 # that we can delay accessing sys.stdout until runtime. The way
497 # things are written now, the sys.stdout object is dynamically managed
497 # things are written now, the sys.stdout object is dynamically managed
498 # so a reference to it should NEVER be stored statically. This
498 # so a reference to it should NEVER be stored statically. This
499 # property approach confines this detail to a single location, and all
499 # property approach confines this detail to a single location, and all
500 # subclasses can simply access self.ostream for writing.
500 # subclasses can simply access self.ostream for writing.
501 self._ostream = ostream
501 self._ostream = ostream
502
502
503 # Create color table
503 # Create color table
504 self.color_scheme_table = exception_colors()
504 self.color_scheme_table = exception_colors()
505
505
506 self.set_colors(color_scheme)
506 self.set_colors(color_scheme)
507 self.old_scheme = color_scheme # save initial value for toggles
507 self.old_scheme = color_scheme # save initial value for toggles
508
508
509 if call_pdb:
509 if call_pdb:
510 self.pdb = debugger.Pdb()
510 self.pdb = debugger.Pdb()
511 else:
511 else:
512 self.pdb = None
512 self.pdb = None
513
513
514 def _get_ostream(self):
514 def _get_ostream(self):
515 """Output stream that exceptions are written to.
515 """Output stream that exceptions are written to.
516
516
517 Valid values are:
517 Valid values are:
518
518
519 - None: the default, which means that IPython will dynamically resolve
519 - None: the default, which means that IPython will dynamically resolve
520 to sys.stdout. This ensures compatibility with most tools, including
520 to sys.stdout. This ensures compatibility with most tools, including
521 Windows (where plain stdout doesn't recognize ANSI escapes).
521 Windows (where plain stdout doesn't recognize ANSI escapes).
522
522
523 - Any object with 'write' and 'flush' attributes.
523 - Any object with 'write' and 'flush' attributes.
524 """
524 """
525 return sys.stdout if self._ostream is None else self._ostream
525 return sys.stdout if self._ostream is None else self._ostream
526
526
527 def _set_ostream(self, val):
527 def _set_ostream(self, val):
528 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
528 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
529 self._ostream = val
529 self._ostream = val
530
530
531 ostream = property(_get_ostream, _set_ostream)
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 def set_colors(self, *args, **kw):
557 def set_colors(self, *args, **kw):
534 """Shorthand access to the color table scheme selector method."""
558 """Shorthand access to the color table scheme selector method."""
535
559
536 # Set own color table
560 # Set own color table
537 self.color_scheme_table.set_active_scheme(*args, **kw)
561 self.color_scheme_table.set_active_scheme(*args, **kw)
538 # for convenience, set Colors to the active scheme
562 # for convenience, set Colors to the active scheme
539 self.Colors = self.color_scheme_table.active_colors
563 self.Colors = self.color_scheme_table.active_colors
540 # Also set colors of debugger
564 # Also set colors of debugger
541 if hasattr(self, 'pdb') and self.pdb is not None:
565 if hasattr(self, 'pdb') and self.pdb is not None:
542 self.pdb.set_colors(*args, **kw)
566 self.pdb.set_colors(*args, **kw)
543
567
544 def color_toggle(self):
568 def color_toggle(self):
545 """Toggle between the currently active color scheme and NoColor."""
569 """Toggle between the currently active color scheme and NoColor."""
546
570
547 if self.color_scheme_table.active_scheme_name == 'NoColor':
571 if self.color_scheme_table.active_scheme_name == 'NoColor':
548 self.color_scheme_table.set_active_scheme(self.old_scheme)
572 self.color_scheme_table.set_active_scheme(self.old_scheme)
549 self.Colors = self.color_scheme_table.active_colors
573 self.Colors = self.color_scheme_table.active_colors
550 else:
574 else:
551 self.old_scheme = self.color_scheme_table.active_scheme_name
575 self.old_scheme = self.color_scheme_table.active_scheme_name
552 self.color_scheme_table.set_active_scheme('NoColor')
576 self.color_scheme_table.set_active_scheme('NoColor')
553 self.Colors = self.color_scheme_table.active_colors
577 self.Colors = self.color_scheme_table.active_colors
554
578
555 def stb2text(self, stb):
579 def stb2text(self, stb):
556 """Convert a structured traceback (a list) to a string."""
580 """Convert a structured traceback (a list) to a string."""
557 return '\n'.join(stb)
581 return '\n'.join(stb)
558
582
559 def text(self, etype, value, tb, tb_offset=None, context=5):
583 def text(self, etype, value, tb, tb_offset=None, context=5):
560 """Return formatted traceback.
584 """Return formatted traceback.
561
585
562 Subclasses may override this if they add extra arguments.
586 Subclasses may override this if they add extra arguments.
563 """
587 """
564 tb_list = self.structured_traceback(etype, value, tb,
588 tb_list = self.structured_traceback(etype, value, tb,
565 tb_offset, context)
589 tb_offset, context)
566 return self.stb2text(tb_list)
590 return self.stb2text(tb_list)
567
591
568 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
592 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
569 context=5, mode=None):
593 context=5, mode=None):
570 """Return a list of traceback frames.
594 """Return a list of traceback frames.
571
595
572 Must be implemented by each class.
596 Must be implemented by each class.
573 """
597 """
574 raise NotImplementedError()
598 raise NotImplementedError()
575
599
576
600
577 #---------------------------------------------------------------------------
601 #---------------------------------------------------------------------------
578 class ListTB(TBTools):
602 class ListTB(TBTools):
579 """Print traceback information from a traceback list, with optional color.
603 """Print traceback information from a traceback list, with optional color.
580
604
581 Calling requires 3 arguments: (etype, evalue, elist)
605 Calling requires 3 arguments: (etype, evalue, elist)
582 as would be obtained by::
606 as would be obtained by::
583
607
584 etype, evalue, tb = sys.exc_info()
608 etype, evalue, tb = sys.exc_info()
585 if tb:
609 if tb:
586 elist = traceback.extract_tb(tb)
610 elist = traceback.extract_tb(tb)
587 else:
611 else:
588 elist = None
612 elist = None
589
613
590 It can thus be used by programs which need to process the traceback before
614 It can thus be used by programs which need to process the traceback before
591 printing (such as console replacements based on the code module from the
615 printing (such as console replacements based on the code module from the
592 standard library).
616 standard library).
593
617
594 Because they are meant to be called without a full traceback (only a
618 Because they are meant to be called without a full traceback (only a
595 list), instances of this class can't call the interactive pdb debugger."""
619 list), instances of this class can't call the interactive pdb debugger."""
596
620
597 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
621 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
598 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
622 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
599 ostream=ostream, parent=parent,config=config)
623 ostream=ostream, parent=parent,config=config)
600
624
601 def __call__(self, etype, value, elist):
625 def __call__(self, etype, value, elist):
602 self.ostream.flush()
626 self.ostream.flush()
603 self.ostream.write(self.text(etype, value, elist))
627 self.ostream.write(self.text(etype, value, elist))
604 self.ostream.write('\n')
628 self.ostream.write('\n')
605
629
606 def structured_traceback(self, etype, value, elist, tb_offset=None,
630 def structured_traceback(self, etype, evalue, etb=None, tb_offset=None,
607 context=5):
631 context=5):
608 """Return a color formatted string with the traceback info.
632 """Return a color formatted string with the traceback info.
609
633
610 Parameters
634 Parameters
611 ----------
635 ----------
612 etype : exception type
636 etype : exception type
613 Type of the exception raised.
637 Type of the exception raised.
614
638
615 value : object
639 evalue : object
616 Data stored in the exception
640 Data stored in the exception
617
641
618 elist : list
642 etb : object
619 List of frames, see class docstring for details.
643 If list: List of frames, see class docstring for details.
644 If Traceback: Traceback of the exception.
620
645
621 tb_offset : int, optional
646 tb_offset : int, optional
622 Number of frames in the traceback to skip. If not given, the
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 context : int, optional
650 context : int, optional
626 Number of lines of context information to print.
651 Number of lines of context information to print.
627
652
628 Returns
653 Returns
629 -------
654 -------
630 String with formatted exception.
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 tb_offset = self.tb_offset if tb_offset is None else tb_offset
670 tb_offset = self.tb_offset if tb_offset is None else tb_offset
633 Colors = self.Colors
671 Colors = self.Colors
634 out_list = []
672 out_list = []
635 if elist:
673 if elist:
636
674
637 if tb_offset and len(elist) > tb_offset:
675 if tb_offset and len(elist) > tb_offset:
638 elist = elist[tb_offset:]
676 elist = elist[tb_offset:]
639
677
640 out_list.append('Traceback %s(most recent call last)%s:' %
678 out_list.append('Traceback %s(most recent call last)%s:' %
641 (Colors.normalEm, Colors.Normal) + '\n')
679 (Colors.normalEm, Colors.Normal) + '\n')
642 out_list.extend(self._format_list(elist))
680 out_list.extend(self._format_list(elist))
643 # The exception info should be a single entry in the list.
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 out_list.append(lines)
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 return out_list
701 return out_list
648
702
649 def _format_list(self, extracted_list):
703 def _format_list(self, extracted_list):
650 """Format a list of traceback entry tuples for printing.
704 """Format a list of traceback entry tuples for printing.
651
705
652 Given a list of tuples as returned by extract_tb() or
706 Given a list of tuples as returned by extract_tb() or
653 extract_stack(), return a list of strings ready for printing.
707 extract_stack(), return a list of strings ready for printing.
654 Each string in the resulting list corresponds to the item with the
708 Each string in the resulting list corresponds to the item with the
655 same index in the argument list. Each string ends in a newline;
709 same index in the argument list. Each string ends in a newline;
656 the strings may contain internal newlines as well, for those items
710 the strings may contain internal newlines as well, for those items
657 whose source text line is not None.
711 whose source text line is not None.
658
712
659 Lifted almost verbatim from traceback.py
713 Lifted almost verbatim from traceback.py
660 """
714 """
661
715
662 Colors = self.Colors
716 Colors = self.Colors
663 list = []
717 list = []
664 for filename, lineno, name, line in extracted_list[:-1]:
718 for filename, lineno, name, line in extracted_list[:-1]:
665 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
719 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
666 (Colors.filename, filename, Colors.Normal,
720 (Colors.filename, filename, Colors.Normal,
667 Colors.lineno, lineno, Colors.Normal,
721 Colors.lineno, lineno, Colors.Normal,
668 Colors.name, name, Colors.Normal)
722 Colors.name, name, Colors.Normal)
669 if line:
723 if line:
670 item += ' %s\n' % line.strip()
724 item += ' %s\n' % line.strip()
671 list.append(item)
725 list.append(item)
672 # Emphasize the last entry
726 # Emphasize the last entry
673 filename, lineno, name, line = extracted_list[-1]
727 filename, lineno, name, line = extracted_list[-1]
674 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
728 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
675 (Colors.normalEm,
729 (Colors.normalEm,
676 Colors.filenameEm, filename, Colors.normalEm,
730 Colors.filenameEm, filename, Colors.normalEm,
677 Colors.linenoEm, lineno, Colors.normalEm,
731 Colors.linenoEm, lineno, Colors.normalEm,
678 Colors.nameEm, name, Colors.normalEm,
732 Colors.nameEm, name, Colors.normalEm,
679 Colors.Normal)
733 Colors.Normal)
680 if line:
734 if line:
681 item += '%s %s%s\n' % (Colors.line, line.strip(),
735 item += '%s %s%s\n' % (Colors.line, line.strip(),
682 Colors.Normal)
736 Colors.Normal)
683 list.append(item)
737 list.append(item)
684 return list
738 return list
685
739
686 def _format_exception_only(self, etype, value):
740 def _format_exception_only(self, etype, value):
687 """Format the exception part of a traceback.
741 """Format the exception part of a traceback.
688
742
689 The arguments are the exception type and value such as given by
743 The arguments are the exception type and value such as given by
690 sys.exc_info()[:2]. The return value is a list of strings, each ending
744 sys.exc_info()[:2]. The return value is a list of strings, each ending
691 in a newline. Normally, the list contains a single string; however,
745 in a newline. Normally, the list contains a single string; however,
692 for SyntaxError exceptions, it contains several lines that (when
746 for SyntaxError exceptions, it contains several lines that (when
693 printed) display detailed information about where the syntax error
747 printed) display detailed information about where the syntax error
694 occurred. The message indicating which exception occurred is the
748 occurred. The message indicating which exception occurred is the
695 always last string in the list.
749 always last string in the list.
696
750
697 Also lifted nearly verbatim from traceback.py
751 Also lifted nearly verbatim from traceback.py
698 """
752 """
699 have_filedata = False
753 have_filedata = False
700 Colors = self.Colors
754 Colors = self.Colors
701 list = []
755 list = []
702 stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal)
756 stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal)
703 if value is None:
757 if value is None:
704 # Not sure if this can still happen in Python 2.6 and above
758 # Not sure if this can still happen in Python 2.6 and above
705 list.append(stype + '\n')
759 list.append(stype + '\n')
706 else:
760 else:
707 if issubclass(etype, SyntaxError):
761 if issubclass(etype, SyntaxError):
708 have_filedata = True
762 have_filedata = True
709 if not value.filename: value.filename = "<string>"
763 if not value.filename: value.filename = "<string>"
710 if value.lineno:
764 if value.lineno:
711 lineno = value.lineno
765 lineno = value.lineno
712 textline = linecache.getline(value.filename, value.lineno)
766 textline = linecache.getline(value.filename, value.lineno)
713 else:
767 else:
714 lineno = 'unknown'
768 lineno = 'unknown'
715 textline = ''
769 textline = ''
716 list.append('%s File %s"%s"%s, line %s%s%s\n' % \
770 list.append('%s File %s"%s"%s, line %s%s%s\n' % \
717 (Colors.normalEm,
771 (Colors.normalEm,
718 Colors.filenameEm, py3compat.cast_unicode(value.filename), Colors.normalEm,
772 Colors.filenameEm, py3compat.cast_unicode(value.filename), Colors.normalEm,
719 Colors.linenoEm, lineno, Colors.Normal ))
773 Colors.linenoEm, lineno, Colors.Normal ))
720 if textline == '':
774 if textline == '':
721 textline = py3compat.cast_unicode(value.text, "utf-8")
775 textline = py3compat.cast_unicode(value.text, "utf-8")
722
776
723 if textline is not None:
777 if textline is not None:
724 i = 0
778 i = 0
725 while i < len(textline) and textline[i].isspace():
779 while i < len(textline) and textline[i].isspace():
726 i += 1
780 i += 1
727 list.append('%s %s%s\n' % (Colors.line,
781 list.append('%s %s%s\n' % (Colors.line,
728 textline.strip(),
782 textline.strip(),
729 Colors.Normal))
783 Colors.Normal))
730 if value.offset is not None:
784 if value.offset is not None:
731 s = ' '
785 s = ' '
732 for c in textline[i:value.offset - 1]:
786 for c in textline[i:value.offset - 1]:
733 if c.isspace():
787 if c.isspace():
734 s += c
788 s += c
735 else:
789 else:
736 s += ' '
790 s += ' '
737 list.append('%s%s^%s\n' % (Colors.caret, s,
791 list.append('%s%s^%s\n' % (Colors.caret, s,
738 Colors.Normal))
792 Colors.Normal))
739
793
740 try:
794 try:
741 s = value.msg
795 s = value.msg
742 except Exception:
796 except Exception:
743 s = self._some_str(value)
797 s = self._some_str(value)
744 if s:
798 if s:
745 list.append('%s%s:%s %s\n' % (stype, Colors.excName,
799 list.append('%s%s:%s %s\n' % (stype, Colors.excName,
746 Colors.Normal, s))
800 Colors.Normal, s))
747 else:
801 else:
748 list.append('%s\n' % stype)
802 list.append('%s\n' % stype)
749
803
750 # sync with user hooks
804 # sync with user hooks
751 if have_filedata:
805 if have_filedata:
752 ipinst = get_ipython()
806 ipinst = get_ipython()
753 if ipinst is not None:
807 if ipinst is not None:
754 ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
808 ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
755
809
756 return list
810 return list
757
811
758 def get_exception_only(self, etype, value):
812 def get_exception_only(self, etype, value):
759 """Only print the exception type and message, without a traceback.
813 """Only print the exception type and message, without a traceback.
760
814
761 Parameters
815 Parameters
762 ----------
816 ----------
763 etype : exception type
817 etype : exception type
764 value : exception value
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 def show_exception_only(self, etype, evalue):
822 def show_exception_only(self, etype, evalue):
769 """Only print the exception type and message, without a traceback.
823 """Only print the exception type and message, without a traceback.
770
824
771 Parameters
825 Parameters
772 ----------
826 ----------
773 etype : exception type
827 etype : exception type
774 value : exception value
828 value : exception value
775 """
829 """
776 # This method needs to use __call__ from *this* class, not the one from
830 # This method needs to use __call__ from *this* class, not the one from
777 # a subclass whose signature or behavior may be different
831 # a subclass whose signature or behavior may be different
778 ostream = self.ostream
832 ostream = self.ostream
779 ostream.flush()
833 ostream.flush()
780 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
834 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
781 ostream.flush()
835 ostream.flush()
782
836
783 def _some_str(self, value):
837 def _some_str(self, value):
784 # Lifted from traceback.py
838 # Lifted from traceback.py
785 try:
839 try:
786 return py3compat.cast_unicode(str(value))
840 return py3compat.cast_unicode(str(value))
787 except:
841 except:
788 return u'<unprintable %s object>' % type(value).__name__
842 return u'<unprintable %s object>' % type(value).__name__
789
843
790
844
791 #----------------------------------------------------------------------------
845 #----------------------------------------------------------------------------
792 class VerboseTB(TBTools):
846 class VerboseTB(TBTools):
793 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
847 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
794 of HTML. Requires inspect and pydoc. Crazy, man.
848 of HTML. Requires inspect and pydoc. Crazy, man.
795
849
796 Modified version which optionally strips the topmost entries from the
850 Modified version which optionally strips the topmost entries from the
797 traceback, to be used with alternate interpreters (because their own code
851 traceback, to be used with alternate interpreters (because their own code
798 would appear in the traceback)."""
852 would appear in the traceback)."""
799
853
800 def __init__(self, color_scheme='Linux', call_pdb=False, ostream=None,
854 def __init__(self, color_scheme='Linux', call_pdb=False, ostream=None,
801 tb_offset=0, long_header=False, include_vars=True,
855 tb_offset=0, long_header=False, include_vars=True,
802 check_cache=None, debugger_cls = None,
856 check_cache=None, debugger_cls = None,
803 parent=None, config=None):
857 parent=None, config=None):
804 """Specify traceback offset, headers and color scheme.
858 """Specify traceback offset, headers and color scheme.
805
859
806 Define how many frames to drop from the tracebacks. Calling it with
860 Define how many frames to drop from the tracebacks. Calling it with
807 tb_offset=1 allows use of this handler in interpreters which will have
861 tb_offset=1 allows use of this handler in interpreters which will have
808 their own code at the top of the traceback (VerboseTB will first
862 their own code at the top of the traceback (VerboseTB will first
809 remove that frame before printing the traceback info)."""
863 remove that frame before printing the traceback info)."""
810 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
864 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
811 ostream=ostream, parent=parent, config=config)
865 ostream=ostream, parent=parent, config=config)
812 self.tb_offset = tb_offset
866 self.tb_offset = tb_offset
813 self.long_header = long_header
867 self.long_header = long_header
814 self.include_vars = include_vars
868 self.include_vars = include_vars
815 # By default we use linecache.checkcache, but the user can provide a
869 # By default we use linecache.checkcache, but the user can provide a
816 # different check_cache implementation. This is used by the IPython
870 # different check_cache implementation. This is used by the IPython
817 # kernel to provide tracebacks for interactive code that is cached,
871 # kernel to provide tracebacks for interactive code that is cached,
818 # by a compiler instance that flushes the linecache but preserves its
872 # by a compiler instance that flushes the linecache but preserves its
819 # own code cache.
873 # own code cache.
820 if check_cache is None:
874 if check_cache is None:
821 check_cache = linecache.checkcache
875 check_cache = linecache.checkcache
822 self.check_cache = check_cache
876 self.check_cache = check_cache
823
877
824 self.debugger_cls = debugger_cls or debugger.Pdb
878 self.debugger_cls = debugger_cls or debugger.Pdb
825
879
826 def format_records(self, records, last_unique, recursion_repeat):
880 def format_records(self, records, last_unique, recursion_repeat):
827 """Format the stack frames of the traceback"""
881 """Format the stack frames of the traceback"""
828 frames = []
882 frames = []
829 for r in records[:last_unique+recursion_repeat+1]:
883 for r in records[:last_unique+recursion_repeat+1]:
830 #print '*** record:',file,lnum,func,lines,index # dbg
884 #print '*** record:',file,lnum,func,lines,index # dbg
831 frames.append(self.format_record(*r))
885 frames.append(self.format_record(*r))
832
886
833 if recursion_repeat:
887 if recursion_repeat:
834 frames.append('... last %d frames repeated, from the frame below ...\n' % recursion_repeat)
888 frames.append('... last %d frames repeated, from the frame below ...\n' % recursion_repeat)
835 frames.append(self.format_record(*records[last_unique+recursion_repeat+1]))
889 frames.append(self.format_record(*records[last_unique+recursion_repeat+1]))
836
890
837 return frames
891 return frames
838
892
839 def format_record(self, frame, file, lnum, func, lines, index):
893 def format_record(self, frame, file, lnum, func, lines, index):
840 """Format a single stack frame"""
894 """Format a single stack frame"""
841 Colors = self.Colors # just a shorthand + quicker name lookup
895 Colors = self.Colors # just a shorthand + quicker name lookup
842 ColorsNormal = Colors.Normal # used a lot
896 ColorsNormal = Colors.Normal # used a lot
843 col_scheme = self.color_scheme_table.active_scheme_name
897 col_scheme = self.color_scheme_table.active_scheme_name
844 indent = ' ' * INDENT_SIZE
898 indent = ' ' * INDENT_SIZE
845 em_normal = '%s\n%s%s' % (Colors.valEm, indent, ColorsNormal)
899 em_normal = '%s\n%s%s' % (Colors.valEm, indent, ColorsNormal)
846 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
900 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
847 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
901 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
848 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
902 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
849 ColorsNormal)
903 ColorsNormal)
850 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
904 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
851 (Colors.vName, Colors.valEm, ColorsNormal)
905 (Colors.vName, Colors.valEm, ColorsNormal)
852 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
906 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
853 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
907 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
854 Colors.vName, ColorsNormal)
908 Colors.vName, ColorsNormal)
855 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
909 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
856
910
857 if not file:
911 if not file:
858 file = '?'
912 file = '?'
859 elif file.startswith(str("<")) and file.endswith(str(">")):
913 elif file.startswith(str("<")) and file.endswith(str(">")):
860 # Not a real filename, no problem...
914 # Not a real filename, no problem...
861 pass
915 pass
862 elif not os.path.isabs(file):
916 elif not os.path.isabs(file):
863 # Try to make the filename absolute by trying all
917 # Try to make the filename absolute by trying all
864 # sys.path entries (which is also what linecache does)
918 # sys.path entries (which is also what linecache does)
865 for dirname in sys.path:
919 for dirname in sys.path:
866 try:
920 try:
867 fullname = os.path.join(dirname, file)
921 fullname = os.path.join(dirname, file)
868 if os.path.isfile(fullname):
922 if os.path.isfile(fullname):
869 file = os.path.abspath(fullname)
923 file = os.path.abspath(fullname)
870 break
924 break
871 except Exception:
925 except Exception:
872 # Just in case that sys.path contains very
926 # Just in case that sys.path contains very
873 # strange entries...
927 # strange entries...
874 pass
928 pass
875
929
876 file = py3compat.cast_unicode(file, util_path.fs_encoding)
930 file = py3compat.cast_unicode(file, util_path.fs_encoding)
877 link = tpl_link % util_path.compress_user(file)
931 link = tpl_link % util_path.compress_user(file)
878 args, varargs, varkw, locals_ = inspect.getargvalues(frame)
932 args, varargs, varkw, locals_ = inspect.getargvalues(frame)
879
933
880 if func == '?':
934 if func == '?':
881 call = ''
935 call = ''
882 elif func == '<module>':
936 elif func == '<module>':
883 call = tpl_call % (func, '')
937 call = tpl_call % (func, '')
884 else:
938 else:
885 # Decide whether to include variable details or not
939 # Decide whether to include variable details or not
886 var_repr = eqrepr if self.include_vars else nullrepr
940 var_repr = eqrepr if self.include_vars else nullrepr
887 try:
941 try:
888 call = tpl_call % (func, inspect.formatargvalues(args,
942 call = tpl_call % (func, inspect.formatargvalues(args,
889 varargs, varkw,
943 varargs, varkw,
890 locals_, formatvalue=var_repr))
944 locals_, formatvalue=var_repr))
891 except KeyError:
945 except KeyError:
892 # This happens in situations like errors inside generator
946 # This happens in situations like errors inside generator
893 # expressions, where local variables are listed in the
947 # expressions, where local variables are listed in the
894 # line, but can't be extracted from the frame. I'm not
948 # line, but can't be extracted from the frame. I'm not
895 # 100% sure this isn't actually a bug in inspect itself,
949 # 100% sure this isn't actually a bug in inspect itself,
896 # but since there's no info for us to compute with, the
950 # but since there's no info for us to compute with, the
897 # best we can do is report the failure and move on. Here
951 # best we can do is report the failure and move on. Here
898 # we must *not* call any traceback construction again,
952 # we must *not* call any traceback construction again,
899 # because that would mess up use of %debug later on. So we
953 # because that would mess up use of %debug later on. So we
900 # simply report the failure and move on. The only
954 # simply report the failure and move on. The only
901 # limitation will be that this frame won't have locals
955 # limitation will be that this frame won't have locals
902 # listed in the call signature. Quite subtle problem...
956 # listed in the call signature. Quite subtle problem...
903 # I can't think of a good way to validate this in a unit
957 # I can't think of a good way to validate this in a unit
904 # test, but running a script consisting of:
958 # test, but running a script consisting of:
905 # dict( (k,v.strip()) for (k,v) in range(10) )
959 # dict( (k,v.strip()) for (k,v) in range(10) )
906 # will illustrate the error, if this exception catch is
960 # will illustrate the error, if this exception catch is
907 # disabled.
961 # disabled.
908 call = tpl_call_fail % func
962 call = tpl_call_fail % func
909
963
910 # Don't attempt to tokenize binary files.
964 # Don't attempt to tokenize binary files.
911 if file.endswith(('.so', '.pyd', '.dll')):
965 if file.endswith(('.so', '.pyd', '.dll')):
912 return '%s %s\n' % (link, call)
966 return '%s %s\n' % (link, call)
913
967
914 elif file.endswith(('.pyc', '.pyo')):
968 elif file.endswith(('.pyc', '.pyo')):
915 # Look up the corresponding source file.
969 # Look up the corresponding source file.
916 try:
970 try:
917 file = source_from_cache(file)
971 file = source_from_cache(file)
918 except ValueError:
972 except ValueError:
919 # Failed to get the source file for some reason
973 # Failed to get the source file for some reason
920 # E.g. https://github.com/ipython/ipython/issues/9486
974 # E.g. https://github.com/ipython/ipython/issues/9486
921 return '%s %s\n' % (link, call)
975 return '%s %s\n' % (link, call)
922
976
923 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
977 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
924 line = getline(file, lnum[0])
978 line = getline(file, lnum[0])
925 lnum[0] += 1
979 lnum[0] += 1
926 return line
980 return line
927
981
928 # Build the list of names on this line of code where the exception
982 # Build the list of names on this line of code where the exception
929 # occurred.
983 # occurred.
930 try:
984 try:
931 names = []
985 names = []
932 name_cont = False
986 name_cont = False
933
987
934 for token_type, token, start, end, line in generate_tokens(linereader):
988 for token_type, token, start, end, line in generate_tokens(linereader):
935 # build composite names
989 # build composite names
936 if token_type == tokenize.NAME and token not in keyword.kwlist:
990 if token_type == tokenize.NAME and token not in keyword.kwlist:
937 if name_cont:
991 if name_cont:
938 # Continuation of a dotted name
992 # Continuation of a dotted name
939 try:
993 try:
940 names[-1].append(token)
994 names[-1].append(token)
941 except IndexError:
995 except IndexError:
942 names.append([token])
996 names.append([token])
943 name_cont = False
997 name_cont = False
944 else:
998 else:
945 # Regular new names. We append everything, the caller
999 # Regular new names. We append everything, the caller
946 # will be responsible for pruning the list later. It's
1000 # will be responsible for pruning the list later. It's
947 # very tricky to try to prune as we go, b/c composite
1001 # very tricky to try to prune as we go, b/c composite
948 # names can fool us. The pruning at the end is easy
1002 # names can fool us. The pruning at the end is easy
949 # to do (or the caller can print a list with repeated
1003 # to do (or the caller can print a list with repeated
950 # names if so desired.
1004 # names if so desired.
951 names.append([token])
1005 names.append([token])
952 elif token == '.':
1006 elif token == '.':
953 name_cont = True
1007 name_cont = True
954 elif token_type == tokenize.NEWLINE:
1008 elif token_type == tokenize.NEWLINE:
955 break
1009 break
956
1010
957 except (IndexError, UnicodeDecodeError, SyntaxError):
1011 except (IndexError, UnicodeDecodeError, SyntaxError):
958 # signals exit of tokenizer
1012 # signals exit of tokenizer
959 # SyntaxError can occur if the file is not actually Python
1013 # SyntaxError can occur if the file is not actually Python
960 # - see gh-6300
1014 # - see gh-6300
961 pass
1015 pass
962 except tokenize.TokenError as msg:
1016 except tokenize.TokenError as msg:
963 # Tokenizing may fail for various reasons, many of which are
1017 # Tokenizing may fail for various reasons, many of which are
964 # harmless. (A good example is when the line in question is the
1018 # harmless. (A good example is when the line in question is the
965 # close of a triple-quoted string, cf gh-6864). We don't want to
1019 # close of a triple-quoted string, cf gh-6864). We don't want to
966 # show this to users, but want make it available for debugging
1020 # show this to users, but want make it available for debugging
967 # purposes.
1021 # purposes.
968 _m = ("An unexpected error occurred while tokenizing input\n"
1022 _m = ("An unexpected error occurred while tokenizing input\n"
969 "The following traceback may be corrupted or invalid\n"
1023 "The following traceback may be corrupted or invalid\n"
970 "The error message is: %s\n" % msg)
1024 "The error message is: %s\n" % msg)
971 debug(_m)
1025 debug(_m)
972
1026
973 # Join composite names (e.g. "dict.fromkeys")
1027 # Join composite names (e.g. "dict.fromkeys")
974 names = ['.'.join(n) for n in names]
1028 names = ['.'.join(n) for n in names]
975 # prune names list of duplicates, but keep the right order
1029 # prune names list of duplicates, but keep the right order
976 unique_names = uniq_stable(names)
1030 unique_names = uniq_stable(names)
977
1031
978 # Start loop over vars
1032 # Start loop over vars
979 lvals = ''
1033 lvals = ''
980 lvals_list = []
1034 lvals_list = []
981 if self.include_vars:
1035 if self.include_vars:
982 for name_full in unique_names:
1036 for name_full in unique_names:
983 name_base = name_full.split('.', 1)[0]
1037 name_base = name_full.split('.', 1)[0]
984 if name_base in frame.f_code.co_varnames:
1038 if name_base in frame.f_code.co_varnames:
985 if name_base in locals_:
1039 if name_base in locals_:
986 try:
1040 try:
987 value = repr(eval(name_full, locals_))
1041 value = repr(eval(name_full, locals_))
988 except:
1042 except:
989 value = undefined
1043 value = undefined
990 else:
1044 else:
991 value = undefined
1045 value = undefined
992 name = tpl_local_var % name_full
1046 name = tpl_local_var % name_full
993 else:
1047 else:
994 if name_base in frame.f_globals:
1048 if name_base in frame.f_globals:
995 try:
1049 try:
996 value = repr(eval(name_full, frame.f_globals))
1050 value = repr(eval(name_full, frame.f_globals))
997 except:
1051 except:
998 value = undefined
1052 value = undefined
999 else:
1053 else:
1000 value = undefined
1054 value = undefined
1001 name = tpl_global_var % name_full
1055 name = tpl_global_var % name_full
1002 lvals_list.append(tpl_name_val % (name, value))
1056 lvals_list.append(tpl_name_val % (name, value))
1003 if lvals_list:
1057 if lvals_list:
1004 lvals = '%s%s' % (indent, em_normal.join(lvals_list))
1058 lvals = '%s%s' % (indent, em_normal.join(lvals_list))
1005
1059
1006 level = '%s %s\n' % (link, call)
1060 level = '%s %s\n' % (link, call)
1007
1061
1008 if index is None:
1062 if index is None:
1009 return level
1063 return level
1010 else:
1064 else:
1011 _line_format = PyColorize.Parser(style=col_scheme, parent=self).format2
1065 _line_format = PyColorize.Parser(style=col_scheme, parent=self).format2
1012 return '%s%s' % (level, ''.join(
1066 return '%s%s' % (level, ''.join(
1013 _format_traceback_lines(lnum, index, lines, Colors, lvals,
1067 _format_traceback_lines(lnum, index, lines, Colors, lvals,
1014 _line_format)))
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 def prepare_header(self, etype, long_version=False):
1070 def prepare_header(self, etype, long_version=False):
1027 colors = self.Colors # just a shorthand + quicker name lookup
1071 colors = self.Colors # just a shorthand + quicker name lookup
1028 colorsnormal = colors.Normal # used a lot
1072 colorsnormal = colors.Normal # used a lot
1029 exc = '%s%s%s' % (colors.excName, etype, colorsnormal)
1073 exc = '%s%s%s' % (colors.excName, etype, colorsnormal)
1030 width = min(75, get_terminal_size()[0])
1074 width = min(75, get_terminal_size()[0])
1031 if long_version:
1075 if long_version:
1032 # Header with the exception type, python version, and date
1076 # Header with the exception type, python version, and date
1033 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
1077 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
1034 date = time.ctime(time.time())
1078 date = time.ctime(time.time())
1035
1079
1036 head = '%s%s%s\n%s%s%s\n%s' % (colors.topline, '-' * width, colorsnormal,
1080 head = '%s%s%s\n%s%s%s\n%s' % (colors.topline, '-' * width, colorsnormal,
1037 exc, ' ' * (width - len(str(etype)) - len(pyver)),
1081 exc, ' ' * (width - len(str(etype)) - len(pyver)),
1038 pyver, date.rjust(width) )
1082 pyver, date.rjust(width) )
1039 head += "\nA problem occurred executing Python code. Here is the sequence of function" \
1083 head += "\nA problem occurred executing Python code. Here is the sequence of function" \
1040 "\ncalls leading up to the error, with the most recent (innermost) call last."
1084 "\ncalls leading up to the error, with the most recent (innermost) call last."
1041 else:
1085 else:
1042 # Simplified header
1086 # Simplified header
1043 head = '%s%s' % (exc, 'Traceback (most recent call last)'. \
1087 head = '%s%s' % (exc, 'Traceback (most recent call last)'. \
1044 rjust(width - len(str(etype))) )
1088 rjust(width - len(str(etype))) )
1045
1089
1046 return head
1090 return head
1047
1091
1048 def format_exception(self, etype, evalue):
1092 def format_exception(self, etype, evalue):
1049 colors = self.Colors # just a shorthand + quicker name lookup
1093 colors = self.Colors # just a shorthand + quicker name lookup
1050 colorsnormal = colors.Normal # used a lot
1094 colorsnormal = colors.Normal # used a lot
1051 # Get (safely) a string form of the exception info
1095 # Get (safely) a string form of the exception info
1052 try:
1096 try:
1053 etype_str, evalue_str = map(str, (etype, evalue))
1097 etype_str, evalue_str = map(str, (etype, evalue))
1054 except:
1098 except:
1055 # User exception is improperly defined.
1099 # User exception is improperly defined.
1056 etype, evalue = str, sys.exc_info()[:2]
1100 etype, evalue = str, sys.exc_info()[:2]
1057 etype_str, evalue_str = map(str, (etype, evalue))
1101 etype_str, evalue_str = map(str, (etype, evalue))
1058 # ... and format it
1102 # ... and format it
1059 return ['%s%s%s: %s' % (colors.excName, etype_str,
1103 return ['%s%s%s: %s' % (colors.excName, etype_str,
1060 colorsnormal, py3compat.cast_unicode(evalue_str))]
1104 colorsnormal, py3compat.cast_unicode(evalue_str))]
1061
1105
1062 def format_exception_as_a_whole(self, etype, evalue, etb, number_of_lines_of_context, tb_offset):
1106 def format_exception_as_a_whole(self, etype, evalue, etb, number_of_lines_of_context, tb_offset):
1063 """Formats the header, traceback and exception message for a single exception.
1107 """Formats the header, traceback and exception message for a single exception.
1064
1108
1065 This may be called multiple times by Python 3 exception chaining
1109 This may be called multiple times by Python 3 exception chaining
1066 (PEP 3134).
1110 (PEP 3134).
1067 """
1111 """
1068 # some locals
1112 # some locals
1069 orig_etype = etype
1113 orig_etype = etype
1070 try:
1114 try:
1071 etype = etype.__name__
1115 etype = etype.__name__
1072 except AttributeError:
1116 except AttributeError:
1073 pass
1117 pass
1074
1118
1075 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1119 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1076 head = self.prepare_header(etype, self.long_header)
1120 head = self.prepare_header(etype, self.long_header)
1077 records = self.get_records(etb, number_of_lines_of_context, tb_offset)
1121 records = self.get_records(etb, number_of_lines_of_context, tb_offset)
1078
1122
1079 if records is None:
1123 if records is None:
1080 return ""
1124 return ""
1081
1125
1082 last_unique, recursion_repeat = find_recursion(orig_etype, evalue, records)
1126 last_unique, recursion_repeat = find_recursion(orig_etype, evalue, records)
1083
1127
1084 frames = self.format_records(records, last_unique, recursion_repeat)
1128 frames = self.format_records(records, last_unique, recursion_repeat)
1085
1129
1086 formatted_exception = self.format_exception(etype, evalue)
1130 formatted_exception = self.format_exception(etype, evalue)
1087 if records:
1131 if records:
1088 filepath, lnum = records[-1][1:3]
1132 filepath, lnum = records[-1][1:3]
1089 filepath = os.path.abspath(filepath)
1133 filepath = os.path.abspath(filepath)
1090 ipinst = get_ipython()
1134 ipinst = get_ipython()
1091 if ipinst is not None:
1135 if ipinst is not None:
1092 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
1136 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
1093
1137
1094 return [[head] + frames + [''.join(formatted_exception[0])]]
1138 return [[head] + frames + [''.join(formatted_exception[0])]]
1095
1139
1096 def get_records(self, etb, number_of_lines_of_context, tb_offset):
1140 def get_records(self, etb, number_of_lines_of_context, tb_offset):
1097 try:
1141 try:
1098 # Try the default getinnerframes and Alex's: Alex's fixes some
1142 # Try the default getinnerframes and Alex's: Alex's fixes some
1099 # problems, but it generates empty tracebacks for console errors
1143 # problems, but it generates empty tracebacks for console errors
1100 # (5 blanks lines) where none should be returned.
1144 # (5 blanks lines) where none should be returned.
1101 return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset)
1145 return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset)
1102 except UnicodeDecodeError:
1146 except UnicodeDecodeError:
1103 # This can occur if a file's encoding magic comment is wrong.
1147 # This can occur if a file's encoding magic comment is wrong.
1104 # I can't see a way to recover without duplicating a bunch of code
1148 # I can't see a way to recover without duplicating a bunch of code
1105 # from the stdlib traceback module. --TK
1149 # from the stdlib traceback module. --TK
1106 error('\nUnicodeDecodeError while processing traceback.\n')
1150 error('\nUnicodeDecodeError while processing traceback.\n')
1107 return None
1151 return None
1108 except:
1152 except:
1109 # FIXME: I've been getting many crash reports from python 2.3
1153 # FIXME: I've been getting many crash reports from python 2.3
1110 # users, traceable to inspect.py. If I can find a small test-case
1154 # users, traceable to inspect.py. If I can find a small test-case
1111 # to reproduce this, I should either write a better workaround or
1155 # to reproduce this, I should either write a better workaround or
1112 # file a bug report against inspect (if that's the real problem).
1156 # file a bug report against inspect (if that's the real problem).
1113 # So far, I haven't been able to find an isolated example to
1157 # So far, I haven't been able to find an isolated example to
1114 # reproduce the problem.
1158 # reproduce the problem.
1115 inspect_error()
1159 inspect_error()
1116 traceback.print_exc(file=self.ostream)
1160 traceback.print_exc(file=self.ostream)
1117 info('\nUnfortunately, your original traceback can not be constructed.\n')
1161 info('\nUnfortunately, your original traceback can not be constructed.\n')
1118 return None
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 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
1164 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
1135 number_of_lines_of_context=5):
1165 number_of_lines_of_context=5):
1136 """Return a nice text document describing the traceback."""
1166 """Return a nice text document describing the traceback."""
1137
1167
1138 formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
1168 formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
1139 tb_offset)
1169 tb_offset)
1140
1170
1141 colors = self.Colors # just a shorthand + quicker name lookup
1171 colors = self.Colors # just a shorthand + quicker name lookup
1142 colorsnormal = colors.Normal # used a lot
1172 colorsnormal = colors.Normal # used a lot
1143 head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal)
1173 head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal)
1144 structured_traceback_parts = [head]
1174 structured_traceback_parts = [head]
1145 chained_exceptions_tb_offset = 0
1175 chained_exceptions_tb_offset = 0
1146 lines_of_context = 3
1176 lines_of_context = 3
1147 formatted_exceptions = formatted_exception
1177 formatted_exceptions = formatted_exception
1148 exception = self.get_parts_of_chained_exception(evalue)
1178 exception = self.get_parts_of_chained_exception(evalue)
1149 if exception:
1179 if exception:
1150 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1180 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1151 etype, evalue, etb = exception
1181 etype, evalue, etb = exception
1152 else:
1182 else:
1153 evalue = None
1183 evalue = None
1154 chained_exc_ids = set()
1184 chained_exc_ids = set()
1155 while evalue:
1185 while evalue:
1156 formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context,
1186 formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context,
1157 chained_exceptions_tb_offset)
1187 chained_exceptions_tb_offset)
1158 exception = self.get_parts_of_chained_exception(evalue)
1188 exception = self.get_parts_of_chained_exception(evalue)
1159
1189
1160 if exception and not id(exception[1]) in chained_exc_ids:
1190 if exception and not id(exception[1]) in chained_exc_ids:
1161 chained_exc_ids.add(id(exception[1])) # trace exception to avoid infinite 'cause' loop
1191 chained_exc_ids.add(id(exception[1])) # trace exception to avoid infinite 'cause' loop
1162 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1192 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1163 etype, evalue, etb = exception
1193 etype, evalue, etb = exception
1164 else:
1194 else:
1165 evalue = None
1195 evalue = None
1166
1196
1167 # we want to see exceptions in a reversed order:
1197 # we want to see exceptions in a reversed order:
1168 # the first exception should be on top
1198 # the first exception should be on top
1169 for formatted_exception in reversed(formatted_exceptions):
1199 for formatted_exception in reversed(formatted_exceptions):
1170 structured_traceback_parts += formatted_exception
1200 structured_traceback_parts += formatted_exception
1171
1201
1172 return structured_traceback_parts
1202 return structured_traceback_parts
1173
1203
1174 def debugger(self, force=False):
1204 def debugger(self, force=False):
1175 """Call up the pdb debugger if desired, always clean up the tb
1205 """Call up the pdb debugger if desired, always clean up the tb
1176 reference.
1206 reference.
1177
1207
1178 Keywords:
1208 Keywords:
1179
1209
1180 - force(False): by default, this routine checks the instance call_pdb
1210 - force(False): by default, this routine checks the instance call_pdb
1181 flag and does not actually invoke the debugger if the flag is false.
1211 flag and does not actually invoke the debugger if the flag is false.
1182 The 'force' option forces the debugger to activate even if the flag
1212 The 'force' option forces the debugger to activate even if the flag
1183 is false.
1213 is false.
1184
1214
1185 If the call_pdb flag is set, the pdb interactive debugger is
1215 If the call_pdb flag is set, the pdb interactive debugger is
1186 invoked. In all cases, the self.tb reference to the current traceback
1216 invoked. In all cases, the self.tb reference to the current traceback
1187 is deleted to prevent lingering references which hamper memory
1217 is deleted to prevent lingering references which hamper memory
1188 management.
1218 management.
1189
1219
1190 Note that each call to pdb() does an 'import readline', so if your app
1220 Note that each call to pdb() does an 'import readline', so if your app
1191 requires a special setup for the readline completers, you'll have to
1221 requires a special setup for the readline completers, you'll have to
1192 fix that by hand after invoking the exception handler."""
1222 fix that by hand after invoking the exception handler."""
1193
1223
1194 if force or self.call_pdb:
1224 if force or self.call_pdb:
1195 if self.pdb is None:
1225 if self.pdb is None:
1196 self.pdb = self.debugger_cls()
1226 self.pdb = self.debugger_cls()
1197 # the system displayhook may have changed, restore the original
1227 # the system displayhook may have changed, restore the original
1198 # for pdb
1228 # for pdb
1199 display_trap = DisplayTrap(hook=sys.__displayhook__)
1229 display_trap = DisplayTrap(hook=sys.__displayhook__)
1200 with display_trap:
1230 with display_trap:
1201 self.pdb.reset()
1231 self.pdb.reset()
1202 # Find the right frame so we don't pop up inside ipython itself
1232 # Find the right frame so we don't pop up inside ipython itself
1203 if hasattr(self, 'tb') and self.tb is not None:
1233 if hasattr(self, 'tb') and self.tb is not None:
1204 etb = self.tb
1234 etb = self.tb
1205 else:
1235 else:
1206 etb = self.tb = sys.last_traceback
1236 etb = self.tb = sys.last_traceback
1207 while self.tb is not None and self.tb.tb_next is not None:
1237 while self.tb is not None and self.tb.tb_next is not None:
1208 self.tb = self.tb.tb_next
1238 self.tb = self.tb.tb_next
1209 if etb and etb.tb_next:
1239 if etb and etb.tb_next:
1210 etb = etb.tb_next
1240 etb = etb.tb_next
1211 self.pdb.botframe = etb.tb_frame
1241 self.pdb.botframe = etb.tb_frame
1212 self.pdb.interaction(None, etb)
1242 self.pdb.interaction(None, etb)
1213
1243
1214 if hasattr(self, 'tb'):
1244 if hasattr(self, 'tb'):
1215 del self.tb
1245 del self.tb
1216
1246
1217 def handler(self, info=None):
1247 def handler(self, info=None):
1218 (etype, evalue, etb) = info or sys.exc_info()
1248 (etype, evalue, etb) = info or sys.exc_info()
1219 self.tb = etb
1249 self.tb = etb
1220 ostream = self.ostream
1250 ostream = self.ostream
1221 ostream.flush()
1251 ostream.flush()
1222 ostream.write(self.text(etype, evalue, etb))
1252 ostream.write(self.text(etype, evalue, etb))
1223 ostream.write('\n')
1253 ostream.write('\n')
1224 ostream.flush()
1254 ostream.flush()
1225
1255
1226 # Changed so an instance can just be called as VerboseTB_inst() and print
1256 # Changed so an instance can just be called as VerboseTB_inst() and print
1227 # out the right info on its own.
1257 # out the right info on its own.
1228 def __call__(self, etype=None, evalue=None, etb=None):
1258 def __call__(self, etype=None, evalue=None, etb=None):
1229 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
1259 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
1230 if etb is None:
1260 if etb is None:
1231 self.handler()
1261 self.handler()
1232 else:
1262 else:
1233 self.handler((etype, evalue, etb))
1263 self.handler((etype, evalue, etb))
1234 try:
1264 try:
1235 self.debugger()
1265 self.debugger()
1236 except KeyboardInterrupt:
1266 except KeyboardInterrupt:
1237 print("\nKeyboardInterrupt")
1267 print("\nKeyboardInterrupt")
1238
1268
1239
1269
1240 #----------------------------------------------------------------------------
1270 #----------------------------------------------------------------------------
1241 class FormattedTB(VerboseTB, ListTB):
1271 class FormattedTB(VerboseTB, ListTB):
1242 """Subclass ListTB but allow calling with a traceback.
1272 """Subclass ListTB but allow calling with a traceback.
1243
1273
1244 It can thus be used as a sys.excepthook for Python > 2.1.
1274 It can thus be used as a sys.excepthook for Python > 2.1.
1245
1275
1246 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
1276 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
1247
1277
1248 Allows a tb_offset to be specified. This is useful for situations where
1278 Allows a tb_offset to be specified. This is useful for situations where
1249 one needs to remove a number of topmost frames from the traceback (such as
1279 one needs to remove a number of topmost frames from the traceback (such as
1250 occurs with python programs that themselves execute other python code,
1280 occurs with python programs that themselves execute other python code,
1251 like Python shells). """
1281 like Python shells). """
1252
1282
1253 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
1283 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
1254 ostream=None,
1284 ostream=None,
1255 tb_offset=0, long_header=False, include_vars=False,
1285 tb_offset=0, long_header=False, include_vars=False,
1256 check_cache=None, debugger_cls=None,
1286 check_cache=None, debugger_cls=None,
1257 parent=None, config=None):
1287 parent=None, config=None):
1258
1288
1259 # NEVER change the order of this list. Put new modes at the end:
1289 # NEVER change the order of this list. Put new modes at the end:
1260 self.valid_modes = ['Plain', 'Context', 'Verbose', 'Minimal']
1290 self.valid_modes = ['Plain', 'Context', 'Verbose', 'Minimal']
1261 self.verbose_modes = self.valid_modes[1:3]
1291 self.verbose_modes = self.valid_modes[1:3]
1262
1292
1263 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
1293 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
1264 ostream=ostream, tb_offset=tb_offset,
1294 ostream=ostream, tb_offset=tb_offset,
1265 long_header=long_header, include_vars=include_vars,
1295 long_header=long_header, include_vars=include_vars,
1266 check_cache=check_cache, debugger_cls=debugger_cls,
1296 check_cache=check_cache, debugger_cls=debugger_cls,
1267 parent=parent, config=config)
1297 parent=parent, config=config)
1268
1298
1269 # Different types of tracebacks are joined with different separators to
1299 # Different types of tracebacks are joined with different separators to
1270 # form a single string. They are taken from this dict
1300 # form a single string. They are taken from this dict
1271 self._join_chars = dict(Plain='', Context='\n', Verbose='\n',
1301 self._join_chars = dict(Plain='', Context='\n', Verbose='\n',
1272 Minimal='')
1302 Minimal='')
1273 # set_mode also sets the tb_join_char attribute
1303 # set_mode also sets the tb_join_char attribute
1274 self.set_mode(mode)
1304 self.set_mode(mode)
1275
1305
1276 def _extract_tb(self, tb):
1306 def _extract_tb(self, tb):
1277 if tb:
1307 if tb:
1278 return traceback.extract_tb(tb)
1308 return traceback.extract_tb(tb)
1279 else:
1309 else:
1280 return None
1310 return None
1281
1311
1282 def structured_traceback(self, etype, value, tb, tb_offset=None, number_of_lines_of_context=5):
1312 def structured_traceback(self, etype, value, tb, tb_offset=None, number_of_lines_of_context=5):
1283 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1313 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1284 mode = self.mode
1314 mode = self.mode
1285 if mode in self.verbose_modes:
1315 if mode in self.verbose_modes:
1286 # Verbose modes need a full traceback
1316 # Verbose modes need a full traceback
1287 return VerboseTB.structured_traceback(
1317 return VerboseTB.structured_traceback(
1288 self, etype, value, tb, tb_offset, number_of_lines_of_context
1318 self, etype, value, tb, tb_offset, number_of_lines_of_context
1289 )
1319 )
1290 elif mode == 'Minimal':
1320 elif mode == 'Minimal':
1291 return ListTB.get_exception_only(self, etype, value)
1321 return ListTB.get_exception_only(self, etype, value)
1292 else:
1322 else:
1293 # We must check the source cache because otherwise we can print
1323 # We must check the source cache because otherwise we can print
1294 # out-of-date source code.
1324 # out-of-date source code.
1295 self.check_cache()
1325 self.check_cache()
1296 # Now we can extract and format the exception
1326 # Now we can extract and format the exception
1297 elist = self._extract_tb(tb)
1298 return ListTB.structured_traceback(
1327 return ListTB.structured_traceback(
1299 self, etype, value, elist, tb_offset, number_of_lines_of_context
1328 self, etype, value, tb, tb_offset, number_of_lines_of_context
1300 )
1329 )
1301
1330
1302 def stb2text(self, stb):
1331 def stb2text(self, stb):
1303 """Convert a structured traceback (a list) to a string."""
1332 """Convert a structured traceback (a list) to a string."""
1304 return self.tb_join_char.join(stb)
1333 return self.tb_join_char.join(stb)
1305
1334
1306
1335
1307 def set_mode(self, mode=None):
1336 def set_mode(self, mode=None):
1308 """Switch to the desired mode.
1337 """Switch to the desired mode.
1309
1338
1310 If mode is not specified, cycles through the available modes."""
1339 If mode is not specified, cycles through the available modes."""
1311
1340
1312 if not mode:
1341 if not mode:
1313 new_idx = (self.valid_modes.index(self.mode) + 1 ) % \
1342 new_idx = (self.valid_modes.index(self.mode) + 1 ) % \
1314 len(self.valid_modes)
1343 len(self.valid_modes)
1315 self.mode = self.valid_modes[new_idx]
1344 self.mode = self.valid_modes[new_idx]
1316 elif mode not in self.valid_modes:
1345 elif mode not in self.valid_modes:
1317 raise ValueError('Unrecognized mode in FormattedTB: <' + mode + '>\n'
1346 raise ValueError('Unrecognized mode in FormattedTB: <' + mode + '>\n'
1318 'Valid modes: ' + str(self.valid_modes))
1347 'Valid modes: ' + str(self.valid_modes))
1319 else:
1348 else:
1320 self.mode = mode
1349 self.mode = mode
1321 # include variable details only in 'Verbose' mode
1350 # include variable details only in 'Verbose' mode
1322 self.include_vars = (self.mode == self.valid_modes[2])
1351 self.include_vars = (self.mode == self.valid_modes[2])
1323 # Set the join character for generating text tracebacks
1352 # Set the join character for generating text tracebacks
1324 self.tb_join_char = self._join_chars[self.mode]
1353 self.tb_join_char = self._join_chars[self.mode]
1325
1354
1326 # some convenient shortcuts
1355 # some convenient shortcuts
1327 def plain(self):
1356 def plain(self):
1328 self.set_mode(self.valid_modes[0])
1357 self.set_mode(self.valid_modes[0])
1329
1358
1330 def context(self):
1359 def context(self):
1331 self.set_mode(self.valid_modes[1])
1360 self.set_mode(self.valid_modes[1])
1332
1361
1333 def verbose(self):
1362 def verbose(self):
1334 self.set_mode(self.valid_modes[2])
1363 self.set_mode(self.valid_modes[2])
1335
1364
1336 def minimal(self):
1365 def minimal(self):
1337 self.set_mode(self.valid_modes[3])
1366 self.set_mode(self.valid_modes[3])
1338
1367
1339
1368
1340 #----------------------------------------------------------------------------
1369 #----------------------------------------------------------------------------
1341 class AutoFormattedTB(FormattedTB):
1370 class AutoFormattedTB(FormattedTB):
1342 """A traceback printer which can be called on the fly.
1371 """A traceback printer which can be called on the fly.
1343
1372
1344 It will find out about exceptions by itself.
1373 It will find out about exceptions by itself.
1345
1374
1346 A brief example::
1375 A brief example::
1347
1376
1348 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1377 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1349 try:
1378 try:
1350 ...
1379 ...
1351 except:
1380 except:
1352 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1381 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1353 """
1382 """
1354
1383
1355 def __call__(self, etype=None, evalue=None, etb=None,
1384 def __call__(self, etype=None, evalue=None, etb=None,
1356 out=None, tb_offset=None):
1385 out=None, tb_offset=None):
1357 """Print out a formatted exception traceback.
1386 """Print out a formatted exception traceback.
1358
1387
1359 Optional arguments:
1388 Optional arguments:
1360 - out: an open file-like object to direct output to.
1389 - out: an open file-like object to direct output to.
1361
1390
1362 - tb_offset: the number of frames to skip over in the stack, on a
1391 - tb_offset: the number of frames to skip over in the stack, on a
1363 per-call basis (this overrides temporarily the instance's tb_offset
1392 per-call basis (this overrides temporarily the instance's tb_offset
1364 given at initialization time. """
1393 given at initialization time. """
1365
1394
1366 if out is None:
1395 if out is None:
1367 out = self.ostream
1396 out = self.ostream
1368 out.flush()
1397 out.flush()
1369 out.write(self.text(etype, evalue, etb, tb_offset))
1398 out.write(self.text(etype, evalue, etb, tb_offset))
1370 out.write('\n')
1399 out.write('\n')
1371 out.flush()
1400 out.flush()
1372 # FIXME: we should remove the auto pdb behavior from here and leave
1401 # FIXME: we should remove the auto pdb behavior from here and leave
1373 # that to the clients.
1402 # that to the clients.
1374 try:
1403 try:
1375 self.debugger()
1404 self.debugger()
1376 except KeyboardInterrupt:
1405 except KeyboardInterrupt:
1377 print("\nKeyboardInterrupt")
1406 print("\nKeyboardInterrupt")
1378
1407
1379 def structured_traceback(self, etype=None, value=None, tb=None,
1408 def structured_traceback(self, etype=None, value=None, tb=None,
1380 tb_offset=None, number_of_lines_of_context=5):
1409 tb_offset=None, number_of_lines_of_context=5):
1381 if etype is None:
1410 if etype is None:
1382 etype, value, tb = sys.exc_info()
1411 etype, value, tb = sys.exc_info()
1383 self.tb = tb
1412 self.tb = tb
1384 return FormattedTB.structured_traceback(
1413 return FormattedTB.structured_traceback(
1385 self, etype, value, tb, tb_offset, number_of_lines_of_context)
1414 self, etype, value, tb, tb_offset, number_of_lines_of_context)
1386
1415
1387
1416
1388 #---------------------------------------------------------------------------
1417 #---------------------------------------------------------------------------
1389
1418
1390 # A simple class to preserve Nathan's original functionality.
1419 # A simple class to preserve Nathan's original functionality.
1391 class ColorTB(FormattedTB):
1420 class ColorTB(FormattedTB):
1392 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1421 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1393
1422
1394 def __init__(self, color_scheme='Linux', call_pdb=0, **kwargs):
1423 def __init__(self, color_scheme='Linux', call_pdb=0, **kwargs):
1395 FormattedTB.__init__(self, color_scheme=color_scheme,
1424 FormattedTB.__init__(self, color_scheme=color_scheme,
1396 call_pdb=call_pdb, **kwargs)
1425 call_pdb=call_pdb, **kwargs)
1397
1426
1398
1427
1399 class SyntaxTB(ListTB):
1428 class SyntaxTB(ListTB):
1400 """Extension which holds some state: the last exception value"""
1429 """Extension which holds some state: the last exception value"""
1401
1430
1402 def __init__(self, color_scheme='NoColor', parent=None, config=None):
1431 def __init__(self, color_scheme='NoColor', parent=None, config=None):
1403 ListTB.__init__(self, color_scheme, parent=parent, config=config)
1432 ListTB.__init__(self, color_scheme, parent=parent, config=config)
1404 self.last_syntax_error = None
1433 self.last_syntax_error = None
1405
1434
1406 def __call__(self, etype, value, elist):
1435 def __call__(self, etype, value, elist):
1407 self.last_syntax_error = value
1436 self.last_syntax_error = value
1408
1437
1409 ListTB.__call__(self, etype, value, elist)
1438 ListTB.__call__(self, etype, value, elist)
1410
1439
1411 def structured_traceback(self, etype, value, elist, tb_offset=None,
1440 def structured_traceback(self, etype, value, elist, tb_offset=None,
1412 context=5):
1441 context=5):
1413 # If the source file has been edited, the line in the syntax error can
1442 # If the source file has been edited, the line in the syntax error can
1414 # be wrong (retrieved from an outdated cache). This replaces it with
1443 # be wrong (retrieved from an outdated cache). This replaces it with
1415 # the current value.
1444 # the current value.
1416 if isinstance(value, SyntaxError) \
1445 if isinstance(value, SyntaxError) \
1417 and isinstance(value.filename, str) \
1446 and isinstance(value.filename, str) \
1418 and isinstance(value.lineno, int):
1447 and isinstance(value.lineno, int):
1419 linecache.checkcache(value.filename)
1448 linecache.checkcache(value.filename)
1420 newtext = linecache.getline(value.filename, value.lineno)
1449 newtext = linecache.getline(value.filename, value.lineno)
1421 if newtext:
1450 if newtext:
1422 value.text = newtext
1451 value.text = newtext
1423 self.last_syntax_error = value
1452 self.last_syntax_error = value
1424 return super(SyntaxTB, self).structured_traceback(etype, value, elist,
1453 return super(SyntaxTB, self).structured_traceback(etype, value, elist,
1425 tb_offset=tb_offset, context=context)
1454 tb_offset=tb_offset, context=context)
1426
1455
1427 def clear_err_state(self):
1456 def clear_err_state(self):
1428 """Return the current error state and clear it"""
1457 """Return the current error state and clear it"""
1429 e = self.last_syntax_error
1458 e = self.last_syntax_error
1430 self.last_syntax_error = None
1459 self.last_syntax_error = None
1431 return e
1460 return e
1432
1461
1433 def stb2text(self, stb):
1462 def stb2text(self, stb):
1434 """Convert a structured traceback (a list) to a string."""
1463 """Convert a structured traceback (a list) to a string."""
1435 return ''.join(stb)
1464 return ''.join(stb)
1436
1465
1437
1466
1438 # some internal-use functions
1467 # some internal-use functions
1439 def text_repr(value):
1468 def text_repr(value):
1440 """Hopefully pretty robust repr equivalent."""
1469 """Hopefully pretty robust repr equivalent."""
1441 # this is pretty horrible but should always return *something*
1470 # this is pretty horrible but should always return *something*
1442 try:
1471 try:
1443 return pydoc.text.repr(value)
1472 return pydoc.text.repr(value)
1444 except KeyboardInterrupt:
1473 except KeyboardInterrupt:
1445 raise
1474 raise
1446 except:
1475 except:
1447 try:
1476 try:
1448 return repr(value)
1477 return repr(value)
1449 except KeyboardInterrupt:
1478 except KeyboardInterrupt:
1450 raise
1479 raise
1451 except:
1480 except:
1452 try:
1481 try:
1453 # all still in an except block so we catch
1482 # all still in an except block so we catch
1454 # getattr raising
1483 # getattr raising
1455 name = getattr(value, '__name__', None)
1484 name = getattr(value, '__name__', None)
1456 if name:
1485 if name:
1457 # ick, recursion
1486 # ick, recursion
1458 return text_repr(name)
1487 return text_repr(name)
1459 klass = getattr(value, '__class__', None)
1488 klass = getattr(value, '__class__', None)
1460 if klass:
1489 if klass:
1461 return '%s instance' % text_repr(klass)
1490 return '%s instance' % text_repr(klass)
1462 except KeyboardInterrupt:
1491 except KeyboardInterrupt:
1463 raise
1492 raise
1464 except:
1493 except:
1465 return 'UNRECOVERABLE REPR FAILURE'
1494 return 'UNRECOVERABLE REPR FAILURE'
1466
1495
1467
1496
1468 def eqrepr(value, repr=text_repr):
1497 def eqrepr(value, repr=text_repr):
1469 return '=%s' % repr(value)
1498 return '=%s' % repr(value)
1470
1499
1471
1500
1472 def nullrepr(value, repr=text_repr):
1501 def nullrepr(value, repr=text_repr):
1473 return ''
1502 return ''
@@ -1,69 +1,69 b''
1 """ Utilities for accessing the platform's clipboard.
1 """ Utilities for accessing the platform's clipboard.
2 """
2 """
3
3
4 import subprocess
4 import subprocess
5
5
6 from IPython.core.error import TryNext
6 from IPython.core.error import TryNext
7 import IPython.utils.py3compat as py3compat
7 import IPython.utils.py3compat as py3compat
8
8
9 class ClipboardEmpty(ValueError):
9 class ClipboardEmpty(ValueError):
10 pass
10 pass
11
11
12 def win32_clipboard_get():
12 def win32_clipboard_get():
13 """ Get the current clipboard's text on Windows.
13 """ Get the current clipboard's text on Windows.
14
14
15 Requires Mark Hammond's pywin32 extensions.
15 Requires Mark Hammond's pywin32 extensions.
16 """
16 """
17 try:
17 try:
18 import win32clipboard
18 import win32clipboard
19 except ImportError:
19 except ImportError:
20 raise TryNext("Getting text from the clipboard requires the pywin32 "
20 raise TryNext("Getting text from the clipboard requires the pywin32 "
21 "extensions: http://sourceforge.net/projects/pywin32/")
21 "extensions: http://sourceforge.net/projects/pywin32/")
22 win32clipboard.OpenClipboard()
22 win32clipboard.OpenClipboard()
23 try:
23 try:
24 text = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT)
24 text = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT)
25 except (TypeError, win32clipboard.error):
25 except (TypeError, win32clipboard.error):
26 try:
26 try:
27 text = win32clipboard.GetClipboardData(win32clipboard.CF_TEXT)
27 text = win32clipboard.GetClipboardData(win32clipboard.CF_TEXT)
28 text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING)
28 text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING)
29 except (TypeError, win32clipboard.error):
29 except (TypeError, win32clipboard.error):
30 raise ClipboardEmpty
30 raise ClipboardEmpty
31 finally:
31 finally:
32 win32clipboard.CloseClipboard()
32 win32clipboard.CloseClipboard()
33 return text
33 return text
34
34
35 def osx_clipboard_get():
35 def osx_clipboard_get() -> str:
36 """ Get the clipboard's text on OS X.
36 """ Get the clipboard's text on OS X.
37 """
37 """
38 p = subprocess.Popen(['pbpaste', '-Prefer', 'ascii'],
38 p = subprocess.Popen(['pbpaste', '-Prefer', 'ascii'],
39 stdout=subprocess.PIPE)
39 stdout=subprocess.PIPE)
40 text, stderr = p.communicate()
40 bytes_, stderr = p.communicate()
41 # Text comes in with old Mac \r line endings. Change them to \n.
41 # Text comes in with old Mac \r line endings. Change them to \n.
42 text = text.replace(b'\r', b'\n')
42 bytes_ = bytes_.replace(b'\r', b'\n')
43 text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING)
43 text = py3compat.decode(bytes_)
44 return text
44 return text
45
45
46 def tkinter_clipboard_get():
46 def tkinter_clipboard_get():
47 """ Get the clipboard's text using Tkinter.
47 """ Get the clipboard's text using Tkinter.
48
48
49 This is the default on systems that are not Windows or OS X. It may
49 This is the default on systems that are not Windows or OS X. It may
50 interfere with other UI toolkits and should be replaced with an
50 interfere with other UI toolkits and should be replaced with an
51 implementation that uses that toolkit.
51 implementation that uses that toolkit.
52 """
52 """
53 try:
53 try:
54 from tkinter import Tk, TclError
54 from tkinter import Tk, TclError
55 except ImportError:
55 except ImportError:
56 raise TryNext("Getting text from the clipboard on this platform requires tkinter.")
56 raise TryNext("Getting text from the clipboard on this platform requires tkinter.")
57
57
58 root = Tk()
58 root = Tk()
59 root.withdraw()
59 root.withdraw()
60 try:
60 try:
61 text = root.clipboard_get()
61 text = root.clipboard_get()
62 except TclError:
62 except TclError:
63 raise ClipboardEmpty
63 raise ClipboardEmpty
64 finally:
64 finally:
65 root.destroy()
65 root.destroy()
66 text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING)
66 text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING)
67 return text
67 return text
68
68
69
69
@@ -1,871 +1,863 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Python advanced pretty printer. This pretty printer is intended to
3 Python advanced pretty printer. This pretty printer is intended to
4 replace the old `pprint` python module which does not allow developers
4 replace the old `pprint` python module which does not allow developers
5 to provide their own pretty print callbacks.
5 to provide their own pretty print callbacks.
6
6
7 This module is based on ruby's `prettyprint.rb` library by `Tanaka Akira`.
7 This module is based on ruby's `prettyprint.rb` library by `Tanaka Akira`.
8
8
9
9
10 Example Usage
10 Example Usage
11 -------------
11 -------------
12
12
13 To directly print the representation of an object use `pprint`::
13 To directly print the representation of an object use `pprint`::
14
14
15 from pretty import pprint
15 from pretty import pprint
16 pprint(complex_object)
16 pprint(complex_object)
17
17
18 To get a string of the output use `pretty`::
18 To get a string of the output use `pretty`::
19
19
20 from pretty import pretty
20 from pretty import pretty
21 string = pretty(complex_object)
21 string = pretty(complex_object)
22
22
23
23
24 Extending
24 Extending
25 ---------
25 ---------
26
26
27 The pretty library allows developers to add pretty printing rules for their
27 The pretty library allows developers to add pretty printing rules for their
28 own objects. This process is straightforward. All you have to do is to
28 own objects. This process is straightforward. All you have to do is to
29 add a `_repr_pretty_` method to your object and call the methods on the
29 add a `_repr_pretty_` method to your object and call the methods on the
30 pretty printer passed::
30 pretty printer passed::
31
31
32 class MyObject(object):
32 class MyObject(object):
33
33
34 def _repr_pretty_(self, p, cycle):
34 def _repr_pretty_(self, p, cycle):
35 ...
35 ...
36
36
37 Here is an example implementation of a `_repr_pretty_` method for a list
37 Here is an example implementation of a `_repr_pretty_` method for a list
38 subclass::
38 subclass::
39
39
40 class MyList(list):
40 class MyList(list):
41
41
42 def _repr_pretty_(self, p, cycle):
42 def _repr_pretty_(self, p, cycle):
43 if cycle:
43 if cycle:
44 p.text('MyList(...)')
44 p.text('MyList(...)')
45 else:
45 else:
46 with p.group(8, 'MyList([', '])'):
46 with p.group(8, 'MyList([', '])'):
47 for idx, item in enumerate(self):
47 for idx, item in enumerate(self):
48 if idx:
48 if idx:
49 p.text(',')
49 p.text(',')
50 p.breakable()
50 p.breakable()
51 p.pretty(item)
51 p.pretty(item)
52
52
53 The `cycle` parameter is `True` if pretty detected a cycle. You *have* to
53 The `cycle` parameter is `True` if pretty detected a cycle. You *have* to
54 react to that or the result is an infinite loop. `p.text()` just adds
54 react to that or the result is an infinite loop. `p.text()` just adds
55 non breaking text to the output, `p.breakable()` either adds a whitespace
55 non breaking text to the output, `p.breakable()` either adds a whitespace
56 or breaks here. If you pass it an argument it's used instead of the
56 or breaks here. If you pass it an argument it's used instead of the
57 default space. `p.pretty` prettyprints another object using the pretty print
57 default space. `p.pretty` prettyprints another object using the pretty print
58 method.
58 method.
59
59
60 The first parameter to the `group` function specifies the extra indentation
60 The first parameter to the `group` function specifies the extra indentation
61 of the next line. In this example the next item will either be on the same
61 of the next line. In this example the next item will either be on the same
62 line (if the items are short enough) or aligned with the right edge of the
62 line (if the items are short enough) or aligned with the right edge of the
63 opening bracket of `MyList`.
63 opening bracket of `MyList`.
64
64
65 If you just want to indent something you can use the group function
65 If you just want to indent something you can use the group function
66 without open / close parameters. You can also use this code::
66 without open / close parameters. You can also use this code::
67
67
68 with p.indent(2):
68 with p.indent(2):
69 ...
69 ...
70
70
71 Inheritance diagram:
71 Inheritance diagram:
72
72
73 .. inheritance-diagram:: IPython.lib.pretty
73 .. inheritance-diagram:: IPython.lib.pretty
74 :parts: 3
74 :parts: 3
75
75
76 :copyright: 2007 by Armin Ronacher.
76 :copyright: 2007 by Armin Ronacher.
77 Portions (c) 2009 by Robert Kern.
77 Portions (c) 2009 by Robert Kern.
78 :license: BSD License.
78 :license: BSD License.
79 """
79 """
80
80
81 from contextlib import contextmanager
81 from contextlib import contextmanager
82 import datetime
82 import datetime
83 import os
83 import os
84 import re
84 import re
85 import sys
85 import sys
86 import types
86 import types
87 from collections import deque
87 from collections import deque
88 from inspect import signature
88 from inspect import signature
89 from io import StringIO
89 from io import StringIO
90 from warnings import warn
90 from warnings import warn
91
91
92 from IPython.utils.decorators import undoc
92 from IPython.utils.decorators import undoc
93 from IPython.utils.py3compat import PYPY
93 from IPython.utils.py3compat import PYPY
94
94
95 __all__ = ['pretty', 'pprint', 'PrettyPrinter', 'RepresentationPrinter',
95 __all__ = ['pretty', 'pprint', 'PrettyPrinter', 'RepresentationPrinter',
96 'for_type', 'for_type_by_name']
96 'for_type', 'for_type_by_name']
97
97
98
98
99 MAX_SEQ_LENGTH = 1000
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 _re_pattern_type = type(re.compile(''))
100 _re_pattern_type = type(re.compile(''))
104
101
105 def _safe_getattr(obj, attr, default=None):
102 def _safe_getattr(obj, attr, default=None):
106 """Safe version of getattr.
103 """Safe version of getattr.
107
104
108 Same as getattr, but will return ``default`` on any Exception,
105 Same as getattr, but will return ``default`` on any Exception,
109 rather than raising.
106 rather than raising.
110 """
107 """
111 try:
108 try:
112 return getattr(obj, attr, default)
109 return getattr(obj, attr, default)
113 except Exception:
110 except Exception:
114 return default
111 return default
115
112
116 @undoc
113 @undoc
117 class CUnicodeIO(StringIO):
114 class CUnicodeIO(StringIO):
118 def __init__(self, *args, **kwargs):
115 def __init__(self, *args, **kwargs):
119 super().__init__(*args, **kwargs)
116 super().__init__(*args, **kwargs)
120 warn(("CUnicodeIO is deprecated since IPython 6.0. "
117 warn(("CUnicodeIO is deprecated since IPython 6.0. "
121 "Please use io.StringIO instead."),
118 "Please use io.StringIO instead."),
122 DeprecationWarning, stacklevel=2)
119 DeprecationWarning, stacklevel=2)
123
120
124 def _sorted_for_pprint(items):
121 def _sorted_for_pprint(items):
125 """
122 """
126 Sort the given items for pretty printing. Since some predictable
123 Sort the given items for pretty printing. Since some predictable
127 sorting is better than no sorting at all, we sort on the string
124 sorting is better than no sorting at all, we sort on the string
128 representation if normal sorting fails.
125 representation if normal sorting fails.
129 """
126 """
130 items = list(items)
127 items = list(items)
131 try:
128 try:
132 return sorted(items)
129 return sorted(items)
133 except Exception:
130 except Exception:
134 try:
131 try:
135 return sorted(items, key=str)
132 return sorted(items, key=str)
136 except Exception:
133 except Exception:
137 return items
134 return items
138
135
139 def pretty(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
136 def pretty(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
140 """
137 """
141 Pretty print the object's representation.
138 Pretty print the object's representation.
142 """
139 """
143 stream = StringIO()
140 stream = StringIO()
144 printer = RepresentationPrinter(stream, verbose, max_width, newline, max_seq_length=max_seq_length)
141 printer = RepresentationPrinter(stream, verbose, max_width, newline, max_seq_length=max_seq_length)
145 printer.pretty(obj)
142 printer.pretty(obj)
146 printer.flush()
143 printer.flush()
147 return stream.getvalue()
144 return stream.getvalue()
148
145
149
146
150 def pprint(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
147 def pprint(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
151 """
148 """
152 Like `pretty` but print to stdout.
149 Like `pretty` but print to stdout.
153 """
150 """
154 printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline, max_seq_length=max_seq_length)
151 printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline, max_seq_length=max_seq_length)
155 printer.pretty(obj)
152 printer.pretty(obj)
156 printer.flush()
153 printer.flush()
157 sys.stdout.write(newline)
154 sys.stdout.write(newline)
158 sys.stdout.flush()
155 sys.stdout.flush()
159
156
160 class _PrettyPrinterBase(object):
157 class _PrettyPrinterBase(object):
161
158
162 @contextmanager
159 @contextmanager
163 def indent(self, indent):
160 def indent(self, indent):
164 """with statement support for indenting/dedenting."""
161 """with statement support for indenting/dedenting."""
165 self.indentation += indent
162 self.indentation += indent
166 try:
163 try:
167 yield
164 yield
168 finally:
165 finally:
169 self.indentation -= indent
166 self.indentation -= indent
170
167
171 @contextmanager
168 @contextmanager
172 def group(self, indent=0, open='', close=''):
169 def group(self, indent=0, open='', close=''):
173 """like begin_group / end_group but for the with statement."""
170 """like begin_group / end_group but for the with statement."""
174 self.begin_group(indent, open)
171 self.begin_group(indent, open)
175 try:
172 try:
176 yield
173 yield
177 finally:
174 finally:
178 self.end_group(indent, close)
175 self.end_group(indent, close)
179
176
180 class PrettyPrinter(_PrettyPrinterBase):
177 class PrettyPrinter(_PrettyPrinterBase):
181 """
178 """
182 Baseclass for the `RepresentationPrinter` prettyprinter that is used to
179 Baseclass for the `RepresentationPrinter` prettyprinter that is used to
183 generate pretty reprs of objects. Contrary to the `RepresentationPrinter`
180 generate pretty reprs of objects. Contrary to the `RepresentationPrinter`
184 this printer knows nothing about the default pprinters or the `_repr_pretty_`
181 this printer knows nothing about the default pprinters or the `_repr_pretty_`
185 callback method.
182 callback method.
186 """
183 """
187
184
188 def __init__(self, output, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
185 def __init__(self, output, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
189 self.output = output
186 self.output = output
190 self.max_width = max_width
187 self.max_width = max_width
191 self.newline = newline
188 self.newline = newline
192 self.max_seq_length = max_seq_length
189 self.max_seq_length = max_seq_length
193 self.output_width = 0
190 self.output_width = 0
194 self.buffer_width = 0
191 self.buffer_width = 0
195 self.buffer = deque()
192 self.buffer = deque()
196
193
197 root_group = Group(0)
194 root_group = Group(0)
198 self.group_stack = [root_group]
195 self.group_stack = [root_group]
199 self.group_queue = GroupQueue(root_group)
196 self.group_queue = GroupQueue(root_group)
200 self.indentation = 0
197 self.indentation = 0
201
198
202 def _break_outer_groups(self):
199 def _break_outer_groups(self):
203 while self.max_width < self.output_width + self.buffer_width:
200 while self.max_width < self.output_width + self.buffer_width:
204 group = self.group_queue.deq()
201 group = self.group_queue.deq()
205 if not group:
202 if not group:
206 return
203 return
207 while group.breakables:
204 while group.breakables:
208 x = self.buffer.popleft()
205 x = self.buffer.popleft()
209 self.output_width = x.output(self.output, self.output_width)
206 self.output_width = x.output(self.output, self.output_width)
210 self.buffer_width -= x.width
207 self.buffer_width -= x.width
211 while self.buffer and isinstance(self.buffer[0], Text):
208 while self.buffer and isinstance(self.buffer[0], Text):
212 x = self.buffer.popleft()
209 x = self.buffer.popleft()
213 self.output_width = x.output(self.output, self.output_width)
210 self.output_width = x.output(self.output, self.output_width)
214 self.buffer_width -= x.width
211 self.buffer_width -= x.width
215
212
216 def text(self, obj):
213 def text(self, obj):
217 """Add literal text to the output."""
214 """Add literal text to the output."""
218 width = len(obj)
215 width = len(obj)
219 if self.buffer:
216 if self.buffer:
220 text = self.buffer[-1]
217 text = self.buffer[-1]
221 if not isinstance(text, Text):
218 if not isinstance(text, Text):
222 text = Text()
219 text = Text()
223 self.buffer.append(text)
220 self.buffer.append(text)
224 text.add(obj, width)
221 text.add(obj, width)
225 self.buffer_width += width
222 self.buffer_width += width
226 self._break_outer_groups()
223 self._break_outer_groups()
227 else:
224 else:
228 self.output.write(obj)
225 self.output.write(obj)
229 self.output_width += width
226 self.output_width += width
230
227
231 def breakable(self, sep=' '):
228 def breakable(self, sep=' '):
232 """
229 """
233 Add a breakable separator to the output. This does not mean that it
230 Add a breakable separator to the output. This does not mean that it
234 will automatically break here. If no breaking on this position takes
231 will automatically break here. If no breaking on this position takes
235 place the `sep` is inserted which default to one space.
232 place the `sep` is inserted which default to one space.
236 """
233 """
237 width = len(sep)
234 width = len(sep)
238 group = self.group_stack[-1]
235 group = self.group_stack[-1]
239 if group.want_break:
236 if group.want_break:
240 self.flush()
237 self.flush()
241 self.output.write(self.newline)
238 self.output.write(self.newline)
242 self.output.write(' ' * self.indentation)
239 self.output.write(' ' * self.indentation)
243 self.output_width = self.indentation
240 self.output_width = self.indentation
244 self.buffer_width = 0
241 self.buffer_width = 0
245 else:
242 else:
246 self.buffer.append(Breakable(sep, width, self))
243 self.buffer.append(Breakable(sep, width, self))
247 self.buffer_width += width
244 self.buffer_width += width
248 self._break_outer_groups()
245 self._break_outer_groups()
249
246
250 def break_(self):
247 def break_(self):
251 """
248 """
252 Explicitly insert a newline into the output, maintaining correct indentation.
249 Explicitly insert a newline into the output, maintaining correct indentation.
253 """
250 """
254 self.flush()
251 self.flush()
255 self.output.write(self.newline)
252 self.output.write(self.newline)
256 self.output.write(' ' * self.indentation)
253 self.output.write(' ' * self.indentation)
257 self.output_width = self.indentation
254 self.output_width = self.indentation
258 self.buffer_width = 0
255 self.buffer_width = 0
259
256
260
257
261 def begin_group(self, indent=0, open=''):
258 def begin_group(self, indent=0, open=''):
262 """
259 """
263 Begin a group. If you want support for python < 2.5 which doesn't has
260 Begin a group. If you want support for python < 2.5 which doesn't has
264 the with statement this is the preferred way:
261 the with statement this is the preferred way:
265
262
266 p.begin_group(1, '{')
263 p.begin_group(1, '{')
267 ...
264 ...
268 p.end_group(1, '}')
265 p.end_group(1, '}')
269
266
270 The python 2.5 expression would be this:
267 The python 2.5 expression would be this:
271
268
272 with p.group(1, '{', '}'):
269 with p.group(1, '{', '}'):
273 ...
270 ...
274
271
275 The first parameter specifies the indentation for the next line (usually
272 The first parameter specifies the indentation for the next line (usually
276 the width of the opening text), the second the opening text. All
273 the width of the opening text), the second the opening text. All
277 parameters are optional.
274 parameters are optional.
278 """
275 """
279 if open:
276 if open:
280 self.text(open)
277 self.text(open)
281 group = Group(self.group_stack[-1].depth + 1)
278 group = Group(self.group_stack[-1].depth + 1)
282 self.group_stack.append(group)
279 self.group_stack.append(group)
283 self.group_queue.enq(group)
280 self.group_queue.enq(group)
284 self.indentation += indent
281 self.indentation += indent
285
282
286 def _enumerate(self, seq):
283 def _enumerate(self, seq):
287 """like enumerate, but with an upper limit on the number of items"""
284 """like enumerate, but with an upper limit on the number of items"""
288 for idx, x in enumerate(seq):
285 for idx, x in enumerate(seq):
289 if self.max_seq_length and idx >= self.max_seq_length:
286 if self.max_seq_length and idx >= self.max_seq_length:
290 self.text(',')
287 self.text(',')
291 self.breakable()
288 self.breakable()
292 self.text('...')
289 self.text('...')
293 return
290 return
294 yield idx, x
291 yield idx, x
295
292
296 def end_group(self, dedent=0, close=''):
293 def end_group(self, dedent=0, close=''):
297 """End a group. See `begin_group` for more details."""
294 """End a group. See `begin_group` for more details."""
298 self.indentation -= dedent
295 self.indentation -= dedent
299 group = self.group_stack.pop()
296 group = self.group_stack.pop()
300 if not group.breakables:
297 if not group.breakables:
301 self.group_queue.remove(group)
298 self.group_queue.remove(group)
302 if close:
299 if close:
303 self.text(close)
300 self.text(close)
304
301
305 def flush(self):
302 def flush(self):
306 """Flush data that is left in the buffer."""
303 """Flush data that is left in the buffer."""
307 for data in self.buffer:
304 for data in self.buffer:
308 self.output_width += data.output(self.output, self.output_width)
305 self.output_width += data.output(self.output, self.output_width)
309 self.buffer.clear()
306 self.buffer.clear()
310 self.buffer_width = 0
307 self.buffer_width = 0
311
308
312
309
313 def _get_mro(obj_class):
310 def _get_mro(obj_class):
314 """ Get a reasonable method resolution order of a class and its superclasses
311 """ Get a reasonable method resolution order of a class and its superclasses
315 for both old-style and new-style classes.
312 for both old-style and new-style classes.
316 """
313 """
317 if not hasattr(obj_class, '__mro__'):
314 if not hasattr(obj_class, '__mro__'):
318 # Old-style class. Mix in object to make a fake new-style class.
315 # Old-style class. Mix in object to make a fake new-style class.
319 try:
316 try:
320 obj_class = type(obj_class.__name__, (obj_class, object), {})
317 obj_class = type(obj_class.__name__, (obj_class, object), {})
321 except TypeError:
318 except TypeError:
322 # Old-style extension type that does not descend from object.
319 # Old-style extension type that does not descend from object.
323 # FIXME: try to construct a more thorough MRO.
320 # FIXME: try to construct a more thorough MRO.
324 mro = [obj_class]
321 mro = [obj_class]
325 else:
322 else:
326 mro = obj_class.__mro__[1:-1]
323 mro = obj_class.__mro__[1:-1]
327 else:
324 else:
328 mro = obj_class.__mro__
325 mro = obj_class.__mro__
329 return mro
326 return mro
330
327
331
328
332 class RepresentationPrinter(PrettyPrinter):
329 class RepresentationPrinter(PrettyPrinter):
333 """
330 """
334 Special pretty printer that has a `pretty` method that calls the pretty
331 Special pretty printer that has a `pretty` method that calls the pretty
335 printer for a python object.
332 printer for a python object.
336
333
337 This class stores processing data on `self` so you must *never* use
334 This class stores processing data on `self` so you must *never* use
338 this class in a threaded environment. Always lock it or reinstanciate
335 this class in a threaded environment. Always lock it or reinstanciate
339 it.
336 it.
340
337
341 Instances also have a verbose flag callbacks can access to control their
338 Instances also have a verbose flag callbacks can access to control their
342 output. For example the default instance repr prints all attributes and
339 output. For example the default instance repr prints all attributes and
343 methods that are not prefixed by an underscore if the printer is in
340 methods that are not prefixed by an underscore if the printer is in
344 verbose mode.
341 verbose mode.
345 """
342 """
346
343
347 def __init__(self, output, verbose=False, max_width=79, newline='\n',
344 def __init__(self, output, verbose=False, max_width=79, newline='\n',
348 singleton_pprinters=None, type_pprinters=None, deferred_pprinters=None,
345 singleton_pprinters=None, type_pprinters=None, deferred_pprinters=None,
349 max_seq_length=MAX_SEQ_LENGTH):
346 max_seq_length=MAX_SEQ_LENGTH):
350
347
351 PrettyPrinter.__init__(self, output, max_width, newline, max_seq_length=max_seq_length)
348 PrettyPrinter.__init__(self, output, max_width, newline, max_seq_length=max_seq_length)
352 self.verbose = verbose
349 self.verbose = verbose
353 self.stack = []
350 self.stack = []
354 if singleton_pprinters is None:
351 if singleton_pprinters is None:
355 singleton_pprinters = _singleton_pprinters.copy()
352 singleton_pprinters = _singleton_pprinters.copy()
356 self.singleton_pprinters = singleton_pprinters
353 self.singleton_pprinters = singleton_pprinters
357 if type_pprinters is None:
354 if type_pprinters is None:
358 type_pprinters = _type_pprinters.copy()
355 type_pprinters = _type_pprinters.copy()
359 self.type_pprinters = type_pprinters
356 self.type_pprinters = type_pprinters
360 if deferred_pprinters is None:
357 if deferred_pprinters is None:
361 deferred_pprinters = _deferred_type_pprinters.copy()
358 deferred_pprinters = _deferred_type_pprinters.copy()
362 self.deferred_pprinters = deferred_pprinters
359 self.deferred_pprinters = deferred_pprinters
363
360
364 def pretty(self, obj):
361 def pretty(self, obj):
365 """Pretty print the given object."""
362 """Pretty print the given object."""
366 obj_id = id(obj)
363 obj_id = id(obj)
367 cycle = obj_id in self.stack
364 cycle = obj_id in self.stack
368 self.stack.append(obj_id)
365 self.stack.append(obj_id)
369 self.begin_group()
366 self.begin_group()
370 try:
367 try:
371 obj_class = _safe_getattr(obj, '__class__', None) or type(obj)
368 obj_class = _safe_getattr(obj, '__class__', None) or type(obj)
372 # First try to find registered singleton printers for the type.
369 # First try to find registered singleton printers for the type.
373 try:
370 try:
374 printer = self.singleton_pprinters[obj_id]
371 printer = self.singleton_pprinters[obj_id]
375 except (TypeError, KeyError):
372 except (TypeError, KeyError):
376 pass
373 pass
377 else:
374 else:
378 return printer(obj, self, cycle)
375 return printer(obj, self, cycle)
379 # Next walk the mro and check for either:
376 # Next walk the mro and check for either:
380 # 1) a registered printer
377 # 1) a registered printer
381 # 2) a _repr_pretty_ method
378 # 2) a _repr_pretty_ method
382 for cls in _get_mro(obj_class):
379 for cls in _get_mro(obj_class):
383 if cls in self.type_pprinters:
380 if cls in self.type_pprinters:
384 # printer registered in self.type_pprinters
381 # printer registered in self.type_pprinters
385 return self.type_pprinters[cls](obj, self, cycle)
382 return self.type_pprinters[cls](obj, self, cycle)
386 else:
383 else:
387 # deferred printer
384 # deferred printer
388 printer = self._in_deferred_types(cls)
385 printer = self._in_deferred_types(cls)
389 if printer is not None:
386 if printer is not None:
390 return printer(obj, self, cycle)
387 return printer(obj, self, cycle)
391 else:
388 else:
392 # Finally look for special method names.
389 # Finally look for special method names.
393 # Some objects automatically create any requested
390 # Some objects automatically create any requested
394 # attribute. Try to ignore most of them by checking for
391 # attribute. Try to ignore most of them by checking for
395 # callability.
392 # callability.
396 if '_repr_pretty_' in cls.__dict__:
393 if '_repr_pretty_' in cls.__dict__:
397 meth = cls._repr_pretty_
394 meth = cls._repr_pretty_
398 if callable(meth):
395 if callable(meth):
399 return meth(obj, self, cycle)
396 return meth(obj, self, cycle)
400 if cls is not object \
397 if cls is not object \
401 and callable(cls.__dict__.get('__repr__')):
398 and callable(cls.__dict__.get('__repr__')):
402 return _repr_pprint(obj, self, cycle)
399 return _repr_pprint(obj, self, cycle)
403
400
404 return _default_pprint(obj, self, cycle)
401 return _default_pprint(obj, self, cycle)
405 finally:
402 finally:
406 self.end_group()
403 self.end_group()
407 self.stack.pop()
404 self.stack.pop()
408
405
409 def _in_deferred_types(self, cls):
406 def _in_deferred_types(self, cls):
410 """
407 """
411 Check if the given class is specified in the deferred type registry.
408 Check if the given class is specified in the deferred type registry.
412
409
413 Returns the printer from the registry if it exists, and None if the
410 Returns the printer from the registry if it exists, and None if the
414 class is not in the registry. Successful matches will be moved to the
411 class is not in the registry. Successful matches will be moved to the
415 regular type registry for future use.
412 regular type registry for future use.
416 """
413 """
417 mod = _safe_getattr(cls, '__module__', None)
414 mod = _safe_getattr(cls, '__module__', None)
418 name = _safe_getattr(cls, '__name__', None)
415 name = _safe_getattr(cls, '__name__', None)
419 key = (mod, name)
416 key = (mod, name)
420 printer = None
417 printer = None
421 if key in self.deferred_pprinters:
418 if key in self.deferred_pprinters:
422 # Move the printer over to the regular registry.
419 # Move the printer over to the regular registry.
423 printer = self.deferred_pprinters.pop(key)
420 printer = self.deferred_pprinters.pop(key)
424 self.type_pprinters[cls] = printer
421 self.type_pprinters[cls] = printer
425 return printer
422 return printer
426
423
427
424
428 class Printable(object):
425 class Printable(object):
429
426
430 def output(self, stream, output_width):
427 def output(self, stream, output_width):
431 return output_width
428 return output_width
432
429
433
430
434 class Text(Printable):
431 class Text(Printable):
435
432
436 def __init__(self):
433 def __init__(self):
437 self.objs = []
434 self.objs = []
438 self.width = 0
435 self.width = 0
439
436
440 def output(self, stream, output_width):
437 def output(self, stream, output_width):
441 for obj in self.objs:
438 for obj in self.objs:
442 stream.write(obj)
439 stream.write(obj)
443 return output_width + self.width
440 return output_width + self.width
444
441
445 def add(self, obj, width):
442 def add(self, obj, width):
446 self.objs.append(obj)
443 self.objs.append(obj)
447 self.width += width
444 self.width += width
448
445
449
446
450 class Breakable(Printable):
447 class Breakable(Printable):
451
448
452 def __init__(self, seq, width, pretty):
449 def __init__(self, seq, width, pretty):
453 self.obj = seq
450 self.obj = seq
454 self.width = width
451 self.width = width
455 self.pretty = pretty
452 self.pretty = pretty
456 self.indentation = pretty.indentation
453 self.indentation = pretty.indentation
457 self.group = pretty.group_stack[-1]
454 self.group = pretty.group_stack[-1]
458 self.group.breakables.append(self)
455 self.group.breakables.append(self)
459
456
460 def output(self, stream, output_width):
457 def output(self, stream, output_width):
461 self.group.breakables.popleft()
458 self.group.breakables.popleft()
462 if self.group.want_break:
459 if self.group.want_break:
463 stream.write(self.pretty.newline)
460 stream.write(self.pretty.newline)
464 stream.write(' ' * self.indentation)
461 stream.write(' ' * self.indentation)
465 return self.indentation
462 return self.indentation
466 if not self.group.breakables:
463 if not self.group.breakables:
467 self.pretty.group_queue.remove(self.group)
464 self.pretty.group_queue.remove(self.group)
468 stream.write(self.obj)
465 stream.write(self.obj)
469 return output_width + self.width
466 return output_width + self.width
470
467
471
468
472 class Group(Printable):
469 class Group(Printable):
473
470
474 def __init__(self, depth):
471 def __init__(self, depth):
475 self.depth = depth
472 self.depth = depth
476 self.breakables = deque()
473 self.breakables = deque()
477 self.want_break = False
474 self.want_break = False
478
475
479
476
480 class GroupQueue(object):
477 class GroupQueue(object):
481
478
482 def __init__(self, *groups):
479 def __init__(self, *groups):
483 self.queue = []
480 self.queue = []
484 for group in groups:
481 for group in groups:
485 self.enq(group)
482 self.enq(group)
486
483
487 def enq(self, group):
484 def enq(self, group):
488 depth = group.depth
485 depth = group.depth
489 while depth > len(self.queue) - 1:
486 while depth > len(self.queue) - 1:
490 self.queue.append([])
487 self.queue.append([])
491 self.queue[depth].append(group)
488 self.queue[depth].append(group)
492
489
493 def deq(self):
490 def deq(self):
494 for stack in self.queue:
491 for stack in self.queue:
495 for idx, group in enumerate(reversed(stack)):
492 for idx, group in enumerate(reversed(stack)):
496 if group.breakables:
493 if group.breakables:
497 del stack[idx]
494 del stack[idx]
498 group.want_break = True
495 group.want_break = True
499 return group
496 return group
500 for group in stack:
497 for group in stack:
501 group.want_break = True
498 group.want_break = True
502 del stack[:]
499 del stack[:]
503
500
504 def remove(self, group):
501 def remove(self, group):
505 try:
502 try:
506 self.queue[group.depth].remove(group)
503 self.queue[group.depth].remove(group)
507 except ValueError:
504 except ValueError:
508 pass
505 pass
509
506
510
507
511 def _default_pprint(obj, p, cycle):
508 def _default_pprint(obj, p, cycle):
512 """
509 """
513 The default print function. Used if an object does not provide one and
510 The default print function. Used if an object does not provide one and
514 it's none of the builtin objects.
511 it's none of the builtin objects.
515 """
512 """
516 klass = _safe_getattr(obj, '__class__', None) or type(obj)
513 klass = _safe_getattr(obj, '__class__', None) or type(obj)
517 if _safe_getattr(klass, '__repr__', None) is not object.__repr__:
514 if _safe_getattr(klass, '__repr__', None) is not object.__repr__:
518 # A user-provided repr. Find newlines and replace them with p.break_()
515 # A user-provided repr. Find newlines and replace them with p.break_()
519 _repr_pprint(obj, p, cycle)
516 _repr_pprint(obj, p, cycle)
520 return
517 return
521 p.begin_group(1, '<')
518 p.begin_group(1, '<')
522 p.pretty(klass)
519 p.pretty(klass)
523 p.text(' at 0x%x' % id(obj))
520 p.text(' at 0x%x' % id(obj))
524 if cycle:
521 if cycle:
525 p.text(' ...')
522 p.text(' ...')
526 elif p.verbose:
523 elif p.verbose:
527 first = True
524 first = True
528 for key in dir(obj):
525 for key in dir(obj):
529 if not key.startswith('_'):
526 if not key.startswith('_'):
530 try:
527 try:
531 value = getattr(obj, key)
528 value = getattr(obj, key)
532 except AttributeError:
529 except AttributeError:
533 continue
530 continue
534 if isinstance(value, types.MethodType):
531 if isinstance(value, types.MethodType):
535 continue
532 continue
536 if not first:
533 if not first:
537 p.text(',')
534 p.text(',')
538 p.breakable()
535 p.breakable()
539 p.text(key)
536 p.text(key)
540 p.text('=')
537 p.text('=')
541 step = len(key) + 1
538 step = len(key) + 1
542 p.indentation += step
539 p.indentation += step
543 p.pretty(value)
540 p.pretty(value)
544 p.indentation -= step
541 p.indentation -= step
545 first = False
542 first = False
546 p.end_group(1, '>')
543 p.end_group(1, '>')
547
544
548
545
549 def _seq_pprinter_factory(start, end):
546 def _seq_pprinter_factory(start, end):
550 """
547 """
551 Factory that returns a pprint function useful for sequences. Used by
548 Factory that returns a pprint function useful for sequences. Used by
552 the default pprint for tuples, dicts, and lists.
549 the default pprint for tuples, dicts, and lists.
553 """
550 """
554 def inner(obj, p, cycle):
551 def inner(obj, p, cycle):
555 if cycle:
552 if cycle:
556 return p.text(start + '...' + end)
553 return p.text(start + '...' + end)
557 step = len(start)
554 step = len(start)
558 p.begin_group(step, start)
555 p.begin_group(step, start)
559 for idx, x in p._enumerate(obj):
556 for idx, x in p._enumerate(obj):
560 if idx:
557 if idx:
561 p.text(',')
558 p.text(',')
562 p.breakable()
559 p.breakable()
563 p.pretty(x)
560 p.pretty(x)
564 if len(obj) == 1 and type(obj) is tuple:
561 if len(obj) == 1 and type(obj) is tuple:
565 # Special case for 1-item tuples.
562 # Special case for 1-item tuples.
566 p.text(',')
563 p.text(',')
567 p.end_group(step, end)
564 p.end_group(step, end)
568 return inner
565 return inner
569
566
570
567
571 def _set_pprinter_factory(start, end):
568 def _set_pprinter_factory(start, end):
572 """
569 """
573 Factory that returns a pprint function useful for sets and frozensets.
570 Factory that returns a pprint function useful for sets and frozensets.
574 """
571 """
575 def inner(obj, p, cycle):
572 def inner(obj, p, cycle):
576 if cycle:
573 if cycle:
577 return p.text(start + '...' + end)
574 return p.text(start + '...' + end)
578 if len(obj) == 0:
575 if len(obj) == 0:
579 # Special case.
576 # Special case.
580 p.text(type(obj).__name__ + '()')
577 p.text(type(obj).__name__ + '()')
581 else:
578 else:
582 step = len(start)
579 step = len(start)
583 p.begin_group(step, start)
580 p.begin_group(step, start)
584 # Like dictionary keys, we will try to sort the items if there aren't too many
581 # Like dictionary keys, we will try to sort the items if there aren't too many
585 if not (p.max_seq_length and len(obj) >= p.max_seq_length):
582 if not (p.max_seq_length and len(obj) >= p.max_seq_length):
586 items = _sorted_for_pprint(obj)
583 items = _sorted_for_pprint(obj)
587 else:
584 else:
588 items = obj
585 items = obj
589 for idx, x in p._enumerate(items):
586 for idx, x in p._enumerate(items):
590 if idx:
587 if idx:
591 p.text(',')
588 p.text(',')
592 p.breakable()
589 p.breakable()
593 p.pretty(x)
590 p.pretty(x)
594 p.end_group(step, end)
591 p.end_group(step, end)
595 return inner
592 return inner
596
593
597
594
598 def _dict_pprinter_factory(start, end):
595 def _dict_pprinter_factory(start, end):
599 """
596 """
600 Factory that returns a pprint function used by the default pprint of
597 Factory that returns a pprint function used by the default pprint of
601 dicts and dict proxies.
598 dicts and dict proxies.
602 """
599 """
603 def inner(obj, p, cycle):
600 def inner(obj, p, cycle):
604 if cycle:
601 if cycle:
605 return p.text('{...}')
602 return p.text('{...}')
606 step = len(start)
603 step = len(start)
607 p.begin_group(step, start)
604 p.begin_group(step, start)
608 keys = obj.keys()
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 for idx, key in p._enumerate(keys):
606 for idx, key in p._enumerate(keys):
615 if idx:
607 if idx:
616 p.text(',')
608 p.text(',')
617 p.breakable()
609 p.breakable()
618 p.pretty(key)
610 p.pretty(key)
619 p.text(': ')
611 p.text(': ')
620 p.pretty(obj[key])
612 p.pretty(obj[key])
621 p.end_group(step, end)
613 p.end_group(step, end)
622 return inner
614 return inner
623
615
624
616
625 def _super_pprint(obj, p, cycle):
617 def _super_pprint(obj, p, cycle):
626 """The pprint for the super type."""
618 """The pprint for the super type."""
627 p.begin_group(8, '<super: ')
619 p.begin_group(8, '<super: ')
628 p.pretty(obj.__thisclass__)
620 p.pretty(obj.__thisclass__)
629 p.text(',')
621 p.text(',')
630 p.breakable()
622 p.breakable()
631 if PYPY: # In PyPy, super() objects don't have __self__ attributes
623 if PYPY: # In PyPy, super() objects don't have __self__ attributes
632 dself = obj.__repr__.__self__
624 dself = obj.__repr__.__self__
633 p.pretty(None if dself is obj else dself)
625 p.pretty(None if dself is obj else dself)
634 else:
626 else:
635 p.pretty(obj.__self__)
627 p.pretty(obj.__self__)
636 p.end_group(8, '>')
628 p.end_group(8, '>')
637
629
638
630
639 def _re_pattern_pprint(obj, p, cycle):
631 def _re_pattern_pprint(obj, p, cycle):
640 """The pprint function for regular expression patterns."""
632 """The pprint function for regular expression patterns."""
641 p.text('re.compile(')
633 p.text('re.compile(')
642 pattern = repr(obj.pattern)
634 pattern = repr(obj.pattern)
643 if pattern[:1] in 'uU':
635 if pattern[:1] in 'uU':
644 pattern = pattern[1:]
636 pattern = pattern[1:]
645 prefix = 'ur'
637 prefix = 'ur'
646 else:
638 else:
647 prefix = 'r'
639 prefix = 'r'
648 pattern = prefix + pattern.replace('\\\\', '\\')
640 pattern = prefix + pattern.replace('\\\\', '\\')
649 p.text(pattern)
641 p.text(pattern)
650 if obj.flags:
642 if obj.flags:
651 p.text(',')
643 p.text(',')
652 p.breakable()
644 p.breakable()
653 done_one = False
645 done_one = False
654 for flag in ('TEMPLATE', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL',
646 for flag in ('TEMPLATE', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL',
655 'UNICODE', 'VERBOSE', 'DEBUG'):
647 'UNICODE', 'VERBOSE', 'DEBUG'):
656 if obj.flags & getattr(re, flag):
648 if obj.flags & getattr(re, flag):
657 if done_one:
649 if done_one:
658 p.text('|')
650 p.text('|')
659 p.text('re.' + flag)
651 p.text('re.' + flag)
660 done_one = True
652 done_one = True
661 p.text(')')
653 p.text(')')
662
654
663
655
664 def _type_pprint(obj, p, cycle):
656 def _type_pprint(obj, p, cycle):
665 """The pprint for classes and types."""
657 """The pprint for classes and types."""
666 # Heap allocated types might not have the module attribute,
658 # Heap allocated types might not have the module attribute,
667 # and others may set it to None.
659 # and others may set it to None.
668
660
669 # Checks for a __repr__ override in the metaclass. Can't compare the
661 # Checks for a __repr__ override in the metaclass. Can't compare the
670 # type(obj).__repr__ directly because in PyPy the representation function
662 # type(obj).__repr__ directly because in PyPy the representation function
671 # inherited from type isn't the same type.__repr__
663 # inherited from type isn't the same type.__repr__
672 if [m for m in _get_mro(type(obj)) if "__repr__" in vars(m)][:1] != [type]:
664 if [m for m in _get_mro(type(obj)) if "__repr__" in vars(m)][:1] != [type]:
673 _repr_pprint(obj, p, cycle)
665 _repr_pprint(obj, p, cycle)
674 return
666 return
675
667
676 mod = _safe_getattr(obj, '__module__', None)
668 mod = _safe_getattr(obj, '__module__', None)
677 try:
669 try:
678 name = obj.__qualname__
670 name = obj.__qualname__
679 if not isinstance(name, str):
671 if not isinstance(name, str):
680 # This can happen if the type implements __qualname__ as a property
672 # This can happen if the type implements __qualname__ as a property
681 # or other descriptor in Python 2.
673 # or other descriptor in Python 2.
682 raise Exception("Try __name__")
674 raise Exception("Try __name__")
683 except Exception:
675 except Exception:
684 name = obj.__name__
676 name = obj.__name__
685 if not isinstance(name, str):
677 if not isinstance(name, str):
686 name = '<unknown type>'
678 name = '<unknown type>'
687
679
688 if mod in (None, '__builtin__', 'builtins', 'exceptions'):
680 if mod in (None, '__builtin__', 'builtins', 'exceptions'):
689 p.text(name)
681 p.text(name)
690 else:
682 else:
691 p.text(mod + '.' + name)
683 p.text(mod + '.' + name)
692
684
693
685
694 def _repr_pprint(obj, p, cycle):
686 def _repr_pprint(obj, p, cycle):
695 """A pprint that just redirects to the normal repr function."""
687 """A pprint that just redirects to the normal repr function."""
696 # Find newlines and replace them with p.break_()
688 # Find newlines and replace them with p.break_()
697 output = repr(obj)
689 output = repr(obj)
698 for idx,output_line in enumerate(output.splitlines()):
690 for idx,output_line in enumerate(output.splitlines()):
699 if idx:
691 if idx:
700 p.break_()
692 p.break_()
701 p.text(output_line)
693 p.text(output_line)
702
694
703
695
704 def _function_pprint(obj, p, cycle):
696 def _function_pprint(obj, p, cycle):
705 """Base pprint for all functions and builtin functions."""
697 """Base pprint for all functions and builtin functions."""
706 name = _safe_getattr(obj, '__qualname__', obj.__name__)
698 name = _safe_getattr(obj, '__qualname__', obj.__name__)
707 mod = obj.__module__
699 mod = obj.__module__
708 if mod and mod not in ('__builtin__', 'builtins', 'exceptions'):
700 if mod and mod not in ('__builtin__', 'builtins', 'exceptions'):
709 name = mod + '.' + name
701 name = mod + '.' + name
710 try:
702 try:
711 func_def = name + str(signature(obj))
703 func_def = name + str(signature(obj))
712 except ValueError:
704 except ValueError:
713 func_def = name
705 func_def = name
714 p.text('<function %s>' % func_def)
706 p.text('<function %s>' % func_def)
715
707
716
708
717 def _exception_pprint(obj, p, cycle):
709 def _exception_pprint(obj, p, cycle):
718 """Base pprint for all exceptions."""
710 """Base pprint for all exceptions."""
719 name = getattr(obj.__class__, '__qualname__', obj.__class__.__name__)
711 name = getattr(obj.__class__, '__qualname__', obj.__class__.__name__)
720 if obj.__class__.__module__ not in ('exceptions', 'builtins'):
712 if obj.__class__.__module__ not in ('exceptions', 'builtins'):
721 name = '%s.%s' % (obj.__class__.__module__, name)
713 name = '%s.%s' % (obj.__class__.__module__, name)
722 step = len(name) + 1
714 step = len(name) + 1
723 p.begin_group(step, name + '(')
715 p.begin_group(step, name + '(')
724 for idx, arg in enumerate(getattr(obj, 'args', ())):
716 for idx, arg in enumerate(getattr(obj, 'args', ())):
725 if idx:
717 if idx:
726 p.text(',')
718 p.text(',')
727 p.breakable()
719 p.breakable()
728 p.pretty(arg)
720 p.pretty(arg)
729 p.end_group(step, ')')
721 p.end_group(step, ')')
730
722
731
723
732 #: the exception base
724 #: the exception base
733 try:
725 try:
734 _exception_base = BaseException
726 _exception_base = BaseException
735 except NameError:
727 except NameError:
736 _exception_base = Exception
728 _exception_base = Exception
737
729
738
730
739 #: printers for builtin types
731 #: printers for builtin types
740 _type_pprinters = {
732 _type_pprinters = {
741 int: _repr_pprint,
733 int: _repr_pprint,
742 float: _repr_pprint,
734 float: _repr_pprint,
743 str: _repr_pprint,
735 str: _repr_pprint,
744 tuple: _seq_pprinter_factory('(', ')'),
736 tuple: _seq_pprinter_factory('(', ')'),
745 list: _seq_pprinter_factory('[', ']'),
737 list: _seq_pprinter_factory('[', ']'),
746 dict: _dict_pprinter_factory('{', '}'),
738 dict: _dict_pprinter_factory('{', '}'),
747 set: _set_pprinter_factory('{', '}'),
739 set: _set_pprinter_factory('{', '}'),
748 frozenset: _set_pprinter_factory('frozenset({', '})'),
740 frozenset: _set_pprinter_factory('frozenset({', '})'),
749 super: _super_pprint,
741 super: _super_pprint,
750 _re_pattern_type: _re_pattern_pprint,
742 _re_pattern_type: _re_pattern_pprint,
751 type: _type_pprint,
743 type: _type_pprint,
752 types.FunctionType: _function_pprint,
744 types.FunctionType: _function_pprint,
753 types.BuiltinFunctionType: _function_pprint,
745 types.BuiltinFunctionType: _function_pprint,
754 types.MethodType: _repr_pprint,
746 types.MethodType: _repr_pprint,
755 datetime.datetime: _repr_pprint,
747 datetime.datetime: _repr_pprint,
756 datetime.timedelta: _repr_pprint,
748 datetime.timedelta: _repr_pprint,
757 _exception_base: _exception_pprint
749 _exception_base: _exception_pprint
758 }
750 }
759
751
760 # render os.environ like a dict
752 # render os.environ like a dict
761 _env_type = type(os.environ)
753 _env_type = type(os.environ)
762 # future-proof in case os.environ becomes a plain dict?
754 # future-proof in case os.environ becomes a plain dict?
763 if _env_type is not dict:
755 if _env_type is not dict:
764 _type_pprinters[_env_type] = _dict_pprinter_factory('environ{', '}')
756 _type_pprinters[_env_type] = _dict_pprinter_factory('environ{', '}')
765
757
766 try:
758 try:
767 # In PyPy, types.DictProxyType is dict, setting the dictproxy printer
759 # In PyPy, types.DictProxyType is dict, setting the dictproxy printer
768 # using dict.setdefault avoids overwriting the dict printer
760 # using dict.setdefault avoids overwriting the dict printer
769 _type_pprinters.setdefault(types.DictProxyType,
761 _type_pprinters.setdefault(types.DictProxyType,
770 _dict_pprinter_factory('dict_proxy({', '})'))
762 _dict_pprinter_factory('dict_proxy({', '})'))
771 _type_pprinters[types.ClassType] = _type_pprint
763 _type_pprinters[types.ClassType] = _type_pprint
772 _type_pprinters[types.SliceType] = _repr_pprint
764 _type_pprinters[types.SliceType] = _repr_pprint
773 except AttributeError: # Python 3
765 except AttributeError: # Python 3
774 _type_pprinters[types.MappingProxyType] = \
766 _type_pprinters[types.MappingProxyType] = \
775 _dict_pprinter_factory('mappingproxy({', '})')
767 _dict_pprinter_factory('mappingproxy({', '})')
776 _type_pprinters[slice] = _repr_pprint
768 _type_pprinters[slice] = _repr_pprint
777
769
778 try:
770 try:
779 _type_pprinters[long] = _repr_pprint
771 _type_pprinters[long] = _repr_pprint
780 _type_pprinters[unicode] = _repr_pprint
772 _type_pprinters[unicode] = _repr_pprint
781 except NameError:
773 except NameError:
782 _type_pprinters[range] = _repr_pprint
774 _type_pprinters[range] = _repr_pprint
783 _type_pprinters[bytes] = _repr_pprint
775 _type_pprinters[bytes] = _repr_pprint
784
776
785 #: printers for types specified by name
777 #: printers for types specified by name
786 _deferred_type_pprinters = {
778 _deferred_type_pprinters = {
787 }
779 }
788
780
789 def for_type(typ, func):
781 def for_type(typ, func):
790 """
782 """
791 Add a pretty printer for a given type.
783 Add a pretty printer for a given type.
792 """
784 """
793 oldfunc = _type_pprinters.get(typ, None)
785 oldfunc = _type_pprinters.get(typ, None)
794 if func is not None:
786 if func is not None:
795 # To support easy restoration of old pprinters, we need to ignore Nones.
787 # To support easy restoration of old pprinters, we need to ignore Nones.
796 _type_pprinters[typ] = func
788 _type_pprinters[typ] = func
797 return oldfunc
789 return oldfunc
798
790
799 def for_type_by_name(type_module, type_name, func):
791 def for_type_by_name(type_module, type_name, func):
800 """
792 """
801 Add a pretty printer for a type specified by the module and name of a type
793 Add a pretty printer for a type specified by the module and name of a type
802 rather than the type object itself.
794 rather than the type object itself.
803 """
795 """
804 key = (type_module, type_name)
796 key = (type_module, type_name)
805 oldfunc = _deferred_type_pprinters.get(key, None)
797 oldfunc = _deferred_type_pprinters.get(key, None)
806 if func is not None:
798 if func is not None:
807 # To support easy restoration of old pprinters, we need to ignore Nones.
799 # To support easy restoration of old pprinters, we need to ignore Nones.
808 _deferred_type_pprinters[key] = func
800 _deferred_type_pprinters[key] = func
809 return oldfunc
801 return oldfunc
810
802
811
803
812 #: printers for the default singletons
804 #: printers for the default singletons
813 _singleton_pprinters = dict.fromkeys(map(id, [None, True, False, Ellipsis,
805 _singleton_pprinters = dict.fromkeys(map(id, [None, True, False, Ellipsis,
814 NotImplemented]), _repr_pprint)
806 NotImplemented]), _repr_pprint)
815
807
816
808
817 def _defaultdict_pprint(obj, p, cycle):
809 def _defaultdict_pprint(obj, p, cycle):
818 name = obj.__class__.__name__
810 name = obj.__class__.__name__
819 with p.group(len(name) + 1, name + '(', ')'):
811 with p.group(len(name) + 1, name + '(', ')'):
820 if cycle:
812 if cycle:
821 p.text('...')
813 p.text('...')
822 else:
814 else:
823 p.pretty(obj.default_factory)
815 p.pretty(obj.default_factory)
824 p.text(',')
816 p.text(',')
825 p.breakable()
817 p.breakable()
826 p.pretty(dict(obj))
818 p.pretty(dict(obj))
827
819
828 def _ordereddict_pprint(obj, p, cycle):
820 def _ordereddict_pprint(obj, p, cycle):
829 name = obj.__class__.__name__
821 name = obj.__class__.__name__
830 with p.group(len(name) + 1, name + '(', ')'):
822 with p.group(len(name) + 1, name + '(', ')'):
831 if cycle:
823 if cycle:
832 p.text('...')
824 p.text('...')
833 elif len(obj):
825 elif len(obj):
834 p.pretty(list(obj.items()))
826 p.pretty(list(obj.items()))
835
827
836 def _deque_pprint(obj, p, cycle):
828 def _deque_pprint(obj, p, cycle):
837 name = obj.__class__.__name__
829 name = obj.__class__.__name__
838 with p.group(len(name) + 1, name + '(', ')'):
830 with p.group(len(name) + 1, name + '(', ')'):
839 if cycle:
831 if cycle:
840 p.text('...')
832 p.text('...')
841 else:
833 else:
842 p.pretty(list(obj))
834 p.pretty(list(obj))
843
835
844
836
845 def _counter_pprint(obj, p, cycle):
837 def _counter_pprint(obj, p, cycle):
846 name = obj.__class__.__name__
838 name = obj.__class__.__name__
847 with p.group(len(name) + 1, name + '(', ')'):
839 with p.group(len(name) + 1, name + '(', ')'):
848 if cycle:
840 if cycle:
849 p.text('...')
841 p.text('...')
850 elif len(obj):
842 elif len(obj):
851 p.pretty(dict(obj))
843 p.pretty(dict(obj))
852
844
853 for_type_by_name('collections', 'defaultdict', _defaultdict_pprint)
845 for_type_by_name('collections', 'defaultdict', _defaultdict_pprint)
854 for_type_by_name('collections', 'OrderedDict', _ordereddict_pprint)
846 for_type_by_name('collections', 'OrderedDict', _ordereddict_pprint)
855 for_type_by_name('collections', 'deque', _deque_pprint)
847 for_type_by_name('collections', 'deque', _deque_pprint)
856 for_type_by_name('collections', 'Counter', _counter_pprint)
848 for_type_by_name('collections', 'Counter', _counter_pprint)
857
849
858 if __name__ == '__main__':
850 if __name__ == '__main__':
859 from random import randrange
851 from random import randrange
860 class Foo(object):
852 class Foo(object):
861 def __init__(self):
853 def __init__(self):
862 self.foo = 1
854 self.foo = 1
863 self.bar = re.compile(r'\s+')
855 self.bar = re.compile(r'\s+')
864 self.blub = dict.fromkeys(range(30), randrange(1, 40))
856 self.blub = dict.fromkeys(range(30), randrange(1, 40))
865 self.hehe = 23424.234234
857 self.hehe = 23424.234234
866 self.list = ["blub", "blah", self]
858 self.list = ["blub", "blah", self]
867
859
868 def get_foo(self):
860 def get_foo(self):
869 print("foo")
861 print("foo")
870
862
871 pprint(Foo(), verbose=True)
863 pprint(Foo(), verbose=True)
@@ -1,119 +1,119 b''
1 """Find files and directories which IPython uses.
1 """Find files and directories which IPython uses.
2 """
2 """
3 import os.path
3 import os.path
4 import shutil
4 import shutil
5 import tempfile
5 import tempfile
6 from warnings import warn
6 from warnings import warn
7
7
8 import IPython
8 import IPython
9 from IPython.utils.importstring import import_item
9 from IPython.utils.importstring import import_item
10 from IPython.utils.path import (
10 from IPython.utils.path import (
11 get_home_dir, get_xdg_dir, get_xdg_cache_dir, compress_user, _writable_dir,
11 get_home_dir, get_xdg_dir, get_xdg_cache_dir, compress_user, _writable_dir,
12 ensure_dir_exists, fs_encoding)
12 ensure_dir_exists, fs_encoding)
13 from IPython.utils import py3compat
13 from IPython.utils import py3compat
14
14
15 def get_ipython_dir():
15 def get_ipython_dir() -> str:
16 """Get the IPython directory for this platform and user.
16 """Get the IPython directory for this platform and user.
17
17
18 This uses the logic in `get_home_dir` to find the home directory
18 This uses the logic in `get_home_dir` to find the home directory
19 and then adds .ipython to the end of the path.
19 and then adds .ipython to the end of the path.
20 """
20 """
21
21
22 env = os.environ
22 env = os.environ
23 pjoin = os.path.join
23 pjoin = os.path.join
24
24
25
25
26 ipdir_def = '.ipython'
26 ipdir_def = '.ipython'
27
27
28 home_dir = get_home_dir()
28 home_dir = get_home_dir()
29 xdg_dir = get_xdg_dir()
29 xdg_dir = get_xdg_dir()
30
30
31 # import pdb; pdb.set_trace() # dbg
32 if 'IPYTHON_DIR' in env:
31 if 'IPYTHON_DIR' in env:
33 warn('The environment variable IPYTHON_DIR is deprecated. '
32 warn('The environment variable IPYTHON_DIR is deprecated since IPython 3.0. '
34 'Please use IPYTHONDIR instead.')
33 'Please use IPYTHONDIR instead.', DeprecationWarning)
35 ipdir = env.get('IPYTHONDIR', env.get('IPYTHON_DIR', None))
34 ipdir = env.get('IPYTHONDIR', env.get('IPYTHON_DIR', None))
36 if ipdir is None:
35 if ipdir is None:
37 # not set explicitly, use ~/.ipython
36 # not set explicitly, use ~/.ipython
38 ipdir = pjoin(home_dir, ipdir_def)
37 ipdir = pjoin(home_dir, ipdir_def)
39 if xdg_dir:
38 if xdg_dir:
40 # Several IPython versions (up to 1.x) defaulted to .config/ipython
39 # Several IPython versions (up to 1.x) defaulted to .config/ipython
41 # on Linux. We have decided to go back to using .ipython everywhere
40 # on Linux. We have decided to go back to using .ipython everywhere
42 xdg_ipdir = pjoin(xdg_dir, 'ipython')
41 xdg_ipdir = pjoin(xdg_dir, 'ipython')
43
42
44 if _writable_dir(xdg_ipdir):
43 if _writable_dir(xdg_ipdir):
45 cu = compress_user
44 cu = compress_user
46 if os.path.exists(ipdir):
45 if os.path.exists(ipdir):
47 warn(('Ignoring {0} in favour of {1}. Remove {0} to '
46 warn(('Ignoring {0} in favour of {1}. Remove {0} to '
48 'get rid of this message').format(cu(xdg_ipdir), cu(ipdir)))
47 'get rid of this message').format(cu(xdg_ipdir), cu(ipdir)))
49 elif os.path.islink(xdg_ipdir):
48 elif os.path.islink(xdg_ipdir):
50 warn(('{0} is deprecated. Move link to {1} to '
49 warn(('{0} is deprecated. Move link to {1} to '
51 'get rid of this message').format(cu(xdg_ipdir), cu(ipdir)))
50 'get rid of this message').format(cu(xdg_ipdir), cu(ipdir)))
52 else:
51 else:
53 warn('Moving {0} to {1}'.format(cu(xdg_ipdir), cu(ipdir)))
52 warn('Moving {0} to {1}'.format(cu(xdg_ipdir), cu(ipdir)))
54 shutil.move(xdg_ipdir, ipdir)
53 shutil.move(xdg_ipdir, ipdir)
55
54
56 ipdir = os.path.normpath(os.path.expanduser(ipdir))
55 ipdir = os.path.normpath(os.path.expanduser(ipdir))
57
56
58 if os.path.exists(ipdir) and not _writable_dir(ipdir):
57 if os.path.exists(ipdir) and not _writable_dir(ipdir):
59 # ipdir exists, but is not writable
58 # ipdir exists, but is not writable
60 warn("IPython dir '{0}' is not a writable location,"
59 warn("IPython dir '{0}' is not a writable location,"
61 " using a temp directory.".format(ipdir))
60 " using a temp directory.".format(ipdir))
62 ipdir = tempfile.mkdtemp()
61 ipdir = tempfile.mkdtemp()
63 elif not os.path.exists(ipdir):
62 elif not os.path.exists(ipdir):
64 parent = os.path.dirname(ipdir)
63 parent = os.path.dirname(ipdir)
65 if not _writable_dir(parent):
64 if not _writable_dir(parent):
66 # ipdir does not exist and parent isn't writable
65 # ipdir does not exist and parent isn't writable
67 warn("IPython parent '{0}' is not a writable location,"
66 warn("IPython parent '{0}' is not a writable location,"
68 " using a temp directory.".format(parent))
67 " using a temp directory.".format(parent))
69 ipdir = tempfile.mkdtemp()
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
73 def get_ipython_cache_dir() -> str:
74 def get_ipython_cache_dir():
75 """Get the cache directory it is created if it does not exist."""
74 """Get the cache directory it is created if it does not exist."""
76 xdgdir = get_xdg_cache_dir()
75 xdgdir = get_xdg_cache_dir()
77 if xdgdir is None:
76 if xdgdir is None:
78 return get_ipython_dir()
77 return get_ipython_dir()
79 ipdir = os.path.join(xdgdir, "ipython")
78 ipdir = os.path.join(xdgdir, "ipython")
80 if not os.path.exists(ipdir) and _writable_dir(xdgdir):
79 if not os.path.exists(ipdir) and _writable_dir(xdgdir):
81 ensure_dir_exists(ipdir)
80 ensure_dir_exists(ipdir)
82 elif not _writable_dir(xdgdir):
81 elif not _writable_dir(xdgdir):
83 return get_ipython_dir()
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 """Get the base directory where IPython itself is installed."""
88 """Get the base directory where IPython itself is installed."""
90 ipdir = os.path.dirname(IPython.__file__)
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 def get_ipython_module_path(module_str):
94 def get_ipython_module_path(module_str):
95 """Find the path to an IPython module in this version of IPython.
95 """Find the path to an IPython module in this version of IPython.
96
96
97 This will always find the version of the module that is in this importable
97 This will always find the version of the module that is in this importable
98 IPython package. This will always return the path to the ``.py``
98 IPython package. This will always return the path to the ``.py``
99 version of the module.
99 version of the module.
100 """
100 """
101 if module_str == 'IPython':
101 if module_str == 'IPython':
102 return os.path.join(get_ipython_package_dir(), '__init__.py')
102 return os.path.join(get_ipython_package_dir(), '__init__.py')
103 mod = import_item(module_str)
103 mod = import_item(module_str)
104 the_path = mod.__file__.replace('.pyc', '.py')
104 the_path = mod.__file__.replace('.pyc', '.py')
105 the_path = the_path.replace('.pyo', '.py')
105 the_path = the_path.replace('.pyo', '.py')
106 return py3compat.cast_unicode(the_path, fs_encoding)
106 return py3compat.cast_unicode(the_path, fs_encoding)
107
107
108 def locate_profile(profile='default'):
108 def locate_profile(profile='default'):
109 """Find the path to the folder associated with a given profile.
109 """Find the path to the folder associated with a given profile.
110
110
111 I.e. find $IPYTHONDIR/profile_whatever.
111 I.e. find $IPYTHONDIR/profile_whatever.
112 """
112 """
113 from IPython.core.profiledir import ProfileDir, ProfileDirError
113 from IPython.core.profiledir import ProfileDir, ProfileDirError
114 try:
114 try:
115 pd = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile)
115 pd = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile)
116 except ProfileDirError:
116 except ProfileDirError:
117 # IOError makes more sense when people are expecting a path
117 # IOError makes more sense when people are expecting a path
118 raise IOError("Couldn't find profile %r" % profile)
118 raise IOError("Couldn't find profile %r" % profile)
119 return pd.location
119 return pd.location
@@ -1,120 +1,126 b''
1 import signal
1 import signal
2 import sys
2 import sys
3
3
4 from IPython.core.debugger import Pdb
4 from IPython.core.debugger import Pdb
5
5
6 from IPython.core.completer import IPCompleter
6 from IPython.core.completer import IPCompleter
7 from .ptutils import IPythonPTCompleter
7 from .ptutils import IPythonPTCompleter
8 from .shortcuts import suspend_to_bg, cursor_in_leading_ws
8 from .shortcuts import suspend_to_bg, cursor_in_leading_ws
9
9
10 from prompt_toolkit.enums import DEFAULT_BUFFER
10 from prompt_toolkit.enums import DEFAULT_BUFFER
11 from prompt_toolkit.filters import (Condition, has_focus, has_selection,
11 from prompt_toolkit.filters import (Condition, has_focus, has_selection,
12 vi_insert_mode, emacs_insert_mode)
12 vi_insert_mode, emacs_insert_mode)
13 from prompt_toolkit.key_binding import KeyBindings
13 from prompt_toolkit.key_binding import KeyBindings
14 from prompt_toolkit.key_binding.bindings.completion import display_completions_like_readline
14 from prompt_toolkit.key_binding.bindings.completion import display_completions_like_readline
15 from pygments.token import Token
15 from pygments.token import Token
16 from prompt_toolkit.shortcuts.prompt import PromptSession
16 from prompt_toolkit.shortcuts.prompt import PromptSession
17 from prompt_toolkit.enums import EditingMode
17 from prompt_toolkit.enums import EditingMode
18 from prompt_toolkit.formatted_text import PygmentsTokens
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 class TerminalPdb(Pdb):
24 class TerminalPdb(Pdb):
22 """Standalone IPython debugger."""
25 """Standalone IPython debugger."""
23
26
24 def __init__(self, *args, **kwargs):
27 def __init__(self, *args, **kwargs):
25 Pdb.__init__(self, *args, **kwargs)
28 Pdb.__init__(self, *args, **kwargs)
26 self._ptcomp = None
29 self._ptcomp = None
27 self.pt_init()
30 self.pt_init()
28
31
29 def pt_init(self):
32 def pt_init(self):
30 def get_prompt_tokens():
33 def get_prompt_tokens():
31 return [(Token.Prompt, self.prompt)]
34 return [(Token.Prompt, self.prompt)]
32
35
33 if self._ptcomp is None:
36 if self._ptcomp is None:
34 compl = IPCompleter(shell=self.shell,
37 compl = IPCompleter(shell=self.shell,
35 namespace={},
38 namespace={},
36 global_namespace={},
39 global_namespace={},
37 parent=self.shell,
40 parent=self.shell,
38 )
41 )
39 self._ptcomp = IPythonPTCompleter(compl)
42 self._ptcomp = IPythonPTCompleter(compl)
40
43
41 kb = KeyBindings()
44 kb = KeyBindings()
42 supports_suspend = Condition(lambda: hasattr(signal, 'SIGTSTP'))
45 supports_suspend = Condition(lambda: hasattr(signal, 'SIGTSTP'))
43 kb.add('c-z', filter=supports_suspend)(suspend_to_bg)
46 kb.add('c-z', filter=supports_suspend)(suspend_to_bg)
44
47
45 if self.shell.display_completions == 'readlinelike':
48 if self.shell.display_completions == 'readlinelike':
46 kb.add('tab', filter=(has_focus(DEFAULT_BUFFER)
49 kb.add('tab', filter=(has_focus(DEFAULT_BUFFER)
47 & ~has_selection
50 & ~has_selection
48 & vi_insert_mode | emacs_insert_mode
51 & vi_insert_mode | emacs_insert_mode
49 & ~cursor_in_leading_ws
52 & ~cursor_in_leading_ws
50 ))(display_completions_like_readline)
53 ))(display_completions_like_readline)
51
54
52 self.pt_app = PromptSession(
55 options = dict(
53 message=(lambda: PygmentsTokens(get_prompt_tokens())),
56 message=(lambda: PygmentsTokens(get_prompt_tokens())),
54 editing_mode=getattr(EditingMode, self.shell.editing_mode.upper()),
57 editing_mode=getattr(EditingMode, self.shell.editing_mode.upper()),
55 key_bindings=kb,
58 key_bindings=kb,
56 history=self.shell.debugger_history,
59 history=self.shell.debugger_history,
57 completer=self._ptcomp,
60 completer=self._ptcomp,
58 enable_history_search=True,
61 enable_history_search=True,
59 mouse_support=self.shell.mouse_support,
62 mouse_support=self.shell.mouse_support,
60 complete_style=self.shell.pt_complete_style,
63 complete_style=self.shell.pt_complete_style,
61 style=self.shell.style,
64 style=self.shell.style,
62 inputhook=self.shell.inputhook,
63 color_depth=self.shell.color_depth,
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 def cmdloop(self, intro=None):
72 def cmdloop(self, intro=None):
67 """Repeatedly issue a prompt, accept input, parse an initial prefix
73 """Repeatedly issue a prompt, accept input, parse an initial prefix
68 off the received input, and dispatch to action methods, passing them
74 off the received input, and dispatch to action methods, passing them
69 the remainder of the line as argument.
75 the remainder of the line as argument.
70
76
71 override the same methods from cmd.Cmd to provide prompt toolkit replacement.
77 override the same methods from cmd.Cmd to provide prompt toolkit replacement.
72 """
78 """
73 if not self.use_rawinput:
79 if not self.use_rawinput:
74 raise ValueError('Sorry ipdb does not support use_rawinput=False')
80 raise ValueError('Sorry ipdb does not support use_rawinput=False')
75
81
76 self.preloop()
82 self.preloop()
77
83
78 try:
84 try:
79 if intro is not None:
85 if intro is not None:
80 self.intro = intro
86 self.intro = intro
81 if self.intro:
87 if self.intro:
82 self.stdout.write(str(self.intro)+"\n")
88 self.stdout.write(str(self.intro)+"\n")
83 stop = None
89 stop = None
84 while not stop:
90 while not stop:
85 if self.cmdqueue:
91 if self.cmdqueue:
86 line = self.cmdqueue.pop(0)
92 line = self.cmdqueue.pop(0)
87 else:
93 else:
88 self._ptcomp.ipy_completer.namespace = self.curframe_locals
94 self._ptcomp.ipy_completer.namespace = self.curframe_locals
89 self._ptcomp.ipy_completer.global_namespace = self.curframe.f_globals
95 self._ptcomp.ipy_completer.global_namespace = self.curframe.f_globals
90 try:
96 try:
91 line = self.pt_app.prompt() # reset_current_buffer=True)
97 line = self.pt_app.prompt() # reset_current_buffer=True)
92 except EOFError:
98 except EOFError:
93 line = 'EOF'
99 line = 'EOF'
94 line = self.precmd(line)
100 line = self.precmd(line)
95 stop = self.onecmd(line)
101 stop = self.onecmd(line)
96 stop = self.postcmd(stop, line)
102 stop = self.postcmd(stop, line)
97 self.postloop()
103 self.postloop()
98 except Exception:
104 except Exception:
99 raise
105 raise
100
106
101
107
102 def set_trace(frame=None):
108 def set_trace(frame=None):
103 """
109 """
104 Start debugging from `frame`.
110 Start debugging from `frame`.
105
111
106 If frame is not specified, debugging starts from caller's frame.
112 If frame is not specified, debugging starts from caller's frame.
107 """
113 """
108 TerminalPdb().set_trace(frame or sys._getframe().f_back)
114 TerminalPdb().set_trace(frame or sys._getframe().f_back)
109
115
110
116
111 if __name__ == '__main__':
117 if __name__ == '__main__':
112 import pdb
118 import pdb
113 # IPython.core.debugger.Pdb.trace_dispatch shall not catch
119 # IPython.core.debugger.Pdb.trace_dispatch shall not catch
114 # bdb.BdbQuit. When started through __main__ and an exception
120 # bdb.BdbQuit. When started through __main__ and an exception
115 # happened after hitting "c", this is needed in order to
121 # happened after hitting "c", this is needed in order to
116 # be able to quit the debugging session (see #9950).
122 # be able to quit the debugging session (see #9950).
117 old_trace_dispatch = pdb.Pdb.trace_dispatch
123 old_trace_dispatch = pdb.Pdb.trace_dispatch
118 pdb.Pdb = TerminalPdb
124 pdb.Pdb = TerminalPdb
119 pdb.Pdb.trace_dispatch = old_trace_dispatch
125 pdb.Pdb.trace_dispatch = old_trace_dispatch
120 pdb.main()
126 pdb.main()
@@ -1,570 +1,640 b''
1 """IPython terminal interface using prompt_toolkit"""
1 """IPython terminal interface using prompt_toolkit"""
2
2
3 import asyncio
3 import os
4 import os
4 import sys
5 import sys
5 import warnings
6 import warnings
6 from warnings import warn
7 from warnings import warn
7
8
8 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
9 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
9 from IPython.utils import io
10 from IPython.utils import io
10 from IPython.utils.py3compat import input
11 from IPython.utils.py3compat import input
11 from IPython.utils.terminal import toggle_set_term_title, set_term_title, restore_term_title
12 from IPython.utils.terminal import toggle_set_term_title, set_term_title, restore_term_title
12 from IPython.utils.process import abbrev_cwd
13 from IPython.utils.process import abbrev_cwd
13 from traitlets import (
14 from traitlets import (
14 Bool, Unicode, Dict, Integer, observe, Instance, Type, default, Enum, Union,
15 Bool, Unicode, Dict, Integer, observe, Instance, Type, default, Enum, Union,
15 Any, validate
16 Any, validate
16 )
17 )
17
18
18 from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode
19 from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode
19 from prompt_toolkit.filters import (HasFocus, Condition, IsDone)
20 from prompt_toolkit.filters import (HasFocus, Condition, IsDone)
20 from prompt_toolkit.formatted_text import PygmentsTokens
21 from prompt_toolkit.formatted_text import PygmentsTokens
21 from prompt_toolkit.history import InMemoryHistory
22 from prompt_toolkit.history import InMemoryHistory
22 from prompt_toolkit.layout.processors import ConditionalProcessor, HighlightMatchingBracketProcessor
23 from prompt_toolkit.layout.processors import ConditionalProcessor, HighlightMatchingBracketProcessor
23 from prompt_toolkit.output import ColorDepth
24 from prompt_toolkit.output import ColorDepth
24 from prompt_toolkit.patch_stdout import patch_stdout
25 from prompt_toolkit.patch_stdout import patch_stdout
25 from prompt_toolkit.shortcuts import PromptSession, CompleteStyle, print_formatted_text
26 from prompt_toolkit.shortcuts import PromptSession, CompleteStyle, print_formatted_text
26 from prompt_toolkit.styles import DynamicStyle, merge_styles
27 from prompt_toolkit.styles import DynamicStyle, merge_styles
27 from prompt_toolkit.styles.pygments import style_from_pygments_cls, style_from_pygments_dict
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 from pygments.styles import get_style_by_name
31 from pygments.styles import get_style_by_name
30 from pygments.style import Style
32 from pygments.style import Style
31 from pygments.token import Token
33 from pygments.token import Token
32
34
33 from .debugger import TerminalPdb, Pdb
35 from .debugger import TerminalPdb, Pdb
34 from .magics import TerminalMagics
36 from .magics import TerminalMagics
35 from .pt_inputhooks import get_inputhook_name_and_func
37 from .pt_inputhooks import get_inputhook_name_and_func
36 from .prompts import Prompts, ClassicPrompts, RichPromptDisplayHook
38 from .prompts import Prompts, ClassicPrompts, RichPromptDisplayHook
37 from .ptutils import IPythonPTCompleter, IPythonPTLexer
39 from .ptutils import IPythonPTCompleter, IPythonPTLexer
38 from .shortcuts import create_ipython_shortcuts
40 from .shortcuts import create_ipython_shortcuts
39
41
40 DISPLAY_BANNER_DEPRECATED = object()
42 DISPLAY_BANNER_DEPRECATED = object()
43 PTK3 = ptk_version.startswith('3.')
41
44
42
45
43 class _NoStyle(Style): pass
46 class _NoStyle(Style): pass
44
47
45
48
46
49
47 _style_overrides_light_bg = {
50 _style_overrides_light_bg = {
48 Token.Prompt: '#0000ff',
51 Token.Prompt: '#0000ff',
49 Token.PromptNum: '#0000ee bold',
52 Token.PromptNum: '#0000ee bold',
50 Token.OutPrompt: '#cc0000',
53 Token.OutPrompt: '#cc0000',
51 Token.OutPromptNum: '#bb0000 bold',
54 Token.OutPromptNum: '#bb0000 bold',
52 }
55 }
53
56
54 _style_overrides_linux = {
57 _style_overrides_linux = {
55 Token.Prompt: '#00cc00',
58 Token.Prompt: '#00cc00',
56 Token.PromptNum: '#00bb00 bold',
59 Token.PromptNum: '#00bb00 bold',
57 Token.OutPrompt: '#cc0000',
60 Token.OutPrompt: '#cc0000',
58 Token.OutPromptNum: '#bb0000 bold',
61 Token.OutPromptNum: '#bb0000 bold',
59 }
62 }
60
63
61 def get_default_editor():
64 def get_default_editor():
62 try:
65 try:
63 return os.environ['EDITOR']
66 return os.environ['EDITOR']
64 except KeyError:
67 except KeyError:
65 pass
68 pass
66 except UnicodeError:
69 except UnicodeError:
67 warn("$EDITOR environment variable is not pure ASCII. Using platform "
70 warn("$EDITOR environment variable is not pure ASCII. Using platform "
68 "default editor.")
71 "default editor.")
69
72
70 if os.name == 'posix':
73 if os.name == 'posix':
71 return 'vi' # the only one guaranteed to be there!
74 return 'vi' # the only one guaranteed to be there!
72 else:
75 else:
73 return 'notepad' # same in Windows!
76 return 'notepad' # same in Windows!
74
77
75 # conservatively check for tty
78 # conservatively check for tty
76 # overridden streams can result in things like:
79 # overridden streams can result in things like:
77 # - sys.stdin = None
80 # - sys.stdin = None
78 # - no isatty method
81 # - no isatty method
79 for _name in ('stdin', 'stdout', 'stderr'):
82 for _name in ('stdin', 'stdout', 'stderr'):
80 _stream = getattr(sys, _name)
83 _stream = getattr(sys, _name)
81 if not _stream or not hasattr(_stream, 'isatty') or not _stream.isatty():
84 if not _stream or not hasattr(_stream, 'isatty') or not _stream.isatty():
82 _is_tty = False
85 _is_tty = False
83 break
86 break
84 else:
87 else:
85 _is_tty = True
88 _is_tty = True
86
89
87
90
88 _use_simple_prompt = ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or (not _is_tty)
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 class TerminalInteractiveShell(InteractiveShell):
101 class TerminalInteractiveShell(InteractiveShell):
102 mime_renderers = Dict().tag(config=True)
103
91 space_for_menu = Integer(6, help='Number of line at the bottom of the screen '
104 space_for_menu = Integer(6, help='Number of line at the bottom of the screen '
92 'to reserve for the completion menu'
105 'to reserve for the completion menu'
93 ).tag(config=True)
106 ).tag(config=True)
94
107
95 pt_app = None
108 pt_app = None
96 debugger_history = None
109 debugger_history = None
97
110
98 simple_prompt = Bool(_use_simple_prompt,
111 simple_prompt = Bool(_use_simple_prompt,
99 help="""Use `raw_input` for the REPL, without completion and prompt colors.
112 help="""Use `raw_input` for the REPL, without completion and prompt colors.
100
113
101 Useful when controlling IPython as a subprocess, and piping STDIN/OUT/ERR. Known usage are:
114 Useful when controlling IPython as a subprocess, and piping STDIN/OUT/ERR. Known usage are:
102 IPython own testing machinery, and emacs inferior-shell integration through elpy.
115 IPython own testing machinery, and emacs inferior-shell integration through elpy.
103
116
104 This mode default to `True` if the `IPY_TEST_SIMPLE_PROMPT`
117 This mode default to `True` if the `IPY_TEST_SIMPLE_PROMPT`
105 environment variable is set, or the current terminal is not a tty."""
118 environment variable is set, or the current terminal is not a tty."""
106 ).tag(config=True)
119 ).tag(config=True)
107
120
108 @property
121 @property
109 def debugger_cls(self):
122 def debugger_cls(self):
110 return Pdb if self.simple_prompt else TerminalPdb
123 return Pdb if self.simple_prompt else TerminalPdb
111
124
112 confirm_exit = Bool(True,
125 confirm_exit = Bool(True,
113 help="""
126 help="""
114 Set to confirm when you try to exit IPython with an EOF (Control-D
127 Set to confirm when you try to exit IPython with an EOF (Control-D
115 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
128 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
116 you can force a direct exit without any confirmation.""",
129 you can force a direct exit without any confirmation.""",
117 ).tag(config=True)
130 ).tag(config=True)
118
131
119 editing_mode = Unicode('emacs',
132 editing_mode = Unicode('emacs',
120 help="Shortcut style to use at the prompt. 'vi' or 'emacs'.",
133 help="Shortcut style to use at the prompt. 'vi' or 'emacs'.",
121 ).tag(config=True)
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 mouse_support = Bool(False,
141 mouse_support = Bool(False,
124 help="Enable mouse support in the prompt\n(Note: prevents selecting text with the mouse)"
142 help="Enable mouse support in the prompt\n(Note: prevents selecting text with the mouse)"
125 ).tag(config=True)
143 ).tag(config=True)
126
144
127 # We don't load the list of styles for the help string, because loading
145 # We don't load the list of styles for the help string, because loading
128 # Pygments plugins takes time and can cause unexpected errors.
146 # Pygments plugins takes time and can cause unexpected errors.
129 highlighting_style = Union([Unicode('legacy'), Type(klass=Style)],
147 highlighting_style = Union([Unicode('legacy'), Type(klass=Style)],
130 help="""The name or class of a Pygments style to use for syntax
148 help="""The name or class of a Pygments style to use for syntax
131 highlighting. To see available styles, run `pygmentize -L styles`."""
149 highlighting. To see available styles, run `pygmentize -L styles`."""
132 ).tag(config=True)
150 ).tag(config=True)
133
151
134 @validate('editing_mode')
152 @validate('editing_mode')
135 def _validate_editing_mode(self, proposal):
153 def _validate_editing_mode(self, proposal):
136 if proposal['value'].lower() == 'vim':
154 if proposal['value'].lower() == 'vim':
137 proposal['value']= 'vi'
155 proposal['value']= 'vi'
138 elif proposal['value'].lower() == 'default':
156 elif proposal['value'].lower() == 'default':
139 proposal['value']= 'emacs'
157 proposal['value']= 'emacs'
140
158
141 if hasattr(EditingMode, proposal['value'].upper()):
159 if hasattr(EditingMode, proposal['value'].upper()):
142 return proposal['value'].lower()
160 return proposal['value'].lower()
143
161
144 return self.editing_mode
162 return self.editing_mode
145
163
146
164
147 @observe('editing_mode')
165 @observe('editing_mode')
148 def _editing_mode(self, change):
166 def _editing_mode(self, change):
149 u_mode = change.new.upper()
167 u_mode = change.new.upper()
150 if self.pt_app:
168 if self.pt_app:
151 self.pt_app.editing_mode = u_mode
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 @observe('highlighting_style')
181 @observe('highlighting_style')
154 @observe('colors')
182 @observe('colors')
155 def _highlighting_style_changed(self, change):
183 def _highlighting_style_changed(self, change):
156 self.refresh_style()
184 self.refresh_style()
157
185
158 def refresh_style(self):
186 def refresh_style(self):
159 self._style = self._make_style_from_name_or_cls(self.highlighting_style)
187 self._style = self._make_style_from_name_or_cls(self.highlighting_style)
160
188
161
189
162 highlighting_style_overrides = Dict(
190 highlighting_style_overrides = Dict(
163 help="Override highlighting format for specific tokens"
191 help="Override highlighting format for specific tokens"
164 ).tag(config=True)
192 ).tag(config=True)
165
193
166 true_color = Bool(False,
194 true_color = Bool(False,
167 help=("Use 24bit colors instead of 256 colors in prompt highlighting. "
195 help=("Use 24bit colors instead of 256 colors in prompt highlighting. "
168 "If your terminal supports true color, the following command "
196 "If your terminal supports true color, the following command "
169 "should print 'TRUECOLOR' in orange: "
197 "should print 'TRUECOLOR' in orange: "
170 "printf \"\\x1b[38;2;255;100;0mTRUECOLOR\\x1b[0m\\n\"")
198 "printf \"\\x1b[38;2;255;100;0mTRUECOLOR\\x1b[0m\\n\"")
171 ).tag(config=True)
199 ).tag(config=True)
172
200
173 editor = Unicode(get_default_editor(),
201 editor = Unicode(get_default_editor(),
174 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
202 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
175 ).tag(config=True)
203 ).tag(config=True)
176
204
177 prompts_class = Type(Prompts, help='Class used to generate Prompt token for prompt_toolkit').tag(config=True)
205 prompts_class = Type(Prompts, help='Class used to generate Prompt token for prompt_toolkit').tag(config=True)
178
206
179 prompts = Instance(Prompts)
207 prompts = Instance(Prompts)
180
208
181 @default('prompts')
209 @default('prompts')
182 def _prompts_default(self):
210 def _prompts_default(self):
183 return self.prompts_class(self)
211 return self.prompts_class(self)
184
212
185 # @observe('prompts')
213 # @observe('prompts')
186 # def _(self, change):
214 # def _(self, change):
187 # self._update_layout()
215 # self._update_layout()
188
216
189 @default('displayhook_class')
217 @default('displayhook_class')
190 def _displayhook_class_default(self):
218 def _displayhook_class_default(self):
191 return RichPromptDisplayHook
219 return RichPromptDisplayHook
192
220
193 term_title = Bool(True,
221 term_title = Bool(True,
194 help="Automatically set the terminal title"
222 help="Automatically set the terminal title"
195 ).tag(config=True)
223 ).tag(config=True)
196
224
197 term_title_format = Unicode("IPython: {cwd}",
225 term_title_format = Unicode("IPython: {cwd}",
198 help="Customize the terminal title format. This is a python format string. " +
226 help="Customize the terminal title format. This is a python format string. " +
199 "Available substitutions are: {cwd}."
227 "Available substitutions are: {cwd}."
200 ).tag(config=True)
228 ).tag(config=True)
201
229
202 display_completions = Enum(('column', 'multicolumn','readlinelike'),
230 display_completions = Enum(('column', 'multicolumn','readlinelike'),
203 help= ( "Options for displaying tab completions, 'column', 'multicolumn', and "
231 help= ( "Options for displaying tab completions, 'column', 'multicolumn', and "
204 "'readlinelike'. These options are for `prompt_toolkit`, see "
232 "'readlinelike'. These options are for `prompt_toolkit`, see "
205 "`prompt_toolkit` documentation for more information."
233 "`prompt_toolkit` documentation for more information."
206 ),
234 ),
207 default_value='multicolumn').tag(config=True)
235 default_value='multicolumn').tag(config=True)
208
236
209 highlight_matching_brackets = Bool(True,
237 highlight_matching_brackets = Bool(True,
210 help="Highlight matching brackets.",
238 help="Highlight matching brackets.",
211 ).tag(config=True)
239 ).tag(config=True)
212
240
213 extra_open_editor_shortcuts = Bool(False,
241 extra_open_editor_shortcuts = Bool(False,
214 help="Enable vi (v) or Emacs (C-X C-E) shortcuts to open an external editor. "
242 help="Enable vi (v) or Emacs (C-X C-E) shortcuts to open an external editor. "
215 "This is in addition to the F2 binding, which is always enabled."
243 "This is in addition to the F2 binding, which is always enabled."
216 ).tag(config=True)
244 ).tag(config=True)
217
245
218 handle_return = Any(None,
246 handle_return = Any(None,
219 help="Provide an alternative handler to be called when the user presses "
247 help="Provide an alternative handler to be called when the user presses "
220 "Return. This is an advanced option intended for debugging, which "
248 "Return. This is an advanced option intended for debugging, which "
221 "may be changed or removed in later releases."
249 "may be changed or removed in later releases."
222 ).tag(config=True)
250 ).tag(config=True)
223
251
224 enable_history_search = Bool(True,
252 enable_history_search = Bool(True,
225 help="Allows to enable/disable the prompt toolkit history search"
253 help="Allows to enable/disable the prompt toolkit history search"
226 ).tag(config=True)
254 ).tag(config=True)
227
255
228 prompt_includes_vi_mode = Bool(True,
256 prompt_includes_vi_mode = Bool(True,
229 help="Display the current vi mode (when using vi editing mode)."
257 help="Display the current vi mode (when using vi editing mode)."
230 ).tag(config=True)
258 ).tag(config=True)
231
259
232 @observe('term_title')
260 @observe('term_title')
233 def init_term_title(self, change=None):
261 def init_term_title(self, change=None):
234 # Enable or disable the terminal title.
262 # Enable or disable the terminal title.
235 if self.term_title:
263 if self.term_title:
236 toggle_set_term_title(True)
264 toggle_set_term_title(True)
237 set_term_title(self.term_title_format.format(cwd=abbrev_cwd()))
265 set_term_title(self.term_title_format.format(cwd=abbrev_cwd()))
238 else:
266 else:
239 toggle_set_term_title(False)
267 toggle_set_term_title(False)
240
268
241 def restore_term_title(self):
269 def restore_term_title(self):
242 if self.term_title:
270 if self.term_title:
243 restore_term_title()
271 restore_term_title()
244
272
245 def init_display_formatter(self):
273 def init_display_formatter(self):
246 super(TerminalInteractiveShell, self).init_display_formatter()
274 super(TerminalInteractiveShell, self).init_display_formatter()
247 # terminal only supports plain text
275 # terminal only supports plain text
248 self.display_formatter.active_types = ['text/plain']
276 self.display_formatter.active_types = ['text/plain']
249 # disable `_ipython_display_`
277 # disable `_ipython_display_`
250 self.display_formatter.ipython_display_formatter.enabled = False
278 self.display_formatter.ipython_display_formatter.enabled = False
251
279
252 def init_prompt_toolkit_cli(self):
280 def init_prompt_toolkit_cli(self):
253 if self.simple_prompt:
281 if self.simple_prompt:
254 # Fall back to plain non-interactive output for tests.
282 # Fall back to plain non-interactive output for tests.
255 # This is very limited.
283 # This is very limited.
256 def prompt():
284 def prompt():
257 prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens())
285 prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens())
258 lines = [input(prompt_text)]
286 lines = [input(prompt_text)]
259 prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens())
287 prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens())
260 while self.check_complete('\n'.join(lines))[0] == 'incomplete':
288 while self.check_complete('\n'.join(lines))[0] == 'incomplete':
261 lines.append( input(prompt_continuation) )
289 lines.append( input(prompt_continuation) )
262 return '\n'.join(lines)
290 return '\n'.join(lines)
263 self.prompt_for_code = prompt
291 self.prompt_for_code = prompt
264 return
292 return
265
293
266 # Set up keyboard shortcuts
294 # Set up keyboard shortcuts
267 key_bindings = create_ipython_shortcuts(self)
295 key_bindings = create_ipython_shortcuts(self)
268
296
269 # Pre-populate history from IPython's history database
297 # Pre-populate history from IPython's history database
270 history = InMemoryHistory()
298 history = InMemoryHistory()
271 last_cell = u""
299 last_cell = u""
272 for __, ___, cell in self.history_manager.get_tail(self.history_load_length,
300 for __, ___, cell in self.history_manager.get_tail(self.history_load_length,
273 include_latest=True):
301 include_latest=True):
274 # Ignore blank lines and consecutive duplicates
302 # Ignore blank lines and consecutive duplicates
275 cell = cell.rstrip()
303 cell = cell.rstrip()
276 if cell and (cell != last_cell):
304 if cell and (cell != last_cell):
277 history.append_string(cell)
305 history.append_string(cell)
278 last_cell = cell
306 last_cell = cell
279
307
280 self._style = self._make_style_from_name_or_cls(self.highlighting_style)
308 self._style = self._make_style_from_name_or_cls(self.highlighting_style)
281 self.style = DynamicStyle(lambda: self._style)
309 self.style = DynamicStyle(lambda: self._style)
282
310
283 editing_mode = getattr(EditingMode, self.editing_mode.upper())
311 editing_mode = getattr(EditingMode, self.editing_mode.upper())
284
312
313 self.pt_loop = asyncio.new_event_loop()
285 self.pt_app = PromptSession(
314 self.pt_app = PromptSession(
286 editing_mode=editing_mode,
315 editing_mode=editing_mode,
287 key_bindings=key_bindings,
316 key_bindings=key_bindings,
288 history=history,
317 history=history,
289 completer=IPythonPTCompleter(shell=self),
318 completer=IPythonPTCompleter(shell=self),
290 enable_history_search = self.enable_history_search,
319 enable_history_search = self.enable_history_search,
291 style=self.style,
320 style=self.style,
292 include_default_pygments_style=False,
321 include_default_pygments_style=False,
293 mouse_support=self.mouse_support,
322 mouse_support=self.mouse_support,
294 enable_open_in_editor=self.extra_open_editor_shortcuts,
323 enable_open_in_editor=self.extra_open_editor_shortcuts,
295 color_depth=self.color_depth,
324 color_depth=self.color_depth,
296 **self._extra_prompt_options())
325 **self._extra_prompt_options())
297
326
298 def _make_style_from_name_or_cls(self, name_or_cls):
327 def _make_style_from_name_or_cls(self, name_or_cls):
299 """
328 """
300 Small wrapper that make an IPython compatible style from a style name
329 Small wrapper that make an IPython compatible style from a style name
301
330
302 We need that to add style for prompt ... etc.
331 We need that to add style for prompt ... etc.
303 """
332 """
304 style_overrides = {}
333 style_overrides = {}
305 if name_or_cls == 'legacy':
334 if name_or_cls == 'legacy':
306 legacy = self.colors.lower()
335 legacy = self.colors.lower()
307 if legacy == 'linux':
336 if legacy == 'linux':
308 style_cls = get_style_by_name('monokai')
337 style_cls = get_style_by_name('monokai')
309 style_overrides = _style_overrides_linux
338 style_overrides = _style_overrides_linux
310 elif legacy == 'lightbg':
339 elif legacy == 'lightbg':
311 style_overrides = _style_overrides_light_bg
340 style_overrides = _style_overrides_light_bg
312 style_cls = get_style_by_name('pastie')
341 style_cls = get_style_by_name('pastie')
313 elif legacy == 'neutral':
342 elif legacy == 'neutral':
314 # The default theme needs to be visible on both a dark background
343 # The default theme needs to be visible on both a dark background
315 # and a light background, because we can't tell what the terminal
344 # and a light background, because we can't tell what the terminal
316 # looks like. These tweaks to the default theme help with that.
345 # looks like. These tweaks to the default theme help with that.
317 style_cls = get_style_by_name('default')
346 style_cls = get_style_by_name('default')
318 style_overrides.update({
347 style_overrides.update({
319 Token.Number: '#007700',
348 Token.Number: '#007700',
320 Token.Operator: 'noinherit',
349 Token.Operator: 'noinherit',
321 Token.String: '#BB6622',
350 Token.String: '#BB6622',
322 Token.Name.Function: '#2080D0',
351 Token.Name.Function: '#2080D0',
323 Token.Name.Class: 'bold #2080D0',
352 Token.Name.Class: 'bold #2080D0',
324 Token.Name.Namespace: 'bold #2080D0',
353 Token.Name.Namespace: 'bold #2080D0',
325 Token.Prompt: '#009900',
354 Token.Prompt: '#009900',
326 Token.PromptNum: '#ansibrightgreen bold',
355 Token.PromptNum: '#ansibrightgreen bold',
327 Token.OutPrompt: '#990000',
356 Token.OutPrompt: '#990000',
328 Token.OutPromptNum: '#ansibrightred bold',
357 Token.OutPromptNum: '#ansibrightred bold',
329 })
358 })
330
359
331 # Hack: Due to limited color support on the Windows console
360 # Hack: Due to limited color support on the Windows console
332 # the prompt colors will be wrong without this
361 # the prompt colors will be wrong without this
333 if os.name == 'nt':
362 if os.name == 'nt':
334 style_overrides.update({
363 style_overrides.update({
335 Token.Prompt: '#ansidarkgreen',
364 Token.Prompt: '#ansidarkgreen',
336 Token.PromptNum: '#ansigreen bold',
365 Token.PromptNum: '#ansigreen bold',
337 Token.OutPrompt: '#ansidarkred',
366 Token.OutPrompt: '#ansidarkred',
338 Token.OutPromptNum: '#ansired bold',
367 Token.OutPromptNum: '#ansired bold',
339 })
368 })
340 elif legacy =='nocolor':
369 elif legacy =='nocolor':
341 style_cls=_NoStyle
370 style_cls=_NoStyle
342 style_overrides = {}
371 style_overrides = {}
343 else :
372 else :
344 raise ValueError('Got unknown colors: ', legacy)
373 raise ValueError('Got unknown colors: ', legacy)
345 else :
374 else :
346 if isinstance(name_or_cls, str):
375 if isinstance(name_or_cls, str):
347 style_cls = get_style_by_name(name_or_cls)
376 style_cls = get_style_by_name(name_or_cls)
348 else:
377 else:
349 style_cls = name_or_cls
378 style_cls = name_or_cls
350 style_overrides = {
379 style_overrides = {
351 Token.Prompt: '#009900',
380 Token.Prompt: '#009900',
352 Token.PromptNum: '#ansibrightgreen bold',
381 Token.PromptNum: '#ansibrightgreen bold',
353 Token.OutPrompt: '#990000',
382 Token.OutPrompt: '#990000',
354 Token.OutPromptNum: '#ansibrightred bold',
383 Token.OutPromptNum: '#ansibrightred bold',
355 }
384 }
356 style_overrides.update(self.highlighting_style_overrides)
385 style_overrides.update(self.highlighting_style_overrides)
357 style = merge_styles([
386 style = merge_styles([
358 style_from_pygments_cls(style_cls),
387 style_from_pygments_cls(style_cls),
359 style_from_pygments_dict(style_overrides),
388 style_from_pygments_dict(style_overrides),
360 ])
389 ])
361
390
362 return style
391 return style
363
392
364 @property
393 @property
365 def pt_complete_style(self):
394 def pt_complete_style(self):
366 return {
395 return {
367 'multicolumn': CompleteStyle.MULTI_COLUMN,
396 'multicolumn': CompleteStyle.MULTI_COLUMN,
368 'column': CompleteStyle.COLUMN,
397 'column': CompleteStyle.COLUMN,
369 'readlinelike': CompleteStyle.READLINE_LIKE,
398 'readlinelike': CompleteStyle.READLINE_LIKE,
370 }[self.display_completions]
399 }[self.display_completions]
371
400
372 @property
401 @property
373 def color_depth(self):
402 def color_depth(self):
374 return (ColorDepth.TRUE_COLOR if self.true_color else None)
403 return (ColorDepth.TRUE_COLOR if self.true_color else None)
375
404
376 def _extra_prompt_options(self):
405 def _extra_prompt_options(self):
377 """
406 """
378 Return the current layout option for the current Terminal InteractiveShell
407 Return the current layout option for the current Terminal InteractiveShell
379 """
408 """
380 def get_message():
409 def get_message():
381 return PygmentsTokens(self.prompts.in_prompt_tokens())
410 return PygmentsTokens(self.prompts.in_prompt_tokens())
382
411
383 if self.editing_mode == 'emacs':
412 if self.editing_mode == 'emacs':
384 # with emacs mode the prompt is (usually) static, so we call only
413 # with emacs mode the prompt is (usually) static, so we call only
385 # the function once. With VI mode it can toggle between [ins] and
414 # the function once. With VI mode it can toggle between [ins] and
386 # [nor] so we can't precompute.
415 # [nor] so we can't precompute.
387 # here I'm going to favor the default keybinding which almost
416 # here I'm going to favor the default keybinding which almost
388 # everybody uses to decrease CPU usage.
417 # everybody uses to decrease CPU usage.
389 # if we have issues with users with custom Prompts we can see how to
418 # if we have issues with users with custom Prompts we can see how to
390 # work around this.
419 # work around this.
391 get_message = get_message()
420 get_message = get_message()
392
421
393 return {
422 options = {
394 'complete_in_thread': False,
423 'complete_in_thread': False,
395 'lexer':IPythonPTLexer(),
424 'lexer':IPythonPTLexer(),
396 'reserve_space_for_menu':self.space_for_menu,
425 'reserve_space_for_menu':self.space_for_menu,
397 'message': get_message,
426 'message': get_message,
398 'prompt_continuation': (
427 'prompt_continuation': (
399 lambda width, lineno, is_soft_wrap:
428 lambda width, lineno, is_soft_wrap:
400 PygmentsTokens(self.prompts.continuation_prompt_tokens(width))),
429 PygmentsTokens(self.prompts.continuation_prompt_tokens(width))),
401 'multiline': True,
430 'multiline': True,
402 'complete_style': self.pt_complete_style,
431 'complete_style': self.pt_complete_style,
403
432
404 # Highlight matching brackets, but only when this setting is
433 # Highlight matching brackets, but only when this setting is
405 # enabled, and only when the DEFAULT_BUFFER has the focus.
434 # enabled, and only when the DEFAULT_BUFFER has the focus.
406 'input_processors': [ConditionalProcessor(
435 'input_processors': [ConditionalProcessor(
407 processor=HighlightMatchingBracketProcessor(chars='[](){}'),
436 processor=HighlightMatchingBracketProcessor(chars='[](){}'),
408 filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() &
437 filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() &
409 Condition(lambda: self.highlight_matching_brackets))],
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 def prompt_for_code(self):
445 def prompt_for_code(self):
414 if self.rl_next_input:
446 if self.rl_next_input:
415 default = self.rl_next_input
447 default = self.rl_next_input
416 self.rl_next_input = None
448 self.rl_next_input = None
417 else:
449 else:
418 default = ''
450 default = ''
419
451
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:
420 with patch_stdout(raw=True):
466 with patch_stdout(raw=True):
421 text = self.pt_app.prompt(
467 text = self.pt_app.prompt(
422 default=default,
468 default=default,
423 # pre_run=self.pre_prompt,# reset_current_buffer=True,
424 **self._extra_prompt_options())
469 **self._extra_prompt_options())
470 finally:
471 # Restore the original event loop.
472 asyncio.set_event_loop(old_loop)
473
425 return text
474 return text
426
475
427 def enable_win_unicode_console(self):
476 def enable_win_unicode_console(self):
428 # Since IPython 7.10 doesn't support python < 3.6 and PEP 528, Python uses the unicode APIs for the Windows
477 # Since IPython 7.10 doesn't support python < 3.6 and PEP 528, Python uses the unicode APIs for the Windows
429 # console by default, so WUC shouldn't be needed.
478 # console by default, so WUC shouldn't be needed.
430 from warnings import warn
479 from warnings import warn
431 warn("`enable_win_unicode_console` is deprecated since IPython 7.10, does not do anything and will be removed in the future",
480 warn("`enable_win_unicode_console` is deprecated since IPython 7.10, does not do anything and will be removed in the future",
432 DeprecationWarning,
481 DeprecationWarning,
433 stacklevel=2)
482 stacklevel=2)
434
483
435 def init_io(self):
484 def init_io(self):
436 if sys.platform not in {'win32', 'cli'}:
485 if sys.platform not in {'win32', 'cli'}:
437 return
486 return
438
487
439 import colorama
488 import colorama
440 colorama.init()
489 colorama.init()
441
490
442 # For some reason we make these wrappers around stdout/stderr.
491 # For some reason we make these wrappers around stdout/stderr.
443 # For now, we need to reset them so all output gets coloured.
492 # For now, we need to reset them so all output gets coloured.
444 # https://github.com/ipython/ipython/issues/8669
493 # https://github.com/ipython/ipython/issues/8669
445 # io.std* are deprecated, but don't show our own deprecation warnings
494 # io.std* are deprecated, but don't show our own deprecation warnings
446 # during initialization of the deprecated API.
495 # during initialization of the deprecated API.
447 with warnings.catch_warnings():
496 with warnings.catch_warnings():
448 warnings.simplefilter('ignore', DeprecationWarning)
497 warnings.simplefilter('ignore', DeprecationWarning)
449 io.stdout = io.IOStream(sys.stdout)
498 io.stdout = io.IOStream(sys.stdout)
450 io.stderr = io.IOStream(sys.stderr)
499 io.stderr = io.IOStream(sys.stderr)
451
500
452 def init_magics(self):
501 def init_magics(self):
453 super(TerminalInteractiveShell, self).init_magics()
502 super(TerminalInteractiveShell, self).init_magics()
454 self.register_magics(TerminalMagics)
503 self.register_magics(TerminalMagics)
455
504
456 def init_alias(self):
505 def init_alias(self):
457 # The parent class defines aliases that can be safely used with any
506 # The parent class defines aliases that can be safely used with any
458 # frontend.
507 # frontend.
459 super(TerminalInteractiveShell, self).init_alias()
508 super(TerminalInteractiveShell, self).init_alias()
460
509
461 # Now define aliases that only make sense on the terminal, because they
510 # Now define aliases that only make sense on the terminal, because they
462 # need direct access to the console in a way that we can't emulate in
511 # need direct access to the console in a way that we can't emulate in
463 # GUI or web frontend
512 # GUI or web frontend
464 if os.name == 'posix':
513 if os.name == 'posix':
465 for cmd in ('clear', 'more', 'less', 'man'):
514 for cmd in ('clear', 'more', 'less', 'man'):
466 self.alias_manager.soft_define_alias(cmd, cmd)
515 self.alias_manager.soft_define_alias(cmd, cmd)
467
516
468
517
469 def __init__(self, *args, **kwargs):
518 def __init__(self, *args, **kwargs):
470 super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
519 super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
471 self.init_prompt_toolkit_cli()
520 self.init_prompt_toolkit_cli()
472 self.init_term_title()
521 self.init_term_title()
473 self.keep_running = True
522 self.keep_running = True
474
523
475 self.debugger_history = InMemoryHistory()
524 self.debugger_history = InMemoryHistory()
476
525
477 def ask_exit(self):
526 def ask_exit(self):
478 self.keep_running = False
527 self.keep_running = False
479
528
480 rl_next_input = None
529 rl_next_input = None
481
530
482 def interact(self, display_banner=DISPLAY_BANNER_DEPRECATED):
531 def interact(self, display_banner=DISPLAY_BANNER_DEPRECATED):
483
532
484 if display_banner is not DISPLAY_BANNER_DEPRECATED:
533 if display_banner is not DISPLAY_BANNER_DEPRECATED:
485 warn('interact `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
534 warn('interact `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
486
535
487 self.keep_running = True
536 self.keep_running = True
488 while self.keep_running:
537 while self.keep_running:
489 print(self.separate_in, end='')
538 print(self.separate_in, end='')
490
539
491 try:
540 try:
492 code = self.prompt_for_code()
541 code = self.prompt_for_code()
493 except EOFError:
542 except EOFError:
494 if (not self.confirm_exit) \
543 if (not self.confirm_exit) \
495 or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
544 or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
496 self.ask_exit()
545 self.ask_exit()
497
546
498 else:
547 else:
499 if code:
548 if code:
500 self.run_cell(code, store_history=True)
549 self.run_cell(code, store_history=True)
501
550
502 def mainloop(self, display_banner=DISPLAY_BANNER_DEPRECATED):
551 def mainloop(self, display_banner=DISPLAY_BANNER_DEPRECATED):
503 # An extra layer of protection in case someone mashing Ctrl-C breaks
552 # An extra layer of protection in case someone mashing Ctrl-C breaks
504 # out of our internal code.
553 # out of our internal code.
505 if display_banner is not DISPLAY_BANNER_DEPRECATED:
554 if display_banner is not DISPLAY_BANNER_DEPRECATED:
506 warn('mainloop `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
555 warn('mainloop `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
507 while True:
556 while True:
508 try:
557 try:
509 self.interact()
558 self.interact()
510 break
559 break
511 except KeyboardInterrupt as e:
560 except KeyboardInterrupt as e:
512 print("\n%s escaped interact()\n" % type(e).__name__)
561 print("\n%s escaped interact()\n" % type(e).__name__)
513 finally:
562 finally:
514 # An interrupt during the eventloop will mess up the
563 # An interrupt during the eventloop will mess up the
515 # internal state of the prompt_toolkit library.
564 # internal state of the prompt_toolkit library.
516 # Stopping the eventloop fixes this, see
565 # Stopping the eventloop fixes this, see
517 # https://github.com/ipython/ipython/pull/9867
566 # https://github.com/ipython/ipython/pull/9867
518 if hasattr(self, '_eventloop'):
567 if hasattr(self, '_eventloop'):
519 self._eventloop.stop()
568 self._eventloop.stop()
520
569
521 self.restore_term_title()
570 self.restore_term_title()
522
571
523
572
524 _inputhook = None
573 _inputhook = None
525 def inputhook(self, context):
574 def inputhook(self, context):
526 if self._inputhook is not None:
575 if self._inputhook is not None:
527 self._inputhook(context)
576 self._inputhook(context)
528
577
529 active_eventloop = None
578 active_eventloop = None
530 def enable_gui(self, gui=None):
579 def enable_gui(self, gui=None):
531 if gui:
580 if gui and (gui != 'inline') :
532 self.active_eventloop, self._inputhook =\
581 self.active_eventloop, self._inputhook =\
533 get_inputhook_name_and_func(gui)
582 get_inputhook_name_and_func(gui)
534 else:
583 else:
535 self.active_eventloop = self._inputhook = None
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 # Run !system commands directly, not through pipes, so terminal programs
607 # Run !system commands directly, not through pipes, so terminal programs
538 # work correctly.
608 # work correctly.
539 system = InteractiveShell.system_raw
609 system = InteractiveShell.system_raw
540
610
541 def auto_rewrite_input(self, cmd):
611 def auto_rewrite_input(self, cmd):
542 """Overridden from the parent class to use fancy rewriting prompt"""
612 """Overridden from the parent class to use fancy rewriting prompt"""
543 if not self.show_rewritten_input:
613 if not self.show_rewritten_input:
544 return
614 return
545
615
546 tokens = self.prompts.rewrite_prompt_tokens()
616 tokens = self.prompts.rewrite_prompt_tokens()
547 if self.pt_app:
617 if self.pt_app:
548 print_formatted_text(PygmentsTokens(tokens), end='',
618 print_formatted_text(PygmentsTokens(tokens), end='',
549 style=self.pt_app.app.style)
619 style=self.pt_app.app.style)
550 print(cmd)
620 print(cmd)
551 else:
621 else:
552 prompt = ''.join(s for t, s in tokens)
622 prompt = ''.join(s for t, s in tokens)
553 print(prompt, cmd, sep='')
623 print(prompt, cmd, sep='')
554
624
555 _prompts_before = None
625 _prompts_before = None
556 def switch_doctest_mode(self, mode):
626 def switch_doctest_mode(self, mode):
557 """Switch prompts to classic for %doctest_mode"""
627 """Switch prompts to classic for %doctest_mode"""
558 if mode:
628 if mode:
559 self._prompts_before = self.prompts
629 self._prompts_before = self.prompts
560 self.prompts = ClassicPrompts(self)
630 self.prompts = ClassicPrompts(self)
561 elif self._prompts_before:
631 elif self._prompts_before:
562 self.prompts = self._prompts_before
632 self.prompts = self._prompts_before
563 self._prompts_before = None
633 self._prompts_before = None
564 # self._update_layout()
634 # self._update_layout()
565
635
566
636
567 InteractiveShellABC.register(TerminalInteractiveShell)
637 InteractiveShellABC.register(TerminalInteractiveShell)
568
638
569 if __name__ == '__main__':
639 if __name__ == '__main__':
570 TerminalInteractiveShell.instance().interact()
640 TerminalInteractiveShell.instance().interact()
@@ -1,91 +1,102 b''
1 """Terminal input and output prompts."""
1 """Terminal input and output prompts."""
2
2
3 from pygments.token import Token
3 from pygments.token import Token
4 import sys
4 import sys
5
5
6 from IPython.core.displayhook import DisplayHook
6 from IPython.core.displayhook import DisplayHook
7
7
8 from prompt_toolkit.formatted_text import fragment_list_width, PygmentsTokens
8 from prompt_toolkit.formatted_text import fragment_list_width, PygmentsTokens
9 from prompt_toolkit.shortcuts import print_formatted_text
9 from prompt_toolkit.shortcuts import print_formatted_text
10
10
11
11
12 class Prompts(object):
12 class Prompts(object):
13 def __init__(self, shell):
13 def __init__(self, shell):
14 self.shell = shell
14 self.shell = shell
15
15
16 def vi_mode(self):
16 def vi_mode(self):
17 if (getattr(self.shell.pt_app, 'editing_mode', None) == 'VI'
17 if (getattr(self.shell.pt_app, 'editing_mode', None) == 'VI'
18 and self.shell.prompt_includes_vi_mode):
18 and self.shell.prompt_includes_vi_mode):
19 return '['+str(self.shell.pt_app.app.vi_state.input_mode)[3:6]+'] '
19 return '['+str(self.shell.pt_app.app.vi_state.input_mode)[3:6]+'] '
20 return ''
20 return ''
21
21
22
22
23 def in_prompt_tokens(self):
23 def in_prompt_tokens(self):
24 return [
24 return [
25 (Token.Prompt, self.vi_mode() ),
25 (Token.Prompt, self.vi_mode() ),
26 (Token.Prompt, 'In ['),
26 (Token.Prompt, 'In ['),
27 (Token.PromptNum, str(self.shell.execution_count)),
27 (Token.PromptNum, str(self.shell.execution_count)),
28 (Token.Prompt, ']: '),
28 (Token.Prompt, ']: '),
29 ]
29 ]
30
30
31 def _width(self):
31 def _width(self):
32 return fragment_list_width(self.in_prompt_tokens())
32 return fragment_list_width(self.in_prompt_tokens())
33
33
34 def continuation_prompt_tokens(self, width=None):
34 def continuation_prompt_tokens(self, width=None):
35 if width is None:
35 if width is None:
36 width = self._width()
36 width = self._width()
37 return [
37 return [
38 (Token.Prompt, (' ' * (width - 5)) + '...: '),
38 (Token.Prompt, (' ' * (width - 5)) + '...: '),
39 ]
39 ]
40
40
41 def rewrite_prompt_tokens(self):
41 def rewrite_prompt_tokens(self):
42 width = self._width()
42 width = self._width()
43 return [
43 return [
44 (Token.Prompt, ('-' * (width - 2)) + '> '),
44 (Token.Prompt, ('-' * (width - 2)) + '> '),
45 ]
45 ]
46
46
47 def out_prompt_tokens(self):
47 def out_prompt_tokens(self):
48 return [
48 return [
49 (Token.OutPrompt, 'Out['),
49 (Token.OutPrompt, 'Out['),
50 (Token.OutPromptNum, str(self.shell.execution_count)),
50 (Token.OutPromptNum, str(self.shell.execution_count)),
51 (Token.OutPrompt, ']: '),
51 (Token.OutPrompt, ']: '),
52 ]
52 ]
53
53
54 class ClassicPrompts(Prompts):
54 class ClassicPrompts(Prompts):
55 def in_prompt_tokens(self):
55 def in_prompt_tokens(self):
56 return [
56 return [
57 (Token.Prompt, '>>> '),
57 (Token.Prompt, '>>> '),
58 ]
58 ]
59
59
60 def continuation_prompt_tokens(self, width=None):
60 def continuation_prompt_tokens(self, width=None):
61 return [
61 return [
62 (Token.Prompt, '... ')
62 (Token.Prompt, '... ')
63 ]
63 ]
64
64
65 def rewrite_prompt_tokens(self):
65 def rewrite_prompt_tokens(self):
66 return []
66 return []
67
67
68 def out_prompt_tokens(self):
68 def out_prompt_tokens(self):
69 return []
69 return []
70
70
71 class RichPromptDisplayHook(DisplayHook):
71 class RichPromptDisplayHook(DisplayHook):
72 """Subclass of base display hook using coloured prompt"""
72 """Subclass of base display hook using coloured prompt"""
73 def write_output_prompt(self):
73 def write_output_prompt(self):
74 sys.stdout.write(self.shell.separate_out)
74 sys.stdout.write(self.shell.separate_out)
75 # If we're not displaying a prompt, it effectively ends with a newline,
75 # If we're not displaying a prompt, it effectively ends with a newline,
76 # because the output will be left-aligned.
76 # because the output will be left-aligned.
77 self.prompt_end_newline = True
77 self.prompt_end_newline = True
78
78
79 if self.do_full_cache:
79 if self.do_full_cache:
80 tokens = self.shell.prompts.out_prompt_tokens()
80 tokens = self.shell.prompts.out_prompt_tokens()
81 prompt_txt = ''.join(s for t, s in tokens)
81 prompt_txt = ''.join(s for t, s in tokens)
82 if prompt_txt and not prompt_txt.endswith('\n'):
82 if prompt_txt and not prompt_txt.endswith('\n'):
83 # Ask for a newline before multiline output
83 # Ask for a newline before multiline output
84 self.prompt_end_newline = False
84 self.prompt_end_newline = False
85
85
86 if self.shell.pt_app:
86 if self.shell.pt_app:
87 print_formatted_text(PygmentsTokens(tokens),
87 print_formatted_text(PygmentsTokens(tokens),
88 style=self.shell.pt_app.app.style, end='',
88 style=self.shell.pt_app.app.style, end='',
89 )
89 )
90 else:
90 else:
91 sys.stdout.write(prompt_txt)
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 import importlib
1 import importlib
2 import os
2 import os
3
3
4 aliases = {
4 aliases = {
5 'qt4': 'qt',
5 'qt4': 'qt',
6 'gtk2': 'gtk',
6 'gtk2': 'gtk',
7 }
7 }
8
8
9 backends = [
9 backends = [
10 'qt', 'qt4', 'qt5',
10 'qt', 'qt4', 'qt5',
11 'gtk', 'gtk2', 'gtk3',
11 'gtk', 'gtk2', 'gtk3',
12 'tk',
12 'tk',
13 'wx',
13 'wx',
14 'pyglet', 'glut',
14 'pyglet', 'glut',
15 'osx',
15 'osx',
16 'asyncio'
16 ]
17 ]
17
18
18 registered = {}
19 registered = {}
19
20
20 def register(name, inputhook):
21 def register(name, inputhook):
21 """Register the function *inputhook* as an event loop integration."""
22 """Register the function *inputhook* as an event loop integration."""
22 registered[name] = inputhook
23 registered[name] = inputhook
23
24
24 class UnknownBackend(KeyError):
25 class UnknownBackend(KeyError):
25 def __init__(self, name):
26 def __init__(self, name):
26 self.name = name
27 self.name = name
27
28
28 def __str__(self):
29 def __str__(self):
29 return ("No event loop integration for {!r}. "
30 return ("No event loop integration for {!r}. "
30 "Supported event loops are: {}").format(self.name,
31 "Supported event loops are: {}").format(self.name,
31 ', '.join(backends + sorted(registered)))
32 ', '.join(backends + sorted(registered)))
32
33
33 def get_inputhook_name_and_func(gui):
34 def get_inputhook_name_and_func(gui):
34 if gui in registered:
35 if gui in registered:
35 return gui, registered[gui]
36 return gui, registered[gui]
36
37
37 if gui not in backends:
38 if gui not in backends:
38 raise UnknownBackend(gui)
39 raise UnknownBackend(gui)
39
40
40 if gui in aliases:
41 if gui in aliases:
41 return get_inputhook_name_and_func(aliases[gui])
42 return get_inputhook_name_and_func(aliases[gui])
42
43
43 gui_mod = gui
44 gui_mod = gui
44 if gui == 'qt5':
45 if gui == 'qt5':
45 os.environ['QT_API'] = 'pyqt5'
46 os.environ['QT_API'] = 'pyqt5'
46 gui_mod = 'qt'
47 gui_mod = 'qt'
47
48
48 mod = importlib.import_module('IPython.terminal.pt_inputhooks.'+gui_mod)
49 mod = importlib.import_module('IPython.terminal.pt_inputhooks.'+gui_mod)
49 return gui, mod.inputhook
50 return gui, mod.inputhook
@@ -1,249 +1,274 b''
1 """
1 """
2 Module to define and register Terminal IPython shortcuts with
2 Module to define and register Terminal IPython shortcuts with
3 :mod:`prompt_toolkit`
3 :mod:`prompt_toolkit`
4 """
4 """
5
5
6 # Copyright (c) IPython Development Team.
6 # Copyright (c) IPython Development Team.
7 # Distributed under the terms of the Modified BSD License.
7 # Distributed under the terms of the Modified BSD License.
8
8
9 import warnings
9 import warnings
10 import signal
10 import signal
11 import sys
11 import sys
12 from typing import Callable
12 from typing import Callable
13
13
14
14
15 from prompt_toolkit.application.current import get_app
15 from prompt_toolkit.application.current import get_app
16 from prompt_toolkit.enums import DEFAULT_BUFFER, SEARCH_BUFFER
16 from prompt_toolkit.enums import DEFAULT_BUFFER, SEARCH_BUFFER
17 from prompt_toolkit.filters import (has_focus, has_selection, Condition,
17 from prompt_toolkit.filters import (has_focus, has_selection, Condition,
18 vi_insert_mode, emacs_insert_mode, has_completions, vi_mode)
18 vi_insert_mode, emacs_insert_mode, has_completions, vi_mode)
19 from prompt_toolkit.key_binding.bindings.completion import display_completions_like_readline
19 from prompt_toolkit.key_binding.bindings.completion import display_completions_like_readline
20 from prompt_toolkit.key_binding import KeyBindings
20 from prompt_toolkit.key_binding import KeyBindings
21
21
22 from IPython.utils.decorators import undoc
22 from IPython.utils.decorators import undoc
23
23
24 @undoc
24 @undoc
25 @Condition
25 @Condition
26 def cursor_in_leading_ws():
26 def cursor_in_leading_ws():
27 before = get_app().current_buffer.document.current_line_before_cursor
27 before = get_app().current_buffer.document.current_line_before_cursor
28 return (not before) or before.isspace()
28 return (not before) or before.isspace()
29
29
30
30
31 def create_ipython_shortcuts(shell):
31 def create_ipython_shortcuts(shell):
32 """Set up the prompt_toolkit keyboard shortcuts for IPython"""
32 """Set up the prompt_toolkit keyboard shortcuts for IPython"""
33
33
34 kb = KeyBindings()
34 kb = KeyBindings()
35 insert_mode = vi_insert_mode | emacs_insert_mode
35 insert_mode = vi_insert_mode | emacs_insert_mode
36
36
37 if getattr(shell, 'handle_return', None):
37 if getattr(shell, 'handle_return', None):
38 return_handler = shell.handle_return(shell)
38 return_handler = shell.handle_return(shell)
39 else:
39 else:
40 return_handler = newline_or_execute_outer(shell)
40 return_handler = newline_or_execute_outer(shell)
41
41
42 kb.add('enter', filter=(has_focus(DEFAULT_BUFFER)
42 kb.add('enter', filter=(has_focus(DEFAULT_BUFFER)
43 & ~has_selection
43 & ~has_selection
44 & insert_mode
44 & insert_mode
45 ))(return_handler)
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 kb.add('c-\\')(force_exit)
56 kb.add('c-\\')(force_exit)
48
57
49 kb.add('c-p', filter=(vi_insert_mode & has_focus(DEFAULT_BUFFER))
58 kb.add('c-p', filter=(vi_insert_mode & has_focus(DEFAULT_BUFFER))
50 )(previous_history_or_previous_completion)
59 )(previous_history_or_previous_completion)
51
60
52 kb.add('c-n', filter=(vi_insert_mode & has_focus(DEFAULT_BUFFER))
61 kb.add('c-n', filter=(vi_insert_mode & has_focus(DEFAULT_BUFFER))
53 )(next_history_or_next_completion)
62 )(next_history_or_next_completion)
54
63
55 kb.add('c-g', filter=(has_focus(DEFAULT_BUFFER) & has_completions)
64 kb.add('c-g', filter=(has_focus(DEFAULT_BUFFER) & has_completions)
56 )(dismiss_completion)
65 )(dismiss_completion)
57
66
58 kb.add('c-c', filter=has_focus(DEFAULT_BUFFER))(reset_buffer)
67 kb.add('c-c', filter=has_focus(DEFAULT_BUFFER))(reset_buffer)
59
68
60 kb.add('c-c', filter=has_focus(SEARCH_BUFFER))(reset_search_buffer)
69 kb.add('c-c', filter=has_focus(SEARCH_BUFFER))(reset_search_buffer)
61
70
62 supports_suspend = Condition(lambda: hasattr(signal, 'SIGTSTP'))
71 supports_suspend = Condition(lambda: hasattr(signal, 'SIGTSTP'))
63 kb.add('c-z', filter=supports_suspend)(suspend_to_bg)
72 kb.add('c-z', filter=supports_suspend)(suspend_to_bg)
64
73
65 # Ctrl+I == Tab
74 # Ctrl+I == Tab
66 kb.add('tab', filter=(has_focus(DEFAULT_BUFFER)
75 kb.add('tab', filter=(has_focus(DEFAULT_BUFFER)
67 & ~has_selection
76 & ~has_selection
68 & insert_mode
77 & insert_mode
69 & cursor_in_leading_ws
78 & cursor_in_leading_ws
70 ))(indent_buffer)
79 ))(indent_buffer)
71 kb.add('c-o', filter=(has_focus(DEFAULT_BUFFER) & emacs_insert_mode)
80 kb.add('c-o', filter=(has_focus(DEFAULT_BUFFER) & emacs_insert_mode)
72 )(newline_autoindent_outer(shell.input_transformer_manager))
81 )(newline_autoindent_outer(shell.input_transformer_manager))
73
82
74 kb.add('f2', filter=has_focus(DEFAULT_BUFFER))(open_input_in_editor)
83 kb.add('f2', filter=has_focus(DEFAULT_BUFFER))(open_input_in_editor)
75
84
76 if shell.display_completions == 'readlinelike':
85 if shell.display_completions == 'readlinelike':
77 kb.add('c-i', filter=(has_focus(DEFAULT_BUFFER)
86 kb.add('c-i', filter=(has_focus(DEFAULT_BUFFER)
78 & ~has_selection
87 & ~has_selection
79 & insert_mode
88 & insert_mode
80 & ~cursor_in_leading_ws
89 & ~cursor_in_leading_ws
81 ))(display_completions_like_readline)
90 ))(display_completions_like_readline)
82
91
83 if sys.platform == 'win32':
92 if sys.platform == 'win32':
84 kb.add('c-v', filter=(has_focus(DEFAULT_BUFFER) & ~vi_mode))(win_paste)
93 kb.add('c-v', filter=(has_focus(DEFAULT_BUFFER) & ~vi_mode))(win_paste)
85
94
86 return kb
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 def newline_or_execute_outer(shell):
107 def newline_or_execute_outer(shell):
108
90 def newline_or_execute(event):
109 def newline_or_execute(event):
91 """When the user presses return, insert a newline or execute the code."""
110 """When the user presses return, insert a newline or execute the code."""
92 b = event.current_buffer
111 b = event.current_buffer
93 d = b.document
112 d = b.document
94
113
95 if b.complete_state:
114 if b.complete_state:
96 cc = b.complete_state.current_completion
115 cc = b.complete_state.current_completion
97 if cc:
116 if cc:
98 b.apply_completion(cc)
117 b.apply_completion(cc)
99 else:
118 else:
100 b.cancel_completion()
119 b.cancel_completion()
101 return
120 return
102
121
103 # If there's only one line, treat it as if the cursor is at the end.
122 # If there's only one line, treat it as if the cursor is at the end.
104 # See https://github.com/ipython/ipython/issues/10425
123 # See https://github.com/ipython/ipython/issues/10425
105 if d.line_count == 1:
124 if d.line_count == 1:
106 check_text = d.text
125 check_text = d.text
107 else:
126 else:
108 check_text = d.text[:d.cursor_position]
127 check_text = d.text[:d.cursor_position]
109 status, indent = shell.check_complete(check_text)
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 if not (d.on_last_line or
135 if not (d.on_last_line or
112 d.cursor_position_row >= d.line_count - d.empty_line_count_at_the_end()
136 d.cursor_position_row >= d.line_count - d.empty_line_count_at_the_end()
113 ):
137 ):
114 if shell.autoindent:
138 if shell.autoindent:
115 b.insert_text('\n' + indent)
139 b.insert_text('\n' + indent)
116 else:
140 else:
117 b.insert_text('\n')
141 b.insert_text('\n')
118 return
142 return
119
143
120 if (status != 'incomplete') and b.accept_handler:
144 if (status != 'incomplete') and b.accept_handler:
145 reformat_text_before_cursor(b, d, shell)
121 b.validate_and_handle()
146 b.validate_and_handle()
122 else:
147 else:
123 if shell.autoindent:
148 if shell.autoindent:
124 b.insert_text('\n' + indent)
149 b.insert_text('\n' + indent)
125 else:
150 else:
126 b.insert_text('\n')
151 b.insert_text('\n')
127 return newline_or_execute
152 return newline_or_execute
128
153
129
154
130 def previous_history_or_previous_completion(event):
155 def previous_history_or_previous_completion(event):
131 """
156 """
132 Control-P in vi edit mode on readline is history next, unlike default prompt toolkit.
157 Control-P in vi edit mode on readline is history next, unlike default prompt toolkit.
133
158
134 If completer is open this still select previous completion.
159 If completer is open this still select previous completion.
135 """
160 """
136 event.current_buffer.auto_up()
161 event.current_buffer.auto_up()
137
162
138
163
139 def next_history_or_next_completion(event):
164 def next_history_or_next_completion(event):
140 """
165 """
141 Control-N in vi edit mode on readline is history previous, unlike default prompt toolkit.
166 Control-N in vi edit mode on readline is history previous, unlike default prompt toolkit.
142
167
143 If completer is open this still select next completion.
168 If completer is open this still select next completion.
144 """
169 """
145 event.current_buffer.auto_down()
170 event.current_buffer.auto_down()
146
171
147
172
148 def dismiss_completion(event):
173 def dismiss_completion(event):
149 b = event.current_buffer
174 b = event.current_buffer
150 if b.complete_state:
175 if b.complete_state:
151 b.cancel_completion()
176 b.cancel_completion()
152
177
153
178
154 def reset_buffer(event):
179 def reset_buffer(event):
155 b = event.current_buffer
180 b = event.current_buffer
156 if b.complete_state:
181 if b.complete_state:
157 b.cancel_completion()
182 b.cancel_completion()
158 else:
183 else:
159 b.reset()
184 b.reset()
160
185
161
186
162 def reset_search_buffer(event):
187 def reset_search_buffer(event):
163 if event.current_buffer.document.text:
188 if event.current_buffer.document.text:
164 event.current_buffer.reset()
189 event.current_buffer.reset()
165 else:
190 else:
166 event.app.layout.focus(DEFAULT_BUFFER)
191 event.app.layout.focus(DEFAULT_BUFFER)
167
192
168 def suspend_to_bg(event):
193 def suspend_to_bg(event):
169 event.app.suspend_to_background()
194 event.app.suspend_to_background()
170
195
171 def force_exit(event):
196 def force_exit(event):
172 """
197 """
173 Force exit (with a non-zero return value)
198 Force exit (with a non-zero return value)
174 """
199 """
175 sys.exit("Quit")
200 sys.exit("Quit")
176
201
177 def indent_buffer(event):
202 def indent_buffer(event):
178 event.current_buffer.insert_text(' ' * 4)
203 event.current_buffer.insert_text(' ' * 4)
179
204
180 @undoc
205 @undoc
181 def newline_with_copy_margin(event):
206 def newline_with_copy_margin(event):
182 """
207 """
183 DEPRECATED since IPython 6.0
208 DEPRECATED since IPython 6.0
184
209
185 See :any:`newline_autoindent_outer` for a replacement.
210 See :any:`newline_autoindent_outer` for a replacement.
186
211
187 Preserve margin and cursor position when using
212 Preserve margin and cursor position when using
188 Control-O to insert a newline in EMACS mode
213 Control-O to insert a newline in EMACS mode
189 """
214 """
190 warnings.warn("`newline_with_copy_margin(event)` is deprecated since IPython 6.0. "
215 warnings.warn("`newline_with_copy_margin(event)` is deprecated since IPython 6.0. "
191 "see `newline_autoindent_outer(shell)(event)` for a replacement.",
216 "see `newline_autoindent_outer(shell)(event)` for a replacement.",
192 DeprecationWarning, stacklevel=2)
217 DeprecationWarning, stacklevel=2)
193
218
194 b = event.current_buffer
219 b = event.current_buffer
195 cursor_start_pos = b.document.cursor_position_col
220 cursor_start_pos = b.document.cursor_position_col
196 b.newline(copy_margin=True)
221 b.newline(copy_margin=True)
197 b.cursor_up(count=1)
222 b.cursor_up(count=1)
198 cursor_end_pos = b.document.cursor_position_col
223 cursor_end_pos = b.document.cursor_position_col
199 if cursor_start_pos != cursor_end_pos:
224 if cursor_start_pos != cursor_end_pos:
200 pos_diff = cursor_start_pos - cursor_end_pos
225 pos_diff = cursor_start_pos - cursor_end_pos
201 b.cursor_right(count=pos_diff)
226 b.cursor_right(count=pos_diff)
202
227
203 def newline_autoindent_outer(inputsplitter) -> Callable[..., None]:
228 def newline_autoindent_outer(inputsplitter) -> Callable[..., None]:
204 """
229 """
205 Return a function suitable for inserting a indented newline after the cursor.
230 Return a function suitable for inserting a indented newline after the cursor.
206
231
207 Fancier version of deprecated ``newline_with_copy_margin`` which should
232 Fancier version of deprecated ``newline_with_copy_margin`` which should
208 compute the correct indentation of the inserted line. That is to say, indent
233 compute the correct indentation of the inserted line. That is to say, indent
209 by 4 extra space after a function definition, class definition, context
234 by 4 extra space after a function definition, class definition, context
210 manager... And dedent by 4 space after ``pass``, ``return``, ``raise ...``.
235 manager... And dedent by 4 space after ``pass``, ``return``, ``raise ...``.
211 """
236 """
212
237
213 def newline_autoindent(event):
238 def newline_autoindent(event):
214 """insert a newline after the cursor indented appropriately."""
239 """insert a newline after the cursor indented appropriately."""
215 b = event.current_buffer
240 b = event.current_buffer
216 d = b.document
241 d = b.document
217
242
218 if b.complete_state:
243 if b.complete_state:
219 b.cancel_completion()
244 b.cancel_completion()
220 text = d.text[:d.cursor_position] + '\n'
245 text = d.text[:d.cursor_position] + '\n'
221 _, indent = inputsplitter.check_complete(text)
246 _, indent = inputsplitter.check_complete(text)
222 b.insert_text('\n' + (' ' * (indent or 0)), move_cursor=False)
247 b.insert_text('\n' + (' ' * (indent or 0)), move_cursor=False)
223
248
224 return newline_autoindent
249 return newline_autoindent
225
250
226
251
227 def open_input_in_editor(event):
252 def open_input_in_editor(event):
228 event.app.current_buffer.tempfile_suffix = ".py"
253 event.app.current_buffer.tempfile_suffix = ".py"
229 event.app.current_buffer.open_in_editor()
254 event.app.current_buffer.open_in_editor()
230
255
231
256
232 if sys.platform == 'win32':
257 if sys.platform == 'win32':
233 from IPython.core.error import TryNext
258 from IPython.core.error import TryNext
234 from IPython.lib.clipboard import (ClipboardEmpty,
259 from IPython.lib.clipboard import (ClipboardEmpty,
235 win32_clipboard_get,
260 win32_clipboard_get,
236 tkinter_clipboard_get)
261 tkinter_clipboard_get)
237
262
238 @undoc
263 @undoc
239 def win_paste(event):
264 def win_paste(event):
240 try:
265 try:
241 text = win32_clipboard_get()
266 text = win32_clipboard_get()
242 except TryNext:
267 except TryNext:
243 try:
268 try:
244 text = tkinter_clipboard_get()
269 text = tkinter_clipboard_get()
245 except (TryNext, ClipboardEmpty):
270 except (TryNext, ClipboardEmpty):
246 return
271 return
247 except ClipboardEmpty:
272 except ClipboardEmpty:
248 return
273 return
249 event.current_buffer.insert_text(text.replace('\t', ' ' * 4))
274 event.current_buffer.insert_text(text.replace('\t', ' ' * 4))
@@ -1,439 +1,436 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 Utilities for path handling.
3 Utilities for path handling.
4 """
4 """
5
5
6 # Copyright (c) IPython Development Team.
6 # Copyright (c) IPython Development Team.
7 # Distributed under the terms of the Modified BSD License.
7 # Distributed under the terms of the Modified BSD License.
8
8
9 import os
9 import os
10 import sys
10 import sys
11 import errno
11 import errno
12 import shutil
12 import shutil
13 import random
13 import random
14 import glob
14 import glob
15 from warnings import warn
15 from warnings import warn
16
16
17 from IPython.utils.process import system
17 from IPython.utils.process import system
18 from IPython.utils import py3compat
18 from IPython.utils import py3compat
19 from IPython.utils.decorators import undoc
19 from IPython.utils.decorators import undoc
20
20
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22 # Code
22 # Code
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24
24
25 fs_encoding = sys.getfilesystemencoding()
25 fs_encoding = sys.getfilesystemencoding()
26
26
27 def _writable_dir(path):
27 def _writable_dir(path):
28 """Whether `path` is a directory, to which the user has write access."""
28 """Whether `path` is a directory, to which the user has write access."""
29 return os.path.isdir(path) and os.access(path, os.W_OK)
29 return os.path.isdir(path) and os.access(path, os.W_OK)
30
30
31 if sys.platform == 'win32':
31 if sys.platform == 'win32':
32 def _get_long_path_name(path):
32 def _get_long_path_name(path):
33 """Get a long path name (expand ~) on Windows using ctypes.
33 """Get a long path name (expand ~) on Windows using ctypes.
34
34
35 Examples
35 Examples
36 --------
36 --------
37
37
38 >>> get_long_path_name('c:\\docume~1')
38 >>> get_long_path_name('c:\\docume~1')
39 'c:\\\\Documents and Settings'
39 'c:\\\\Documents and Settings'
40
40
41 """
41 """
42 try:
42 try:
43 import ctypes
43 import ctypes
44 except ImportError:
44 except ImportError:
45 raise ImportError('you need to have ctypes installed for this to work')
45 raise ImportError('you need to have ctypes installed for this to work')
46 _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW
46 _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW
47 _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p,
47 _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p,
48 ctypes.c_uint ]
48 ctypes.c_uint ]
49
49
50 buf = ctypes.create_unicode_buffer(260)
50 buf = ctypes.create_unicode_buffer(260)
51 rv = _GetLongPathName(path, buf, 260)
51 rv = _GetLongPathName(path, buf, 260)
52 if rv == 0 or rv > 260:
52 if rv == 0 or rv > 260:
53 return path
53 return path
54 else:
54 else:
55 return buf.value
55 return buf.value
56 else:
56 else:
57 def _get_long_path_name(path):
57 def _get_long_path_name(path):
58 """Dummy no-op."""
58 """Dummy no-op."""
59 return path
59 return path
60
60
61
61
62
62
63 def get_long_path_name(path):
63 def get_long_path_name(path):
64 """Expand a path into its long form.
64 """Expand a path into its long form.
65
65
66 On Windows this expands any ~ in the paths. On other platforms, it is
66 On Windows this expands any ~ in the paths. On other platforms, it is
67 a null operation.
67 a null operation.
68 """
68 """
69 return _get_long_path_name(path)
69 return _get_long_path_name(path)
70
70
71
71
72 def unquote_filename(name, win32=(sys.platform=='win32')):
72 def unquote_filename(name, win32=(sys.platform=='win32')):
73 """ On Windows, remove leading and trailing quotes from filenames.
73 """ On Windows, remove leading and trailing quotes from filenames.
74
74
75 This function has been deprecated and should not be used any more:
75 This function has been deprecated and should not be used any more:
76 unquoting is now taken care of by :func:`IPython.utils.process.arg_split`.
76 unquoting is now taken care of by :func:`IPython.utils.process.arg_split`.
77 """
77 """
78 warn("'unquote_filename' is deprecated since IPython 5.0 and should not "
78 warn("'unquote_filename' is deprecated since IPython 5.0 and should not "
79 "be used anymore", DeprecationWarning, stacklevel=2)
79 "be used anymore", DeprecationWarning, stacklevel=2)
80 if win32:
80 if win32:
81 if name.startswith(("'", '"')) and name.endswith(("'", '"')):
81 if name.startswith(("'", '"')) and name.endswith(("'", '"')):
82 name = name[1:-1]
82 name = name[1:-1]
83 return name
83 return name
84
84
85
85
86 def compress_user(path):
86 def compress_user(path):
87 """Reverse of :func:`os.path.expanduser`
87 """Reverse of :func:`os.path.expanduser`
88 """
88 """
89 home = os.path.expanduser('~')
89 home = os.path.expanduser('~')
90 if path.startswith(home):
90 if path.startswith(home):
91 path = "~" + path[len(home):]
91 path = "~" + path[len(home):]
92 return path
92 return path
93
93
94 def get_py_filename(name, force_win32=None):
94 def get_py_filename(name, force_win32=None):
95 """Return a valid python filename in the current directory.
95 """Return a valid python filename in the current directory.
96
96
97 If the given name is not a file, it adds '.py' and searches again.
97 If the given name is not a file, it adds '.py' and searches again.
98 Raises IOError with an informative message if the file isn't found.
98 Raises IOError with an informative message if the file isn't found.
99 """
99 """
100
100
101 name = os.path.expanduser(name)
101 name = os.path.expanduser(name)
102 if force_win32 is not None:
102 if force_win32 is not None:
103 warn("The 'force_win32' argument to 'get_py_filename' is deprecated "
103 warn("The 'force_win32' argument to 'get_py_filename' is deprecated "
104 "since IPython 5.0 and should not be used anymore",
104 "since IPython 5.0 and should not be used anymore",
105 DeprecationWarning, stacklevel=2)
105 DeprecationWarning, stacklevel=2)
106 if not os.path.isfile(name) and not name.endswith('.py'):
106 if not os.path.isfile(name) and not name.endswith('.py'):
107 name += '.py'
107 name += '.py'
108 if os.path.isfile(name):
108 if os.path.isfile(name):
109 return name
109 return name
110 else:
110 else:
111 raise IOError('File `%r` not found.' % name)
111 raise IOError('File `%r` not found.' % name)
112
112
113
113
114 def filefind(filename, path_dirs=None):
114 def filefind(filename, path_dirs=None):
115 """Find a file by looking through a sequence of paths.
115 """Find a file by looking through a sequence of paths.
116
116
117 This iterates through a sequence of paths looking for a file and returns
117 This iterates through a sequence of paths looking for a file and returns
118 the full, absolute path of the first occurrence of the file. If no set of
118 the full, absolute path of the first occurrence of the file. If no set of
119 path dirs is given, the filename is tested as is, after running through
119 path dirs is given, the filename is tested as is, after running through
120 :func:`expandvars` and :func:`expanduser`. Thus a simple call::
120 :func:`expandvars` and :func:`expanduser`. Thus a simple call::
121
121
122 filefind('myfile.txt')
122 filefind('myfile.txt')
123
123
124 will find the file in the current working dir, but::
124 will find the file in the current working dir, but::
125
125
126 filefind('~/myfile.txt')
126 filefind('~/myfile.txt')
127
127
128 Will find the file in the users home directory. This function does not
128 Will find the file in the users home directory. This function does not
129 automatically try any paths, such as the cwd or the user's home directory.
129 automatically try any paths, such as the cwd or the user's home directory.
130
130
131 Parameters
131 Parameters
132 ----------
132 ----------
133 filename : str
133 filename : str
134 The filename to look for.
134 The filename to look for.
135 path_dirs : str, None or sequence of str
135 path_dirs : str, None or sequence of str
136 The sequence of paths to look for the file in. If None, the filename
136 The sequence of paths to look for the file in. If None, the filename
137 need to be absolute or be in the cwd. If a string, the string is
137 need to be absolute or be in the cwd. If a string, the string is
138 put into a sequence and the searched. If a sequence, walk through
138 put into a sequence and the searched. If a sequence, walk through
139 each element and join with ``filename``, calling :func:`expandvars`
139 each element and join with ``filename``, calling :func:`expandvars`
140 and :func:`expanduser` before testing for existence.
140 and :func:`expanduser` before testing for existence.
141
141
142 Returns
142 Returns
143 -------
143 -------
144 Raises :exc:`IOError` or returns absolute path to file.
144 Raises :exc:`IOError` or returns absolute path to file.
145 """
145 """
146
146
147 # If paths are quoted, abspath gets confused, strip them...
147 # If paths are quoted, abspath gets confused, strip them...
148 filename = filename.strip('"').strip("'")
148 filename = filename.strip('"').strip("'")
149 # If the input is an absolute path, just check it exists
149 # If the input is an absolute path, just check it exists
150 if os.path.isabs(filename) and os.path.isfile(filename):
150 if os.path.isabs(filename) and os.path.isfile(filename):
151 return filename
151 return filename
152
152
153 if path_dirs is None:
153 if path_dirs is None:
154 path_dirs = ("",)
154 path_dirs = ("",)
155 elif isinstance(path_dirs, str):
155 elif isinstance(path_dirs, str):
156 path_dirs = (path_dirs,)
156 path_dirs = (path_dirs,)
157
157
158 for path in path_dirs:
158 for path in path_dirs:
159 if path == '.': path = os.getcwd()
159 if path == '.': path = os.getcwd()
160 testname = expand_path(os.path.join(path, filename))
160 testname = expand_path(os.path.join(path, filename))
161 if os.path.isfile(testname):
161 if os.path.isfile(testname):
162 return os.path.abspath(testname)
162 return os.path.abspath(testname)
163
163
164 raise IOError("File %r does not exist in any of the search paths: %r" %
164 raise IOError("File %r does not exist in any of the search paths: %r" %
165 (filename, path_dirs) )
165 (filename, path_dirs) )
166
166
167
167
168 class HomeDirError(Exception):
168 class HomeDirError(Exception):
169 pass
169 pass
170
170
171
171
172 def get_home_dir(require_writable=False):
172 def get_home_dir(require_writable=False) -> str:
173 """Return the 'home' directory, as a unicode string.
173 """Return the 'home' directory, as a unicode string.
174
174
175 Uses os.path.expanduser('~'), and checks for writability.
175 Uses os.path.expanduser('~'), and checks for writability.
176
176
177 See stdlib docs for how this is determined.
177 See stdlib docs for how this is determined.
178 For Python <3.8, $HOME is first priority on *ALL* platforms.
178 For Python <3.8, $HOME is first priority on *ALL* platforms.
179 For Python >=3.8 on Windows, %HOME% is no longer considered.
179 For Python >=3.8 on Windows, %HOME% is no longer considered.
180
180
181 Parameters
181 Parameters
182 ----------
182 ----------
183
183
184 require_writable : bool [default: False]
184 require_writable : bool [default: False]
185 if True:
185 if True:
186 guarantees the return value is a writable directory, otherwise
186 guarantees the return value is a writable directory, otherwise
187 raises HomeDirError
187 raises HomeDirError
188 if False:
188 if False:
189 The path is resolved, but it is not guaranteed to exist or be writable.
189 The path is resolved, but it is not guaranteed to exist or be writable.
190 """
190 """
191
191
192 homedir = os.path.expanduser('~')
192 homedir = os.path.expanduser('~')
193 # Next line will make things work even when /home/ is a symlink to
193 # Next line will make things work even when /home/ is a symlink to
194 # /usr/home as it is on FreeBSD, for example
194 # /usr/home as it is on FreeBSD, for example
195 homedir = os.path.realpath(homedir)
195 homedir = os.path.realpath(homedir)
196
196
197 if not _writable_dir(homedir) and os.name == 'nt':
197 if not _writable_dir(homedir) and os.name == 'nt':
198 # expanduser failed, use the registry to get the 'My Documents' folder.
198 # expanduser failed, use the registry to get the 'My Documents' folder.
199 try:
199 try:
200 try:
200 import winreg as wreg
201 import winreg as wreg # Py 3
201 with wreg.OpenKey(
202 except ImportError:
203 import _winreg as wreg # Py 2
204 key = wreg.OpenKey(
205 wreg.HKEY_CURRENT_USER,
202 wreg.HKEY_CURRENT_USER,
206 r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
203 r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
207 )
204 ) as key:
208 homedir = wreg.QueryValueEx(key,'Personal')[0]
205 homedir = wreg.QueryValueEx(key,'Personal')[0]
209 key.Close()
210 except:
206 except:
211 pass
207 pass
212
208
213 if (not require_writable) or _writable_dir(homedir):
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 else:
212 else:
216 raise HomeDirError('%s is not a writable dir, '
213 raise HomeDirError('%s is not a writable dir, '
217 'set $HOME environment variable to override' % homedir)
214 'set $HOME environment variable to override' % homedir)
218
215
219 def get_xdg_dir():
216 def get_xdg_dir():
220 """Return the XDG_CONFIG_HOME, if it is defined and exists, else None.
217 """Return the XDG_CONFIG_HOME, if it is defined and exists, else None.
221
218
222 This is only for non-OS X posix (Linux,Unix,etc.) systems.
219 This is only for non-OS X posix (Linux,Unix,etc.) systems.
223 """
220 """
224
221
225 env = os.environ
222 env = os.environ
226
223
227 if os.name == 'posix' and sys.platform != 'darwin':
224 if os.name == 'posix' and sys.platform != 'darwin':
228 # Linux, Unix, AIX, etc.
225 # Linux, Unix, AIX, etc.
229 # use ~/.config if empty OR not set
226 # use ~/.config if empty OR not set
230 xdg = env.get("XDG_CONFIG_HOME", None) or os.path.join(get_home_dir(), '.config')
227 xdg = env.get("XDG_CONFIG_HOME", None) or os.path.join(get_home_dir(), '.config')
231 if xdg and _writable_dir(xdg):
228 if xdg and _writable_dir(xdg):
232 return py3compat.cast_unicode(xdg, fs_encoding)
229 return py3compat.cast_unicode(xdg, fs_encoding)
233
230
234 return None
231 return None
235
232
236
233
237 def get_xdg_cache_dir():
234 def get_xdg_cache_dir():
238 """Return the XDG_CACHE_HOME, if it is defined and exists, else None.
235 """Return the XDG_CACHE_HOME, if it is defined and exists, else None.
239
236
240 This is only for non-OS X posix (Linux,Unix,etc.) systems.
237 This is only for non-OS X posix (Linux,Unix,etc.) systems.
241 """
238 """
242
239
243 env = os.environ
240 env = os.environ
244
241
245 if os.name == 'posix' and sys.platform != 'darwin':
242 if os.name == 'posix' and sys.platform != 'darwin':
246 # Linux, Unix, AIX, etc.
243 # Linux, Unix, AIX, etc.
247 # use ~/.cache if empty OR not set
244 # use ~/.cache if empty OR not set
248 xdg = env.get("XDG_CACHE_HOME", None) or os.path.join(get_home_dir(), '.cache')
245 xdg = env.get("XDG_CACHE_HOME", None) or os.path.join(get_home_dir(), '.cache')
249 if xdg and _writable_dir(xdg):
246 if xdg and _writable_dir(xdg):
250 return py3compat.cast_unicode(xdg, fs_encoding)
247 return py3compat.cast_unicode(xdg, fs_encoding)
251
248
252 return None
249 return None
253
250
254
251
255 @undoc
252 @undoc
256 def get_ipython_dir():
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 from IPython.paths import get_ipython_dir
255 from IPython.paths import get_ipython_dir
259 return get_ipython_dir()
256 return get_ipython_dir()
260
257
261 @undoc
258 @undoc
262 def get_ipython_cache_dir():
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 from IPython.paths import get_ipython_cache_dir
261 from IPython.paths import get_ipython_cache_dir
265 return get_ipython_cache_dir()
262 return get_ipython_cache_dir()
266
263
267 @undoc
264 @undoc
268 def get_ipython_package_dir():
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 from IPython.paths import get_ipython_package_dir
267 from IPython.paths import get_ipython_package_dir
271 return get_ipython_package_dir()
268 return get_ipython_package_dir()
272
269
273 @undoc
270 @undoc
274 def get_ipython_module_path(module_str):
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 from IPython.paths import get_ipython_module_path
273 from IPython.paths import get_ipython_module_path
277 return get_ipython_module_path(module_str)
274 return get_ipython_module_path(module_str)
278
275
279 @undoc
276 @undoc
280 def locate_profile(profile='default'):
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 from IPython.paths import locate_profile
279 from IPython.paths import locate_profile
283 return locate_profile(profile=profile)
280 return locate_profile(profile=profile)
284
281
285 def expand_path(s):
282 def expand_path(s):
286 """Expand $VARS and ~names in a string, like a shell
283 """Expand $VARS and ~names in a string, like a shell
287
284
288 :Examples:
285 :Examples:
289
286
290 In [2]: os.environ['FOO']='test'
287 In [2]: os.environ['FOO']='test'
291
288
292 In [3]: expand_path('variable FOO is $FOO')
289 In [3]: expand_path('variable FOO is $FOO')
293 Out[3]: 'variable FOO is test'
290 Out[3]: 'variable FOO is test'
294 """
291 """
295 # This is a pretty subtle hack. When expand user is given a UNC path
292 # This is a pretty subtle hack. When expand user is given a UNC path
296 # on Windows (\\server\share$\%username%), os.path.expandvars, removes
293 # on Windows (\\server\share$\%username%), os.path.expandvars, removes
297 # the $ to get (\\server\share\%username%). I think it considered $
294 # the $ to get (\\server\share\%username%). I think it considered $
298 # alone an empty var. But, we need the $ to remains there (it indicates
295 # alone an empty var. But, we need the $ to remains there (it indicates
299 # a hidden share).
296 # a hidden share).
300 if os.name=='nt':
297 if os.name=='nt':
301 s = s.replace('$\\', 'IPYTHON_TEMP')
298 s = s.replace('$\\', 'IPYTHON_TEMP')
302 s = os.path.expandvars(os.path.expanduser(s))
299 s = os.path.expandvars(os.path.expanduser(s))
303 if os.name=='nt':
300 if os.name=='nt':
304 s = s.replace('IPYTHON_TEMP', '$\\')
301 s = s.replace('IPYTHON_TEMP', '$\\')
305 return s
302 return s
306
303
307
304
308 def unescape_glob(string):
305 def unescape_glob(string):
309 """Unescape glob pattern in `string`."""
306 """Unescape glob pattern in `string`."""
310 def unescape(s):
307 def unescape(s):
311 for pattern in '*[]!?':
308 for pattern in '*[]!?':
312 s = s.replace(r'\{0}'.format(pattern), pattern)
309 s = s.replace(r'\{0}'.format(pattern), pattern)
313 return s
310 return s
314 return '\\'.join(map(unescape, string.split('\\\\')))
311 return '\\'.join(map(unescape, string.split('\\\\')))
315
312
316
313
317 def shellglob(args):
314 def shellglob(args):
318 """
315 """
319 Do glob expansion for each element in `args` and return a flattened list.
316 Do glob expansion for each element in `args` and return a flattened list.
320
317
321 Unmatched glob pattern will remain as-is in the returned list.
318 Unmatched glob pattern will remain as-is in the returned list.
322
319
323 """
320 """
324 expanded = []
321 expanded = []
325 # Do not unescape backslash in Windows as it is interpreted as
322 # Do not unescape backslash in Windows as it is interpreted as
326 # path separator:
323 # path separator:
327 unescape = unescape_glob if sys.platform != 'win32' else lambda x: x
324 unescape = unescape_glob if sys.platform != 'win32' else lambda x: x
328 for a in args:
325 for a in args:
329 expanded.extend(glob.glob(a) or [unescape(a)])
326 expanded.extend(glob.glob(a) or [unescape(a)])
330 return expanded
327 return expanded
331
328
332
329
333 def target_outdated(target,deps):
330 def target_outdated(target,deps):
334 """Determine whether a target is out of date.
331 """Determine whether a target is out of date.
335
332
336 target_outdated(target,deps) -> 1/0
333 target_outdated(target,deps) -> 1/0
337
334
338 deps: list of filenames which MUST exist.
335 deps: list of filenames which MUST exist.
339 target: single filename which may or may not exist.
336 target: single filename which may or may not exist.
340
337
341 If target doesn't exist or is older than any file listed in deps, return
338 If target doesn't exist or is older than any file listed in deps, return
342 true, otherwise return false.
339 true, otherwise return false.
343 """
340 """
344 try:
341 try:
345 target_time = os.path.getmtime(target)
342 target_time = os.path.getmtime(target)
346 except os.error:
343 except os.error:
347 return 1
344 return 1
348 for dep in deps:
345 for dep in deps:
349 dep_time = os.path.getmtime(dep)
346 dep_time = os.path.getmtime(dep)
350 if dep_time > target_time:
347 if dep_time > target_time:
351 #print "For target",target,"Dep failed:",dep # dbg
348 #print "For target",target,"Dep failed:",dep # dbg
352 #print "times (dep,tar):",dep_time,target_time # dbg
349 #print "times (dep,tar):",dep_time,target_time # dbg
353 return 1
350 return 1
354 return 0
351 return 0
355
352
356
353
357 def target_update(target,deps,cmd):
354 def target_update(target,deps,cmd):
358 """Update a target with a given command given a list of dependencies.
355 """Update a target with a given command given a list of dependencies.
359
356
360 target_update(target,deps,cmd) -> runs cmd if target is outdated.
357 target_update(target,deps,cmd) -> runs cmd if target is outdated.
361
358
362 This is just a wrapper around target_outdated() which calls the given
359 This is just a wrapper around target_outdated() which calls the given
363 command if target is outdated."""
360 command if target is outdated."""
364
361
365 if target_outdated(target,deps):
362 if target_outdated(target,deps):
366 system(cmd)
363 system(cmd)
367
364
368
365
369 ENOLINK = 1998
366 ENOLINK = 1998
370
367
371 def link(src, dst):
368 def link(src, dst):
372 """Hard links ``src`` to ``dst``, returning 0 or errno.
369 """Hard links ``src`` to ``dst``, returning 0 or errno.
373
370
374 Note that the special errno ``ENOLINK`` will be returned if ``os.link`` isn't
371 Note that the special errno ``ENOLINK`` will be returned if ``os.link`` isn't
375 supported by the operating system.
372 supported by the operating system.
376 """
373 """
377
374
378 if not hasattr(os, "link"):
375 if not hasattr(os, "link"):
379 return ENOLINK
376 return ENOLINK
380 link_errno = 0
377 link_errno = 0
381 try:
378 try:
382 os.link(src, dst)
379 os.link(src, dst)
383 except OSError as e:
380 except OSError as e:
384 link_errno = e.errno
381 link_errno = e.errno
385 return link_errno
382 return link_errno
386
383
387
384
388 def link_or_copy(src, dst):
385 def link_or_copy(src, dst):
389 """Attempts to hardlink ``src`` to ``dst``, copying if the link fails.
386 """Attempts to hardlink ``src`` to ``dst``, copying if the link fails.
390
387
391 Attempts to maintain the semantics of ``shutil.copy``.
388 Attempts to maintain the semantics of ``shutil.copy``.
392
389
393 Because ``os.link`` does not overwrite files, a unique temporary file
390 Because ``os.link`` does not overwrite files, a unique temporary file
394 will be used if the target already exists, then that file will be moved
391 will be used if the target already exists, then that file will be moved
395 into place.
392 into place.
396 """
393 """
397
394
398 if os.path.isdir(dst):
395 if os.path.isdir(dst):
399 dst = os.path.join(dst, os.path.basename(src))
396 dst = os.path.join(dst, os.path.basename(src))
400
397
401 link_errno = link(src, dst)
398 link_errno = link(src, dst)
402 if link_errno == errno.EEXIST:
399 if link_errno == errno.EEXIST:
403 if os.stat(src).st_ino == os.stat(dst).st_ino:
400 if os.stat(src).st_ino == os.stat(dst).st_ino:
404 # dst is already a hard link to the correct file, so we don't need
401 # dst is already a hard link to the correct file, so we don't need
405 # to do anything else. If we try to link and rename the file
402 # to do anything else. If we try to link and rename the file
406 # anyway, we get duplicate files - see http://bugs.python.org/issue21876
403 # anyway, we get duplicate files - see http://bugs.python.org/issue21876
407 return
404 return
408
405
409 new_dst = dst + "-temp-%04X" %(random.randint(1, 16**4), )
406 new_dst = dst + "-temp-%04X" %(random.randint(1, 16**4), )
410 try:
407 try:
411 link_or_copy(src, new_dst)
408 link_or_copy(src, new_dst)
412 except:
409 except:
413 try:
410 try:
414 os.remove(new_dst)
411 os.remove(new_dst)
415 except OSError:
412 except OSError:
416 pass
413 pass
417 raise
414 raise
418 os.rename(new_dst, dst)
415 os.rename(new_dst, dst)
419 elif link_errno != 0:
416 elif link_errno != 0:
420 # Either link isn't supported, or the filesystem doesn't support
417 # Either link isn't supported, or the filesystem doesn't support
421 # linking, or 'src' and 'dst' are on different filesystems.
418 # linking, or 'src' and 'dst' are on different filesystems.
422 shutil.copy(src, dst)
419 shutil.copy(src, dst)
423
420
424 def ensure_dir_exists(path, mode=0o755):
421 def ensure_dir_exists(path, mode=0o755):
425 """ensure that a directory exists
422 """ensure that a directory exists
426
423
427 If it doesn't exist, try to create it and protect against a race condition
424 If it doesn't exist, try to create it and protect against a race condition
428 if another process is doing the same.
425 if another process is doing the same.
429
426
430 The default permissions are 755, which differ from os.makedirs default of 777.
427 The default permissions are 755, which differ from os.makedirs default of 777.
431 """
428 """
432 if not os.path.exists(path):
429 if not os.path.exists(path):
433 try:
430 try:
434 os.makedirs(path, mode=mode)
431 os.makedirs(path, mode=mode)
435 except OSError as e:
432 except OSError as e:
436 if e.errno != errno.EEXIST:
433 if e.errno != errno.EEXIST:
437 raise
434 raise
438 elif not os.path.isdir(path):
435 elif not os.path.isdir(path):
439 raise IOError("%r exists but is not a directory" % path)
436 raise IOError("%r exists but is not a directory" % path)
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
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
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