blob: a6f24485e7c01184c48ad215068e52b5a53ea8ba [file] [log] [blame]
David Scherer7aced172000-08-15 01:13:23 +00001#! /usr/bin/env python
Terry Jan Reedybee003c2014-09-19 22:37:24 -04002from __future__ import print_function
David Scherer7aced172000-08-15 01:13:23 +00003
David Scherer7aced172000-08-15 01:13:23 +00004import os
Kurt B. Kaiser6e44cc22002-11-30 06:18:00 +00005import os.path
David Scherer7aced172000-08-15 01:13:23 +00006import sys
7import string
8import getopt
9import re
Chui Tey5d2af632002-05-26 13:36:41 +000010import socket
11import time
Kurt B. Kaiser003091c2003-02-17 18:57:16 +000012import threading
Martin v. Löwise2b56242012-07-25 10:56:22 +020013import io
David Scherer7aced172000-08-15 01:13:23 +000014
15import linecache
16from code import InteractiveInterpreter
Terry Jan Reedy4ade2d22014-02-08 09:39:51 -050017from platform import python_version, system
David Scherer7aced172000-08-15 01:13:23 +000018
Kurt B. Kaiser2303b1c2003-11-24 05:26:16 +000019try:
Georg Brandl6634bf22008-05-20 07:13:37 +000020 from Tkinter import *
Kurt B. Kaiser2303b1c2003-11-24 05:26:16 +000021except ImportError:
Terry Jan Reedybee003c2014-09-19 22:37:24 -040022 print("** IDLE can't import Tkinter.\n"
23 "Your Python may not be configured for Tk. **", file=sys.__stderr__)
Kurt B. Kaiser2303b1c2003-11-24 05:26:16 +000024 sys.exit(1)
Georg Brandl6634bf22008-05-20 07:13:37 +000025import tkMessageBox
David Scherer7aced172000-08-15 01:13:23 +000026
Florent Xiclunad630c042010-04-02 07:24:52 +000027from idlelib.EditorWindow import EditorWindow, fixwordbreaks
28from idlelib.FileList import FileList
29from idlelib.ColorDelegator import ColorDelegator
30from idlelib.UndoDelegator import UndoDelegator
31from idlelib.OutputWindow import OutputWindow
32from idlelib.configHandler import idleConf
Florent Xiclunad630c042010-04-02 07:24:52 +000033from idlelib import rpc
34from idlelib import Debugger
35from idlelib import RemoteDebugger
36from idlelib import macosxSupport
Serhiy Storchaka4b2c4682015-05-17 13:53:54 +030037from idlelib import IOBinding
Chui Tey5d2af632002-05-26 13:36:41 +000038
Kurt B. Kaiserb9764192002-09-23 04:10:37 +000039IDENTCHARS = string.ascii_letters + string.digits + "_"
Kurt B. Kaiser013d6cc2009-04-04 07:03:48 +000040HOST = '127.0.0.1' # python execution server on localhost loopback
41PORT = 0 # someday pass in host, port for remote debug capability
Kurt B. Kaiserb9764192002-09-23 04:10:37 +000042
Kurt B. Kaisera00050f2003-05-08 20:26:55 +000043try:
44 from signal import SIGTERM
45except ImportError:
46 SIGTERM = 15
47
Kurt B. Kaiser49a5fe12004-07-04 01:25:56 +000048# Override warnings module to write to warning_stream. Initialize to send IDLE
49# internal warnings to the console. ScriptBinding.check_syntax() will
50# temporarily redirect the stream to the shell window to display warnings when
51# checking user's code.
Terry Jan Reedy8eab0082013-06-28 23:51:34 -040052warning_stream = sys.__stderr__ # None, at least on Windows, if no console.
53import warnings
54
55def idle_formatwarning(message, category, filename, lineno, line=None):
56 """Format warnings the IDLE way."""
57
58 s = "\nWarning (from warnings module):\n"
59 s += ' File \"%s\", line %s\n' % (filename, lineno)
60 if line is None:
61 line = linecache.getline(filename, lineno)
62 line = line.strip()
63 if line:
64 s += " %s\n" % line
65 s += "%s: %s\n" % (category.__name__, message)
66 return s
67
68def idle_showwarning(
69 message, category, filename, lineno, file=None, line=None):
70 """Show Idle-format warning (after replacing warnings.showwarning).
71
72 The differences are the formatter called, the file=None replacement,
73 which can be None, the capture of the consequence AttributeError,
74 and the output of a hard-coded prompt.
75 """
76 if file is None:
77 file = warning_stream
78 try:
79 file.write(idle_formatwarning(
80 message, category, filename, lineno, line=line))
81 file.write(">>> ")
82 except (AttributeError, IOError):
83 pass # if file (probably __stderr__) is invalid, skip warning.
84
85_warnings_showwarning = None
86
87def capture_warnings(capture):
88 "Replace warning.showwarning with idle_showwarning, or reverse."
89
90 global _warnings_showwarning
91 if capture:
92 if _warnings_showwarning is None:
93 _warnings_showwarning = warnings.showwarning
94 warnings.showwarning = idle_showwarning
95 else:
96 if _warnings_showwarning is not None:
97 warnings.showwarning = _warnings_showwarning
98 _warnings_showwarning = None
99
100capture_warnings(True)
Chui Tey5d2af632002-05-26 13:36:41 +0000101
Kurt B. Kaiserf7a88992004-11-13 21:05:58 +0000102def extended_linecache_checkcache(filename=None,
103 orig_checkcache=linecache.checkcache):
Kurt B. Kaiser45186c42002-10-23 04:48:08 +0000104 """Extend linecache.checkcache to preserve the <pyshell#...> entries
105
Kurt B. Kaiserf7a88992004-11-13 21:05:58 +0000106 Rather than repeating the linecache code, patch it to save the
107 <pyshell#...> entries, call the original linecache.checkcache()
Guilherme Polof198ac22009-08-14 14:03:07 +0000108 (skipping them), and then restore the saved entries.
Kurt B. Kaiserf7a88992004-11-13 21:05:58 +0000109
110 orig_checkcache is bound at definition time to the original
111 method, allowing it to be patched.
Kurt B. Kaiser45186c42002-10-23 04:48:08 +0000112 """
David Scherer7aced172000-08-15 01:13:23 +0000113 cache = linecache.cache
114 save = {}
Guilherme Polof198ac22009-08-14 14:03:07 +0000115 for key in list(cache):
116 if key[:1] + key[-1:] == '<>':
117 save[key] = cache.pop(key)
118 orig_checkcache(filename)
David Scherer7aced172000-08-15 01:13:23 +0000119 cache.update(save)
Kurt B. Kaiser6655e4b2002-12-31 16:03:23 +0000120
Kurt B. Kaiser81885592002-11-29 22:10:53 +0000121# Patch linecache.checkcache():
122linecache.checkcache = extended_linecache_checkcache
David Scherer7aced172000-08-15 01:13:23 +0000123
Kurt B. Kaiser45186c42002-10-23 04:48:08 +0000124
David Scherer7aced172000-08-15 01:13:23 +0000125class PyShellEditorWindow(EditorWindow):
Kurt B. Kaiser183403a2004-08-22 05:14:32 +0000126 "Regular text edit window in IDLE, supports breakpoints"
Kurt B. Kaiser45186c42002-10-23 04:48:08 +0000127
David Scherer7aced172000-08-15 01:13:23 +0000128 def __init__(self, *args):
Kurt B. Kaiser45186c42002-10-23 04:48:08 +0000129 self.breakpoints = []
Raymond Hettinger931237e2003-07-09 18:48:24 +0000130 EditorWindow.__init__(self, *args)
David Scherer7aced172000-08-15 01:13:23 +0000131 self.text.bind("<<set-breakpoint-here>>", self.set_breakpoint_here)
Kurt B. Kaiser45186c42002-10-23 04:48:08 +0000132 self.text.bind("<<clear-breakpoint-here>>", self.clear_breakpoint_here)
David Scherer7aced172000-08-15 01:13:23 +0000133 self.text.bind("<<open-python-shell>>", self.flist.open_shell)
134
Kurt B. Kaiserbfed3462002-12-14 04:38:51 +0000135 self.breakpointPath = os.path.join(idleConf.GetUserCfgDir(),
136 'breakpoints.lst')
Chui Teya2adb0f2002-11-04 22:14:54 +0000137 # whenever a file is changed, restore breakpoints
Kurt B. Kaiserbfed3462002-12-14 04:38:51 +0000138 def filename_changed_hook(old_hook=self.io.filename_change_hook,
139 self=self):
Chui Teya2adb0f2002-11-04 22:14:54 +0000140 self.restore_file_breaks()
141 old_hook()
142 self.io.set_filename_change_hook(filename_changed_hook)
Roger Serwyd7c9d9c2013-04-02 22:37:12 -0500143 if self.io.filename:
144 self.restore_file_breaks()
Terry Jan Reedy25327d42014-08-08 23:33:11 -0400145 self.color_breakpoint_text()
Chui Teya2adb0f2002-11-04 22:14:54 +0000146
Andrew Svetlov5018db72012-11-01 22:39:14 +0200147 rmenu_specs = [
148 ("Cut", "<<cut>>", "rmenu_check_cut"),
149 ("Copy", "<<copy>>", "rmenu_check_copy"),
150 ("Paste", "<<paste>>", "rmenu_check_paste"),
151 ("Set Breakpoint", "<<set-breakpoint-here>>", None),
152 ("Clear Breakpoint", "<<clear-breakpoint-here>>", None)
153 ]
David Scherer7aced172000-08-15 01:13:23 +0000154
Terry Jan Reedy25327d42014-08-08 23:33:11 -0400155 def color_breakpoint_text(self, color=True):
156 "Turn colorizing of breakpoint text on or off"
Terry Jan Reedy08da46e2014-10-12 22:58:42 -0400157 if self.io is None:
158 # possible due to update in restore_file_breaks
159 return
Terry Jan Reedy25327d42014-08-08 23:33:11 -0400160 if color:
Terry Jan Reedy35aa5d02015-11-12 15:02:50 -0500161 theme = idleConf.CurrentTheme()
Terry Jan Reedy25327d42014-08-08 23:33:11 -0400162 cfg = idleConf.GetHighlight(theme, "break")
163 else:
164 cfg = {'foreground': '', 'background': ''}
165 self.text.tag_config('BREAK', cfg)
166
Chui Teya2adb0f2002-11-04 22:14:54 +0000167 def set_breakpoint(self, lineno):
168 text = self.text
169 filename = self.io.filename
170 text.tag_add("BREAK", "%d.0" % lineno, "%d.0" % (lineno+1))
171 try:
Terry Jan Reedy28489252015-05-15 23:03:11 -0400172 self.breakpoints.index(lineno)
Chui Teya2adb0f2002-11-04 22:14:54 +0000173 except ValueError: # only add if missing, i.e. do once
174 self.breakpoints.append(lineno)
175 try: # update the subprocess debugger
176 debug = self.flist.pyshell.interp.debugger
177 debug.set_breakpoint_here(filename, lineno)
178 except: # but debugger may not be active right now....
179 pass
180
David Scherer7aced172000-08-15 01:13:23 +0000181 def set_breakpoint_here(self, event=None):
Kurt B. Kaiser45186c42002-10-23 04:48:08 +0000182 text = self.text
183 filename = self.io.filename
184 if not filename:
185 text.bell()
David Scherer7aced172000-08-15 01:13:23 +0000186 return
Kurt B. Kaiser45186c42002-10-23 04:48:08 +0000187 lineno = int(float(text.index("insert")))
Chui Teya2adb0f2002-11-04 22:14:54 +0000188 self.set_breakpoint(lineno)
David Scherer7aced172000-08-15 01:13:23 +0000189
Kurt B. Kaiser669f4c32002-06-20 04:01:47 +0000190 def clear_breakpoint_here(self, event=None):
Kurt B. Kaiser45186c42002-10-23 04:48:08 +0000191 text = self.text
192 filename = self.io.filename
193 if not filename:
194 text.bell()
Kurt B. Kaiser669f4c32002-06-20 04:01:47 +0000195 return
Kurt B. Kaiser45186c42002-10-23 04:48:08 +0000196 lineno = int(float(text.index("insert")))
197 try:
198 self.breakpoints.remove(lineno)
199 except:
200 pass
201 text.tag_remove("BREAK", "insert linestart",\
202 "insert lineend +1char")
203 try:
204 debug = self.flist.pyshell.interp.debugger
205 debug.clear_breakpoint_here(filename, lineno)
206 except:
207 pass
208
209 def clear_file_breaks(self):
210 if self.breakpoints:
211 text = self.text
212 filename = self.io.filename
213 if not filename:
214 text.bell()
215 return
216 self.breakpoints = []
217 text.tag_remove("BREAK", "1.0", END)
218 try:
219 debug = self.flist.pyshell.interp.debugger
220 debug.clear_file_breaks(filename)
221 except:
222 pass
223
Chui Teya2adb0f2002-11-04 22:14:54 +0000224 def store_file_breaks(self):
Kurt B. Kaiserbfed3462002-12-14 04:38:51 +0000225 "Save breakpoints when file is saved"
226 # XXX 13 Dec 2002 KBK Currently the file must be saved before it can
227 # be run. The breaks are saved at that time. If we introduce
228 # a temporary file save feature the save breaks functionality
229 # needs to be re-verified, since the breaks at the time the
230 # temp file is created may differ from the breaks at the last
Kurt B. Kaiser7f38ec02003-05-15 03:19:42 +0000231 # permanent save of the file. Currently, a break introduced
232 # after a save will be effective, but not persistent.
233 # This is necessary to keep the saved breaks synched with the
234 # saved file.
Kurt B. Kaiserbfed3462002-12-14 04:38:51 +0000235 #
Terry Jan Reedy987a02b2014-10-12 01:10:58 -0400236 # Breakpoints are set as tagged ranges in the text.
237 # Since a modified file has to be saved before it is
Kurt B. Kaiserbfed3462002-12-14 04:38:51 +0000238 # run, and since self.breakpoints (from which the subprocess
239 # debugger is loaded) is updated during the save, the visible
240 # breaks stay synched with the subprocess even if one of these
241 # unexpected breakpoint deletions occurs.
242 breaks = self.breakpoints
243 filename = self.io.filename
Chui Teya2adb0f2002-11-04 22:14:54 +0000244 try:
Ned Deily40ad0412011-12-14 14:57:43 -0800245 with open(self.breakpointPath,"r") as old_file:
246 lines = old_file.readlines()
Chui Teya2adb0f2002-11-04 22:14:54 +0000247 except IOError:
Kurt B. Kaiserbfed3462002-12-14 04:38:51 +0000248 lines = []
Ned Deily40ad0412011-12-14 14:57:43 -0800249 try:
250 with open(self.breakpointPath,"w") as new_file:
251 for line in lines:
252 if not line.startswith(filename + '='):
253 new_file.write(line)
254 self.update_breakpoints()
255 breaks = self.breakpoints
256 if breaks:
257 new_file.write(filename + '=' + str(breaks) + '\n')
258 except IOError as err:
259 if not getattr(self.root, "breakpoint_error_displayed", False):
260 self.root.breakpoint_error_displayed = True
261 tkMessageBox.showerror(title='IDLE Error',
262 message='Unable to update breakpoint list:\n%s'
263 % str(err),
264 parent=self.text)
Chui Teya2adb0f2002-11-04 22:14:54 +0000265
266 def restore_file_breaks(self):
267 self.text.update() # this enables setting "BREAK" tags to be visible
Roger Serwyd7c9d9c2013-04-02 22:37:12 -0500268 if self.io is None:
269 # can happen if IDLE closes due to the .update() call
270 return
Kurt B. Kaiserbfed3462002-12-14 04:38:51 +0000271 filename = self.io.filename
272 if filename is None:
273 return
Chui Tey69371d62002-11-04 23:39:45 +0000274 if os.path.isfile(self.breakpointPath):
Kurt B. Kaiserbfed3462002-12-14 04:38:51 +0000275 lines = open(self.breakpointPath,"r").readlines()
Chui Tey69371d62002-11-04 23:39:45 +0000276 for line in lines:
Kurt B. Kaiserbfed3462002-12-14 04:38:51 +0000277 if line.startswith(filename + '='):
Kurt B. Kaiser6655e4b2002-12-31 16:03:23 +0000278 breakpoint_linenumbers = eval(line[len(filename)+1:])
Chui Tey69371d62002-11-04 23:39:45 +0000279 for breakpoint_linenumber in breakpoint_linenumbers:
280 self.set_breakpoint(breakpoint_linenumber)
Chui Teya2adb0f2002-11-04 22:14:54 +0000281
Kurt B. Kaiserbfed3462002-12-14 04:38:51 +0000282 def update_breakpoints(self):
283 "Retrieves all the breakpoints in the current window"
Chui Teya2adb0f2002-11-04 22:14:54 +0000284 text = self.text
Kurt B. Kaiserbfed3462002-12-14 04:38:51 +0000285 ranges = text.tag_ranges("BREAK")
286 linenumber_list = self.ranges_to_linenumbers(ranges)
287 self.breakpoints = linenumber_list
288
289 def ranges_to_linenumbers(self, ranges):
290 lines = []
291 for index in range(0, len(ranges), 2):
Andrew Svetlov8a15c372012-07-31 19:51:27 +0300292 lineno = int(float(ranges[index].string))
293 end = int(float(ranges[index+1].string))
Kurt B. Kaiserbfed3462002-12-14 04:38:51 +0000294 while lineno < end:
295 lines.append(lineno)
296 lineno += 1
297 return lines
298
Kurt B. Kaiser11220fa2002-12-24 00:57:22 +0000299# XXX 13 Dec 2002 KBK Not used currently
Kurt B. Kaiserbfed3462002-12-14 04:38:51 +0000300# def saved_change_hook(self):
301# "Extend base method - clear breaks if module is modified"
302# if not self.get_saved():
303# self.clear_file_breaks()
304# EditorWindow.saved_change_hook(self)
Kurt B. Kaiser45186c42002-10-23 04:48:08 +0000305
306 def _close(self):
307 "Extend base method - clear breaks when module is closed"
308 self.clear_file_breaks()
309 EditorWindow._close(self)
Kurt B. Kaiser6655e4b2002-12-31 16:03:23 +0000310
David Scherer7aced172000-08-15 01:13:23 +0000311
312class PyShellFileList(FileList):
Kurt B. Kaiser183403a2004-08-22 05:14:32 +0000313 "Extend base class: IDLE supports a shell and breakpoints"
David Scherer7aced172000-08-15 01:13:23 +0000314
Kurt B. Kaiser183403a2004-08-22 05:14:32 +0000315 # override FileList's class variable, instances return PyShellEditorWindow
316 # instead of EditorWindow when new edit windows are created.
David Scherer7aced172000-08-15 01:13:23 +0000317 EditorWindow = PyShellEditorWindow
318
319 pyshell = None
320
321 def open_shell(self, event=None):
322 if self.pyshell:
Kurt B. Kaiser183403a2004-08-22 05:14:32 +0000323 self.pyshell.top.wakeup()
David Scherer7aced172000-08-15 01:13:23 +0000324 else:
325 self.pyshell = PyShell(self)
Kurt B. Kaiseraf3eb872004-01-21 18:54:30 +0000326 if self.pyshell:
327 if not self.pyshell.begin():
328 return None
David Scherer7aced172000-08-15 01:13:23 +0000329 return self.pyshell
330
331
332class ModifiedColorDelegator(ColorDelegator):
Kurt B. Kaiser83118c62002-06-24 17:03:37 +0000333 "Extend base class: colorizer for the shell window itself"
Kurt B. Kaiser6655e4b2002-12-31 16:03:23 +0000334
Steven M. Gavab77d3432002-03-02 07:16:21 +0000335 def __init__(self):
336 ColorDelegator.__init__(self)
337 self.LoadTagDefs()
David Scherer7aced172000-08-15 01:13:23 +0000338
339 def recolorize_main(self):
340 self.tag_remove("TODO", "1.0", "iomark")
341 self.tag_add("SYNC", "1.0", "iomark")
342 ColorDelegator.recolorize_main(self)
Kurt B. Kaiser6655e4b2002-12-31 16:03:23 +0000343
Steven M. Gavab77d3432002-03-02 07:16:21 +0000344 def LoadTagDefs(self):
345 ColorDelegator.LoadTagDefs(self)
Terry Jan Reedy35aa5d02015-11-12 15:02:50 -0500346 theme = idleConf.CurrentTheme()
Steven M. Gavab77d3432002-03-02 07:16:21 +0000347 self.tagdefs.update({
348 "stdin": {'background':None,'foreground':None},
349 "stdout": idleConf.GetHighlight(theme, "stdout"),
350 "stderr": idleConf.GetHighlight(theme, "stderr"),
351 "console": idleConf.GetHighlight(theme, "console"),
Steven M. Gavab77d3432002-03-02 07:16:21 +0000352 })
David Scherer7aced172000-08-15 01:13:23 +0000353
Ned Deily5e247b72012-05-31 09:17:29 -0700354 def removecolors(self):
355 # Don't remove shell color tags before "iomark"
356 for tag in self.tagdefs:
357 self.tag_remove(tag, "iomark", "end")
358
David Scherer7aced172000-08-15 01:13:23 +0000359class ModifiedUndoDelegator(UndoDelegator):
Kurt B. Kaiser83118c62002-06-24 17:03:37 +0000360 "Extend base class: forbid insert/delete before the I/O mark"
David Scherer7aced172000-08-15 01:13:23 +0000361
362 def insert(self, index, chars, tags=None):
363 try:
364 if self.delegate.compare(index, "<", "iomark"):
365 self.delegate.bell()
366 return
367 except TclError:
368 pass
369 UndoDelegator.insert(self, index, chars, tags)
370
371 def delete(self, index1, index2=None):
372 try:
373 if self.delegate.compare(index1, "<", "iomark"):
374 self.delegate.bell()
375 return
376 except TclError:
377 pass
378 UndoDelegator.delete(self, index1, index2)
379
Kurt B. Kaiser67fd0ea2003-05-24 20:59:15 +0000380
381class MyRPCClient(rpc.RPCClient):
382
383 def handle_EOF(self):
384 "Override the base class - just re-raise EOFError"
385 raise EOFError
386
Kurt B. Kaiser8d1f11b2003-05-26 22:20:34 +0000387
David Scherer7aced172000-08-15 01:13:23 +0000388class ModifiedInterpreter(InteractiveInterpreter):
389
390 def __init__(self, tkconsole):
391 self.tkconsole = tkconsole
392 locals = sys.modules['__main__'].__dict__
393 InteractiveInterpreter.__init__(self, locals=locals)
Kurt B. Kaiser94bd7742001-07-14 00:13:28 +0000394 self.save_warnings_filters = None
Kurt B. Kaiser6f805942003-05-24 21:12:46 +0000395 self.restarting = False
Kurt B. Kaiser013d6cc2009-04-04 07:03:48 +0000396 self.subprocess_arglist = None
397 self.port = PORT
Ned Deily86d669b2011-10-30 19:58:04 -0700398 self.original_compiler_flags = self.compile.compiler.flags
David Scherer7aced172000-08-15 01:13:23 +0000399
Roger Serwy16ce43a2013-06-11 22:13:17 -0500400 _afterid = None
Chui Tey5d2af632002-05-26 13:36:41 +0000401 rpcclt = None
402 rpcpid = None
403
Kurt B. Kaiser6655e4b2002-12-31 16:03:23 +0000404 def spawn_subprocess(self):
Florent Xiclunac8a730b2010-03-25 20:32:07 +0000405 if self.subprocess_arglist is None:
Kurt B. Kaiser013d6cc2009-04-04 07:03:48 +0000406 self.subprocess_arglist = self.build_subprocess_arglist()
Kurt B. Kaiser62df0442003-05-28 01:47:46 +0000407 args = self.subprocess_arglist
Kurt B. Kaiserb7855182003-08-14 14:54:28 +0000408 self.rpcpid = os.spawnv(os.P_NOWAIT, sys.executable, args)
Kurt B. Kaiser63857a42002-09-05 02:31:20 +0000409
Tony Lowndsf53dec22002-12-20 04:24:43 +0000410 def build_subprocess_arglist(self):
Kurt B. Kaiser013d6cc2009-04-04 07:03:48 +0000411 assert (self.port!=0), (
412 "Socket should have been assigned a port number.")
Tony Lownds2398d572003-05-13 15:28:21 +0000413 w = ['-W' + s for s in sys.warnoptions]
Georg Brandld0761532006-10-12 07:57:21 +0000414 if 1/2 > 0: # account for new division
415 w.append('-Qnew')
Tony Lownds2398d572003-05-13 15:28:21 +0000416 # Maybe IDLE is installed and is being accessed via sys.path,
417 # or maybe it's not installed and the idle.py script is being
418 # run from the IDLE source directory.
Kurt B. Kaiser62df0442003-05-28 01:47:46 +0000419 del_exitf = idleConf.GetOption('main', 'General', 'delete-exitfunc',
420 default=False, type='bool')
Tony Lownds2398d572003-05-13 15:28:21 +0000421 if __name__ == 'idlelib.PyShell':
Walter Dörwald70a6b492004-02-12 17:35:32 +0000422 command = "__import__('idlelib.run').run.main(%r)" % (del_exitf,)
Tony Lowndsf2324b92002-09-29 00:34:10 +0000423 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000424 command = "__import__('run').main(%r)" % (del_exitf,)
Kurt B. Kaiserb7855182003-08-14 14:54:28 +0000425 if sys.platform[:3] == 'win' and ' ' in sys.executable:
426 # handle embedded space in path by quoting the argument
427 decorated_exec = '"%s"' % sys.executable
428 else:
429 decorated_exec = sys.executable
430 return [decorated_exec] + w + ["-c", command, str(self.port)]
Tony Lowndsf2324b92002-09-29 00:34:10 +0000431
Kurt B. Kaiser63857a42002-09-05 02:31:20 +0000432 def start_subprocess(self):
Kurt B. Kaiser013d6cc2009-04-04 07:03:48 +0000433 addr = (HOST, self.port)
434 # GUI makes several attempts to acquire socket, listens for connection
Kurt B. Kaiser5db48432003-05-15 03:40:51 +0000435 for i in range(3):
Chui Tey5d2af632002-05-26 13:36:41 +0000436 time.sleep(i)
437 try:
Kurt B. Kaiser67fd0ea2003-05-24 20:59:15 +0000438 self.rpcclt = MyRPCClient(addr)
Chui Tey5d2af632002-05-26 13:36:41 +0000439 break
Terry Jan Reedy28489252015-05-15 23:03:11 -0400440 except socket.error:
Kurt B. Kaiseraf3eb872004-01-21 18:54:30 +0000441 pass
Chui Tey5d2af632002-05-26 13:36:41 +0000442 else:
Kurt B. Kaiseraf3eb872004-01-21 18:54:30 +0000443 self.display_port_binding_error()
444 return None
Kurt B. Kaiser013d6cc2009-04-04 07:03:48 +0000445 # if PORT was 0, system will assign an 'ephemeral' port. Find it out:
446 self.port = self.rpcclt.listening_sock.getsockname()[1]
447 # if PORT was not 0, probably working with a remote execution server
448 if PORT != 0:
449 # To allow reconnection within the 2MSL wait (cf. Stevens TCP
450 # V1, 18.6), set SO_REUSEADDR. Note that this can be problematic
451 # on Windows since the implementation allows two active sockets on
452 # the same address!
453 self.rpcclt.listening_sock.setsockopt(socket.SOL_SOCKET,
454 socket.SO_REUSEADDR, 1)
455 self.spawn_subprocess()
456 #time.sleep(20) # test to simulate GUI not accepting connection
Kurt B. Kaiserb4179362002-07-26 00:06:42 +0000457 # Accept the connection from the Python execution server
Kurt B. Kaiseraf3eb872004-01-21 18:54:30 +0000458 self.rpcclt.listening_sock.settimeout(10)
459 try:
460 self.rpcclt.accept()
Terry Jan Reedy28489252015-05-15 23:03:11 -0400461 except socket.timeout:
Kurt B. Kaiseraf3eb872004-01-21 18:54:30 +0000462 self.display_no_subprocess_error()
463 return None
Serhiy Storchaka9abc8302013-01-25 15:30:35 +0200464 self.rpcclt.register("console", self.tkconsole)
465 self.rpcclt.register("stdin", self.tkconsole.stdin)
Kurt B. Kaiser969de452002-06-12 03:28:57 +0000466 self.rpcclt.register("stdout", self.tkconsole.stdout)
467 self.rpcclt.register("stderr", self.tkconsole.stderr)
Chui Tey5d2af632002-05-26 13:36:41 +0000468 self.rpcclt.register("flist", self.tkconsole.flist)
Kurt B. Kaiser8cd0def2003-01-31 05:06:43 +0000469 self.rpcclt.register("linecache", linecache)
Kurt B. Kaiser9f366092003-06-02 01:50:19 +0000470 self.rpcclt.register("interp", self)
Terry Jan Reedyb98000a2012-01-31 02:09:25 -0500471 self.transfer_path(with_cwd=True)
Chui Tey5d2af632002-05-26 13:36:41 +0000472 self.poll_subprocess()
Kurt B. Kaiseraf3eb872004-01-21 18:54:30 +0000473 return self.rpcclt
Chui Tey5d2af632002-05-26 13:36:41 +0000474
Terry Jan Reedy8755d782015-07-31 22:34:31 -0400475 def restart_subprocess(self, with_cwd=False, filename=''):
Kurt B. Kaiser6f805942003-05-24 21:12:46 +0000476 if self.restarting:
Kurt B. Kaiseraf3eb872004-01-21 18:54:30 +0000477 return self.rpcclt
Kurt B. Kaiser6f805942003-05-24 21:12:46 +0000478 self.restarting = True
Kurt B. Kaiser63857a42002-09-05 02:31:20 +0000479 # close only the subprocess debugger
Kurt B. Kaiser45186c42002-10-23 04:48:08 +0000480 debug = self.getdebugger()
481 if debug:
Kurt B. Kaiser003091c2003-02-17 18:57:16 +0000482 try:
Kurt B. Kaiser9ec454e2003-05-12 02:33:47 +0000483 # Only close subprocess debugger, don't unregister gui_adap!
Kurt B. Kaiser003091c2003-02-17 18:57:16 +0000484 RemoteDebugger.close_subprocess_debugger(self.rpcclt)
485 except:
486 pass
487 # Kill subprocess, spawn a new one, accept connection.
Kurt B. Kaisera00050f2003-05-08 20:26:55 +0000488 self.rpcclt.close()
489 self.unix_terminate()
Kurt B. Kaiser7f38ec02003-05-15 03:19:42 +0000490 console = self.tkconsole
Kurt B. Kaiser6f805942003-05-24 21:12:46 +0000491 was_executing = console.executing
Kurt B. Kaiser7f38ec02003-05-15 03:19:42 +0000492 console.executing = False
Kurt B. Kaiser63857a42002-09-05 02:31:20 +0000493 self.spawn_subprocess()
Kurt B. Kaiseraf3eb872004-01-21 18:54:30 +0000494 try:
495 self.rpcclt.accept()
Terry Jan Reedy28489252015-05-15 23:03:11 -0400496 except socket.timeout:
Kurt B. Kaiseraf3eb872004-01-21 18:54:30 +0000497 self.display_no_subprocess_error()
498 return None
Terry Jan Reedyb98000a2012-01-31 02:09:25 -0500499 self.transfer_path(with_cwd=with_cwd)
Roger Serwyad8cad32013-04-03 00:42:24 -0500500 console.stop_readline()
Kurt B. Kaiser1061e722003-01-04 01:43:53 +0000501 # annotate restart in shell window and mark it
Kurt B. Kaiser4cc5ef52003-01-22 00:23:23 +0000502 console.text.delete("iomark", "end-1c")
Terry Jan Reedyb50d3b22015-09-02 22:07:31 -0400503 tag = 'RESTART: ' + (filename if filename else 'Shell')
Terry Jan Reedy8755d782015-07-31 22:34:31 -0400504 halfbar = ((int(console.width) -len(tag) - 4) // 2) * '='
505 console.write("\n{0} {1} {0}".format(halfbar, tag))
Kurt B. Kaiser1061e722003-01-04 01:43:53 +0000506 console.text.mark_set("restart", "end-1c")
507 console.text.mark_gravity("restart", "left")
Terry Jan Reedy8755d782015-07-31 22:34:31 -0400508 if not filename:
509 console.showprompt()
Kurt B. Kaiser003091c2003-02-17 18:57:16 +0000510 # restart subprocess debugger
Kurt B. Kaiser45186c42002-10-23 04:48:08 +0000511 if debug:
Kurt B. Kaiser9ec454e2003-05-12 02:33:47 +0000512 # Restarted debugger connects to current instance of debug GUI
Terry Jan Reedy28489252015-05-15 23:03:11 -0400513 RemoteDebugger.restart_subprocess_debugger(self.rpcclt)
Kurt B. Kaiser45186c42002-10-23 04:48:08 +0000514 # reload remote debugger breakpoints for all PyShellEditWindows
515 debug.load_breakpoints()
Ned Deily86d669b2011-10-30 19:58:04 -0700516 self.compile.compiler.flags = self.original_compiler_flags
Kurt B. Kaiser6f805942003-05-24 21:12:46 +0000517 self.restarting = False
Kurt B. Kaiseraf3eb872004-01-21 18:54:30 +0000518 return self.rpcclt
Kurt B. Kaiser45186c42002-10-23 04:48:08 +0000519
Kurt B. Kaiser003091c2003-02-17 18:57:16 +0000520 def __request_interrupt(self):
Kurt B. Kaisera00050f2003-05-08 20:26:55 +0000521 self.rpcclt.remotecall("exec", "interrupt_the_server", (), {})
Kurt B. Kaiser003091c2003-02-17 18:57:16 +0000522
523 def interrupt_subprocess(self):
Kurt B. Kaisera00050f2003-05-08 20:26:55 +0000524 threading.Thread(target=self.__request_interrupt).start()
Kurt B. Kaiser003091c2003-02-17 18:57:16 +0000525
Kurt B. Kaisera00050f2003-05-08 20:26:55 +0000526 def kill_subprocess(self):
Roger Serwy16ce43a2013-06-11 22:13:17 -0500527 if self._afterid is not None:
528 self.tkconsole.text.after_cancel(self._afterid)
Kurt B. Kaiseraf3eb872004-01-21 18:54:30 +0000529 try:
530 self.rpcclt.close()
531 except AttributeError: # no socket
532 pass
Kurt B. Kaisera00050f2003-05-08 20:26:55 +0000533 self.unix_terminate()
534 self.tkconsole.executing = False
535 self.rpcclt = None
Kurt B. Kaiser11c53e22003-03-22 19:40:19 +0000536
Kurt B. Kaisera00050f2003-05-08 20:26:55 +0000537 def unix_terminate(self):
538 "UNIX: make sure subprocess is terminated and collect status"
539 if hasattr(os, 'kill'):
540 try:
541 os.kill(self.rpcpid, SIGTERM)
542 except OSError:
543 # process already terminated:
544 return
545 else:
546 try:
547 os.waitpid(self.rpcpid, 0)
548 except OSError:
549 return
Kurt B. Kaiser11c53e22003-03-22 19:40:19 +0000550
Terry Jan Reedyb98000a2012-01-31 02:09:25 -0500551 def transfer_path(self, with_cwd=False):
552 if with_cwd: # Issue 13506
553 path = [''] # include Current Working Directory
554 path.extend(sys.path)
555 else:
556 path = sys.path
Terry Jan Reedy1d4ae482012-01-31 02:55:32 -0500557
Kurt B. Kaiserf06eed02002-12-11 04:42:04 +0000558 self.runcommand("""if 1:
559 import sys as _sys
Walter Dörwald70a6b492004-02-12 17:35:32 +0000560 _sys.path = %r
Kurt B. Kaiserf06eed02002-12-11 04:42:04 +0000561 del _sys
Terry Jan Reedyb98000a2012-01-31 02:09:25 -0500562 \n""" % (path,))
Kurt B. Kaiserf06eed02002-12-11 04:42:04 +0000563
Chui Tey5d2af632002-05-26 13:36:41 +0000564 active_seq = None
565
566 def poll_subprocess(self):
567 clt = self.rpcclt
568 if clt is None:
569 return
Kurt B. Kaiser003091c2003-02-17 18:57:16 +0000570 try:
Kurt B. Kaisera00050f2003-05-08 20:26:55 +0000571 response = clt.pollresponse(self.active_seq, wait=0.05)
572 except (EOFError, IOError, KeyboardInterrupt):
573 # lost connection or subprocess terminated itself, restart
574 # [the KBI is from rpc.SocketIO.handle_EOF()]
Kurt B. Kaiser67fd0ea2003-05-24 20:59:15 +0000575 if self.tkconsole.closing:
576 return
Kurt B. Kaiser003091c2003-02-17 18:57:16 +0000577 response = None
Kurt B. Kaiser003091c2003-02-17 18:57:16 +0000578 self.restart_subprocess()
Chui Tey5d2af632002-05-26 13:36:41 +0000579 if response:
580 self.tkconsole.resetoutput()
581 self.active_seq = None
582 how, what = response
Kurt B. Kaiserbc286132003-01-25 21:33:40 +0000583 console = self.tkconsole.console
Chui Tey5d2af632002-05-26 13:36:41 +0000584 if how == "OK":
585 if what is not None:
Terry Jan Reedybee003c2014-09-19 22:37:24 -0400586 print(repr(what), file=console)
Chui Tey5d2af632002-05-26 13:36:41 +0000587 elif how == "EXCEPTION":
Chui Tey5d2af632002-05-26 13:36:41 +0000588 if self.tkconsole.getvar("<<toggle-jit-stack-viewer>>"):
589 self.remote_stack_viewer()
590 elif how == "ERROR":
Kurt B. Kaiser0930c432002-12-06 21:45:24 +0000591 errmsg = "PyShell.ModifiedInterpreter: Subprocess ERROR:\n"
Terry Jan Reedybee003c2014-09-19 22:37:24 -0400592 print(errmsg, what, file=sys.__stderr__)
593 print(errmsg, what, file=console)
Kurt B. Kaiserbc286132003-01-25 21:33:40 +0000594 # we received a response to the currently active seq number:
Kurt B. Kaiserd112bc72006-08-16 05:01:42 +0000595 try:
596 self.tkconsole.endexecuting()
597 except AttributeError: # shell may have closed
598 pass
Kurt B. Kaiser88957d82003-05-19 23:11:51 +0000599 # Reschedule myself
600 if not self.tkconsole.closing:
Roger Serwy16ce43a2013-06-11 22:13:17 -0500601 self._afterid = self.tkconsole.text.after(
602 self.tkconsole.pollinterval, self.poll_subprocess)
Chui Tey5d2af632002-05-26 13:36:41 +0000603
Kurt B. Kaiser45186c42002-10-23 04:48:08 +0000604 debugger = None
605
606 def setdebugger(self, debugger):
607 self.debugger = debugger
608
609 def getdebugger(self):
610 return self.debugger
611
Kurt B. Kaiser9f366092003-06-02 01:50:19 +0000612 def open_remote_stack_viewer(self):
613 """Initiate the remote stack viewer from a separate thread.
614
615 This method is called from the subprocess, and by returning from this
616 method we allow the subprocess to unblock. After a bit the shell
617 requests the subprocess to open the remote stack viewer which returns a
Ezio Melottic569cfe2010-07-23 16:55:21 +0000618 static object looking at the last exception. It is queried through
Kurt B. Kaiser9f366092003-06-02 01:50:19 +0000619 the RPC mechanism.
620
621 """
622 self.tkconsole.text.after(300, self.remote_stack_viewer)
623 return
624
Chui Tey5d2af632002-05-26 13:36:41 +0000625 def remote_stack_viewer(self):
Florent Xiclunad630c042010-04-02 07:24:52 +0000626 from idlelib import RemoteObjectBrowser
Kurt B. Kaisera00050f2003-05-08 20:26:55 +0000627 oid = self.rpcclt.remotequeue("exec", "stackviewer", ("flist",), {})
Chui Tey5d2af632002-05-26 13:36:41 +0000628 if oid is None:
629 self.tkconsole.root.bell()
630 return
631 item = RemoteObjectBrowser.StubObjectTreeItem(self.rpcclt, oid)
Florent Xiclunad630c042010-04-02 07:24:52 +0000632 from idlelib.TreeWidget import ScrolledCanvas, TreeNode
Chui Tey5d2af632002-05-26 13:36:41 +0000633 top = Toplevel(self.tkconsole.root)
Terry Jan Reedy35aa5d02015-11-12 15:02:50 -0500634 theme = idleConf.CurrentTheme()
Kurt B. Kaiser73360a32004-03-08 18:15:31 +0000635 background = idleConf.GetHighlight(theme, 'normal')['background']
636 sc = ScrolledCanvas(top, bg=background, highlightthickness=0)
Chui Tey5d2af632002-05-26 13:36:41 +0000637 sc.frame.pack(expand=1, fill="both")
638 node = TreeNode(sc.canvas, None, item)
639 node.expand()
640 # XXX Should GC the remote tree when closing the window
641
David Scherer7aced172000-08-15 01:13:23 +0000642 gid = 0
643
644 def execsource(self, source):
Kurt B. Kaiser83118c62002-06-24 17:03:37 +0000645 "Like runsource() but assumes complete exec source"
David Scherer7aced172000-08-15 01:13:23 +0000646 filename = self.stuffsource(source)
647 self.execfile(filename, source)
648
649 def execfile(self, filename, source=None):
Kurt B. Kaiser83118c62002-06-24 17:03:37 +0000650 "Execute an existing file"
David Scherer7aced172000-08-15 01:13:23 +0000651 if source is None:
652 source = open(filename, "r").read()
653 try:
Terry Jan Reedy23120092015-05-18 15:37:37 -0400654 code = compile(source, filename, "exec", dont_inherit=True)
David Scherer7aced172000-08-15 01:13:23 +0000655 except (OverflowError, SyntaxError):
656 self.tkconsole.resetoutput()
Terry Jan Reedybee003c2014-09-19 22:37:24 -0400657 print('*** Error in script or command!\n'
658 'Traceback (most recent call last):',
659 file=self.tkconsole.stderr)
David Scherer7aced172000-08-15 01:13:23 +0000660 InteractiveInterpreter.showsyntaxerror(self, filename)
Kurt B. Kaiser6e44cc22002-11-30 06:18:00 +0000661 self.tkconsole.showprompt()
David Scherer7aced172000-08-15 01:13:23 +0000662 else:
663 self.runcode(code)
664
665 def runsource(self, source):
Kurt B. Kaiser83118c62002-06-24 17:03:37 +0000666 "Extend base class method: Stuff the source in the line cache first"
David Scherer7aced172000-08-15 01:13:23 +0000667 filename = self.stuffsource(source)
668 self.more = 0
Kurt B. Kaiser94bd7742001-07-14 00:13:28 +0000669 self.save_warnings_filters = warnings.filters[:]
670 warnings.filterwarnings(action="error", category=SyntaxWarning)
Serhiy Storchaka4b2c4682015-05-17 13:53:54 +0300671 if isinstance(source, unicode) and IOBinding.encoding != 'utf-8':
Kurt B. Kaiser837d15c2002-09-18 02:29:59 +0000672 try:
Serhiy Storchaka4b2c4682015-05-17 13:53:54 +0300673 source = '# -*- coding: %s -*-\n%s' % (
674 IOBinding.encoding,
675 source.encode(IOBinding.encoding))
Kurt B. Kaiser837d15c2002-09-18 02:29:59 +0000676 except UnicodeError:
677 self.tkconsole.resetoutput()
Kurt B. Kaisercd3d8be2006-08-10 17:11:09 +0000678 self.write("Unsupported characters in input\n")
Kurt B. Kaiser837d15c2002-09-18 02:29:59 +0000679 return
Kurt B. Kaiser94bd7742001-07-14 00:13:28 +0000680 try:
Kurt B. Kaiser935ea9a2005-05-10 03:44:24 +0000681 # InteractiveInterpreter.runsource() calls its runcode() method,
682 # which is overridden (see below)
Kurt B. Kaiser94bd7742001-07-14 00:13:28 +0000683 return InteractiveInterpreter.runsource(self, source, filename)
684 finally:
685 if self.save_warnings_filters is not None:
686 warnings.filters[:] = self.save_warnings_filters
687 self.save_warnings_filters = None
David Scherer7aced172000-08-15 01:13:23 +0000688
689 def stuffsource(self, source):
Kurt B. Kaiser83118c62002-06-24 17:03:37 +0000690 "Stuff source in the filename cache"
David Scherer7aced172000-08-15 01:13:23 +0000691 filename = "<pyshell#%d>" % self.gid
692 self.gid = self.gid + 1
Kurt B. Kaiser837d15c2002-09-18 02:29:59 +0000693 lines = source.split("\n")
David Scherer7aced172000-08-15 01:13:23 +0000694 linecache.cache[filename] = len(source)+1, 0, lines, filename
695 return filename
Kurt B. Kaiser6655e4b2002-12-31 16:03:23 +0000696
Kurt B. Kaiser11659ad2003-05-15 23:23:21 +0000697 def prepend_syspath(self, filename):
698 "Prepend sys.path with file's directory if not already included"
699 self.runcommand("""if 1:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000700 _filename = %r
Kurt B. Kaiser11659ad2003-05-15 23:23:21 +0000701 import sys as _sys
702 from os.path import dirname as _dirname
703 _dir = _dirname(_filename)
704 if not _dir in _sys.path:
705 _sys.path.insert(0, _dir)
706 del _filename, _sys, _dirname, _dir
Walter Dörwald70a6b492004-02-12 17:35:32 +0000707 \n""" % (filename,))
Kurt B. Kaiser11659ad2003-05-15 23:23:21 +0000708
David Scherer7aced172000-08-15 01:13:23 +0000709 def showsyntaxerror(self, filename=None):
Kurt B. Kaiser83118c62002-06-24 17:03:37 +0000710 """Extend base class method: Add Colorizing
711
712 Color the offending position instead of printing it and pointing at it
713 with a caret.
714
715 """
David Scherer7aced172000-08-15 01:13:23 +0000716 text = self.tkconsole.text
717 stuff = self.unpackerror()
Kurt B. Kaiser6e44cc22002-11-30 06:18:00 +0000718 if stuff:
719 msg, lineno, offset, line = stuff
720 if lineno == 1:
721 pos = "iomark + %d chars" % (offset-1)
722 else:
723 pos = "iomark linestart + %d lines + %d chars" % \
724 (lineno-1, offset-1)
725 text.tag_add("ERROR", pos)
726 text.see(pos)
727 char = text.get(pos)
728 if char and char in IDENTCHARS:
729 text.tag_add("ERROR", pos + " wordstart", pos)
730 self.tkconsole.resetoutput()
731 self.write("SyntaxError: %s\n" % str(msg))
732 else:
David Scherer7aced172000-08-15 01:13:23 +0000733 self.tkconsole.resetoutput()
734 InteractiveInterpreter.showsyntaxerror(self, filename)
Kurt B. Kaiser6e44cc22002-11-30 06:18:00 +0000735 self.tkconsole.showprompt()
David Scherer7aced172000-08-15 01:13:23 +0000736
737 def unpackerror(self):
738 type, value, tb = sys.exc_info()
739 ok = type is SyntaxError
740 if ok:
741 try:
742 msg, (dummy_filename, lineno, offset, line) = value
Kurt B. Kaiserbea57c62003-07-09 04:27:24 +0000743 if not offset:
744 offset = 0
David Scherer7aced172000-08-15 01:13:23 +0000745 except:
746 ok = 0
747 if ok:
748 return msg, lineno, offset, line
749 else:
750 return None
751
752 def showtraceback(self):
Kurt B. Kaiser83118c62002-06-24 17:03:37 +0000753 "Extend base class method to reset output properly"
David Scherer7aced172000-08-15 01:13:23 +0000754 self.tkconsole.resetoutput()
755 self.checklinecache()
756 InteractiveInterpreter.showtraceback(self)
Chui Tey5d2af632002-05-26 13:36:41 +0000757 if self.tkconsole.getvar("<<toggle-jit-stack-viewer>>"):
758 self.tkconsole.open_stack_viewer()
David Scherer7aced172000-08-15 01:13:23 +0000759
760 def checklinecache(self):
761 c = linecache.cache
762 for key in c.keys():
763 if key[:1] + key[-1:] != "<>":
764 del c[key]
765
Chui Tey5d2af632002-05-26 13:36:41 +0000766 def runcommand(self, code):
Kurt B. Kaiser83118c62002-06-24 17:03:37 +0000767 "Run the code without invoking the debugger"
Chui Tey5d2af632002-05-26 13:36:41 +0000768 # The code better not raise an exception!
769 if self.tkconsole.executing:
Neal Norwitzf4c4f112002-11-30 18:49:10 +0000770 self.display_executing_dialog()
Chui Tey5d2af632002-05-26 13:36:41 +0000771 return 0
772 if self.rpcclt:
Kurt B. Kaisera00050f2003-05-08 20:26:55 +0000773 self.rpcclt.remotequeue("exec", "runcode", (code,), {})
Chui Tey5d2af632002-05-26 13:36:41 +0000774 else:
775 exec code in self.locals
776 return 1
777
David Scherer7aced172000-08-15 01:13:23 +0000778 def runcode(self, code):
Kurt B. Kaiser83118c62002-06-24 17:03:37 +0000779 "Override base class method"
Chui Tey5d2af632002-05-26 13:36:41 +0000780 if self.tkconsole.executing:
Kurt B. Kaiser003091c2003-02-17 18:57:16 +0000781 self.interp.restart_subprocess()
Chui Tey5d2af632002-05-26 13:36:41 +0000782 self.checklinecache()
Kurt B. Kaiser94bd7742001-07-14 00:13:28 +0000783 if self.save_warnings_filters is not None:
784 warnings.filters[:] = self.save_warnings_filters
785 self.save_warnings_filters = None
David Scherer7aced172000-08-15 01:13:23 +0000786 debugger = self.debugger
787 try:
Kurt B. Kaiser7f38ec02003-05-15 03:19:42 +0000788 self.tkconsole.beginexecuting()
Kurt B. Kaiserdddeb0e2007-02-06 03:21:40 +0000789 if not debugger and self.rpcclt is not None:
790 self.active_seq = self.rpcclt.asyncqueue("exec", "runcode",
791 (code,), {})
792 elif debugger:
793 debugger.run(code, self.locals)
794 else:
795 exec code in self.locals
796 except SystemExit:
797 if not self.tkconsole.closing:
798 if tkMessageBox.askyesno(
799 "Exit?",
800 "Do you want to exit altogether?",
801 default="yes",
Terry Jan Reedy8bfacc72015-09-25 22:22:48 -0400802 parent=self.tkconsole.text):
Kurt B. Kaiserf137e1d2006-08-16 07:04:17 +0000803 raise
Kurt B. Kaiserdddeb0e2007-02-06 03:21:40 +0000804 else:
805 self.showtraceback()
806 else:
807 raise
808 except:
809 if use_subprocess:
Terry Jan Reedybee003c2014-09-19 22:37:24 -0400810 print("IDLE internal error in runcode()",
811 file=self.tkconsole.stderr)
David Scherer7aced172000-08-15 01:13:23 +0000812 self.showtraceback()
Kurt B. Kaiserdddeb0e2007-02-06 03:21:40 +0000813 self.tkconsole.endexecuting()
814 else:
815 if self.tkconsole.canceled:
816 self.tkconsole.canceled = False
Terry Jan Reedybee003c2014-09-19 22:37:24 -0400817 print("KeyboardInterrupt", file=self.tkconsole.stderr)
Kurt B. Kaiserdddeb0e2007-02-06 03:21:40 +0000818 else:
819 self.showtraceback()
Kurt B. Kaiser7f38ec02003-05-15 03:19:42 +0000820 finally:
821 if not use_subprocess:
Kurt B. Kaiserd112bc72006-08-16 05:01:42 +0000822 try:
823 self.tkconsole.endexecuting()
824 except AttributeError: # shell may have closed
825 pass
David Scherer7aced172000-08-15 01:13:23 +0000826
827 def write(self, s):
Kurt B. Kaiser83118c62002-06-24 17:03:37 +0000828 "Override base class method"
Kurt B. Kaiser7f38ec02003-05-15 03:19:42 +0000829 self.tkconsole.stderr.write(s)
David Scherer7aced172000-08-15 01:13:23 +0000830
Kurt B. Kaiseraf3eb872004-01-21 18:54:30 +0000831 def display_port_binding_error(self):
832 tkMessageBox.showerror(
833 "Port Binding Error",
Kurt B. Kaiser013d6cc2009-04-04 07:03:48 +0000834 "IDLE can't bind to a TCP/IP port, which is necessary to "
835 "communicate with its Python execution server. This might be "
836 "because no networking is installed on this computer. "
837 "Run IDLE with the -n command line switch to start without a "
838 "subprocess and refer to Help/IDLE Help 'Running without a "
839 "subprocess' for further details.",
Terry Jan Reedy8bfacc72015-09-25 22:22:48 -0400840 parent=self.tkconsole.text)
Kurt B. Kaiseraf3eb872004-01-21 18:54:30 +0000841
842 def display_no_subprocess_error(self):
843 tkMessageBox.showerror(
844 "Subprocess Startup Error",
845 "IDLE's subprocess didn't make connection. Either IDLE can't "
846 "start a subprocess or personal firewall software is blocking "
847 "the connection.",
Terry Jan Reedy8bfacc72015-09-25 22:22:48 -0400848 parent=self.tkconsole.text)
Kurt B. Kaiseraf3eb872004-01-21 18:54:30 +0000849
850 def display_executing_dialog(self):
851 tkMessageBox.showerror(
852 "Already executing",
853 "The Python Shell window is already executing a command; "
854 "please wait until it is finished.",
Terry Jan Reedy8bfacc72015-09-25 22:22:48 -0400855 parent=self.tkconsole.text)
Kurt B. Kaiseraf3eb872004-01-21 18:54:30 +0000856
857
David Scherer7aced172000-08-15 01:13:23 +0000858class PyShell(OutputWindow):
859
Terry Jan Reedyd676a3a2013-03-30 18:50:43 -0400860 shell_title = "Python " + python_version() + " Shell"
David Scherer7aced172000-08-15 01:13:23 +0000861
862 # Override classes
863 ColorDelegator = ModifiedColorDelegator
864 UndoDelegator = ModifiedUndoDelegator
865
Kurt B. Kaiserf06eed02002-12-11 04:42:04 +0000866 # Override menus
Kurt B. Kaiserdc1e7092002-07-11 04:33:41 +0000867 menu_specs = [
868 ("file", "_File"),
869 ("edit", "_Edit"),
Kurt B. Kaiser4cc5ef52003-01-22 00:23:23 +0000870 ("debug", "_Debug"),
Kurt B. Kaiser1061e722003-01-04 01:43:53 +0000871 ("options", "_Options"),
Ned Deilyb5daa3d2015-01-17 21:03:41 -0800872 ("windows", "_Window"),
Kurt B. Kaiserdc1e7092002-07-11 04:33:41 +0000873 ("help", "_Help"),
874 ]
David Scherer7aced172000-08-15 01:13:23 +0000875
Ronald Oussoren19302d92006-06-11 14:33:36 +0000876
David Scherer7aced172000-08-15 01:13:23 +0000877 # New classes
Florent Xiclunad630c042010-04-02 07:24:52 +0000878 from idlelib.IdleHistory import History
David Scherer7aced172000-08-15 01:13:23 +0000879
880 def __init__(self, flist=None):
Kurt B. Kaiser8f570a72003-05-15 18:52:51 +0000881 if use_subprocess:
Kurt B. Kaiser67fd0ea2003-05-24 20:59:15 +0000882 ms = self.menu_specs
883 if ms[2][0] != "shell":
Kurt B. Kaiser7ae35482006-08-16 21:45:59 +0000884 ms.insert(2, ("shell", "She_ll"))
David Scherer7aced172000-08-15 01:13:23 +0000885 self.interp = ModifiedInterpreter(self)
886 if flist is None:
887 root = Tk()
888 fixwordbreaks(root)
889 root.withdraw()
890 flist = PyShellFileList(root)
Kurt B. Kaiser5afa1df2002-10-10 08:25:24 +0000891 #
David Scherer7aced172000-08-15 01:13:23 +0000892 OutputWindow.__init__(self, flist, None, None)
Kurt B. Kaiser5afa1df2002-10-10 08:25:24 +0000893 #
Kurt B. Kaiser6af44982005-01-19 00:22:59 +0000894## self.config(usetabs=1, indentwidth=8, context_use_ps1=1)
895 self.usetabs = True
896 # indentwidth must be 8 when using tabs. See note in EditorWindow:
897 self.indentwidth = 8
898 self.context_use_ps1 = True
Kurt B. Kaiser5afa1df2002-10-10 08:25:24 +0000899 #
David Scherer7aced172000-08-15 01:13:23 +0000900 text = self.text
901 text.configure(wrap="char")
902 text.bind("<<newline-and-indent>>", self.enter_callback)
903 text.bind("<<plain-newline-and-indent>>", self.linefeed_callback)
904 text.bind("<<interrupt-execution>>", self.cancel_callback)
David Scherer7aced172000-08-15 01:13:23 +0000905 text.bind("<<end-of-file>>", self.eof_callback)
906 text.bind("<<open-stack-viewer>>", self.open_stack_viewer)
Kurt B. Kaiser57bfe5d2003-05-10 00:09:52 +0000907 text.bind("<<toggle-debugger>>", self.toggle_debugger)
David Scherer7aced172000-08-15 01:13:23 +0000908 text.bind("<<toggle-jit-stack-viewer>>", self.toggle_jit_stack_viewer)
Kurt B. Kaiser8f570a72003-05-15 18:52:51 +0000909 if use_subprocess:
910 text.bind("<<view-restart>>", self.view_restart_mark)
911 text.bind("<<restart-shell>>", self.restart_shell)
Kurt B. Kaiser5afa1df2002-10-10 08:25:24 +0000912 #
David Scherer7aced172000-08-15 01:13:23 +0000913 self.save_stdout = sys.stdout
914 self.save_stderr = sys.stderr
915 self.save_stdin = sys.stdin
Florent Xiclunad630c042010-04-02 07:24:52 +0000916 from idlelib import IOBinding
Serhiy Storchaka9abc8302013-01-25 15:30:35 +0200917 self.stdin = PseudoInputFile(self, "stdin", IOBinding.encoding)
918 self.stdout = PseudoOutputFile(self, "stdout", IOBinding.encoding)
919 self.stderr = PseudoOutputFile(self, "stderr", IOBinding.encoding)
920 self.console = PseudoOutputFile(self, "console", IOBinding.encoding)
Chui Tey5d2af632002-05-26 13:36:41 +0000921 if not use_subprocess:
922 sys.stdout = self.stdout
923 sys.stderr = self.stderr
Martin v. Löwise2b56242012-07-25 10:56:22 +0200924 sys.stdin = self.stdin
Kurt B. Kaiser5afa1df2002-10-10 08:25:24 +0000925 #
David Scherer7aced172000-08-15 01:13:23 +0000926 self.history = self.History(self.text)
Kurt B. Kaiser5afa1df2002-10-10 08:25:24 +0000927 #
Kurt B. Kaiser88957d82003-05-19 23:11:51 +0000928 self.pollinterval = 50 # millisec
Chui Tey5d2af632002-05-26 13:36:41 +0000929
Kurt B. Kaiser4d5bc602004-06-06 01:29:22 +0000930 def get_standard_extension_names(self):
931 return idleConf.GetExtensions(shell_only=True)
932
Kurt B. Kaiser003091c2003-02-17 18:57:16 +0000933 reading = False
934 executing = False
935 canceled = False
936 endoffile = False
937 closing = False
Roger Serwyad8cad32013-04-03 00:42:24 -0500938 _stop_readline_flag = False
David Scherer7aced172000-08-15 01:13:23 +0000939
Kurt B. Kaiser49a5fe12004-07-04 01:25:56 +0000940 def set_warning_stream(self, stream):
Skip Montanarod9161422004-07-06 21:53:27 +0000941 global warning_stream
942 warning_stream = stream
Kurt B. Kaiser49a5fe12004-07-04 01:25:56 +0000943
944 def get_warning_stream(self):
945 return warning_stream
946
David Scherer7aced172000-08-15 01:13:23 +0000947 def toggle_debugger(self, event=None):
948 if self.executing:
949 tkMessageBox.showerror("Don't debug now",
950 "You can only toggle the debugger when idle",
Terry Jan Reedy8bfacc72015-09-25 22:22:48 -0400951 parent=self.text)
David Scherer7aced172000-08-15 01:13:23 +0000952 self.set_debugger_indicator()
953 return "break"
954 else:
955 db = self.interp.getdebugger()
956 if db:
957 self.close_debugger()
958 else:
959 self.open_debugger()
960
961 def set_debugger_indicator(self):
962 db = self.interp.getdebugger()
963 self.setvar("<<toggle-debugger>>", not not db)
964
Kurt B. Kaiser1061e722003-01-04 01:43:53 +0000965 def toggle_jit_stack_viewer(self, event=None):
David Scherer7aced172000-08-15 01:13:23 +0000966 pass # All we need is the variable
967
968 def close_debugger(self):
969 db = self.interp.getdebugger()
970 if db:
971 self.interp.setdebugger(None)
972 db.close()
Kurt B. Kaiserffd3a422002-06-26 02:32:09 +0000973 if self.interp.rpcclt:
974 RemoteDebugger.close_remote_debugger(self.interp.rpcclt)
David Scherer7aced172000-08-15 01:13:23 +0000975 self.resetoutput()
976 self.console.write("[DEBUG OFF]\n")
977 sys.ps1 = ">>> "
978 self.showprompt()
979 self.set_debugger_indicator()
980
981 def open_debugger(self):
Chui Tey5d2af632002-05-26 13:36:41 +0000982 if self.interp.rpcclt:
Kurt B. Kaiser7f38ec02003-05-15 03:19:42 +0000983 dbg_gui = RemoteDebugger.start_remote_debugger(self.interp.rpcclt,
984 self)
985 else:
986 dbg_gui = Debugger.Debugger(self)
987 self.interp.setdebugger(dbg_gui)
988 dbg_gui.load_breakpoints()
Chui Tey5d2af632002-05-26 13:36:41 +0000989 sys.ps1 = "[DEBUG ON]\n>>> "
990 self.showprompt()
991 self.set_debugger_indicator()
992
David Scherer7aced172000-08-15 01:13:23 +0000993 def beginexecuting(self):
Kurt B. Kaiserffd3a422002-06-26 02:32:09 +0000994 "Helper for ModifiedInterpreter"
David Scherer7aced172000-08-15 01:13:23 +0000995 self.resetoutput()
996 self.executing = 1
David Scherer7aced172000-08-15 01:13:23 +0000997
998 def endexecuting(self):
Kurt B. Kaiser83118c62002-06-24 17:03:37 +0000999 "Helper for ModifiedInterpreter"
David Scherer7aced172000-08-15 01:13:23 +00001000 self.executing = 0
1001 self.canceled = 0
Chui Tey5d2af632002-05-26 13:36:41 +00001002 self.showprompt()
David Scherer7aced172000-08-15 01:13:23 +00001003
1004 def close(self):
Kurt B. Kaiser83118c62002-06-24 17:03:37 +00001005 "Extend EditorWindow.close()"
David Scherer7aced172000-08-15 01:13:23 +00001006 if self.executing:
Kurt B. Kaiser003091c2003-02-17 18:57:16 +00001007 response = tkMessageBox.askokcancel(
David Scherer7aced172000-08-15 01:13:23 +00001008 "Kill?",
Kurt B. Kaiser003091c2003-02-17 18:57:16 +00001009 "The program is still running!\n Do you want to kill it?",
David Scherer7aced172000-08-15 01:13:23 +00001010 default="ok",
Kurt B. Kaiser7f38ec02003-05-15 03:19:42 +00001011 parent=self.text)
Benjamin Peterson5b63acd2008-03-29 15:24:25 +00001012 if response is False:
David Scherer7aced172000-08-15 01:13:23 +00001013 return "cancel"
Roger Serwyad8cad32013-04-03 00:42:24 -05001014 self.stop_readline()
Kurt B. Kaiser5c3df352004-12-23 04:20:59 +00001015 self.canceled = True
Kurt B. Kaiser67fd0ea2003-05-24 20:59:15 +00001016 self.closing = True
Kurt B. Kaiser88957d82003-05-19 23:11:51 +00001017 return EditorWindow.close(self)
David Scherer7aced172000-08-15 01:13:23 +00001018
1019 def _close(self):
Kurt B. Kaiser83118c62002-06-24 17:03:37 +00001020 "Extend EditorWindow._close(), shut down debugger and execution server"
David Scherer7aced172000-08-15 01:13:23 +00001021 self.close_debugger()
Kurt B. Kaiser7f38ec02003-05-15 03:19:42 +00001022 if use_subprocess:
1023 self.interp.kill_subprocess()
David Scherer7aced172000-08-15 01:13:23 +00001024 # Restore std streams
1025 sys.stdout = self.save_stdout
1026 sys.stderr = self.save_stderr
1027 sys.stdin = self.save_stdin
1028 # Break cycles
1029 self.interp = None
1030 self.console = None
David Scherer7aced172000-08-15 01:13:23 +00001031 self.flist.pyshell = None
1032 self.history = None
Kurt B. Kaiser83118c62002-06-24 17:03:37 +00001033 EditorWindow._close(self)
David Scherer7aced172000-08-15 01:13:23 +00001034
1035 def ispythonsource(self, filename):
Kurt B. Kaiser83118c62002-06-24 17:03:37 +00001036 "Override EditorWindow method: never remove the colorizer"
Kurt B. Kaiser837d15c2002-09-18 02:29:59 +00001037 return True
David Scherer7aced172000-08-15 01:13:23 +00001038
1039 def short_title(self):
1040 return self.shell_title
1041
Kurt B. Kaiser94bd7742001-07-14 00:13:28 +00001042 COPYRIGHT = \
Kurt B. Kaiser8f570a72003-05-15 18:52:51 +00001043 'Type "copyright", "credits" or "license()" for more information.'
Kurt B. Kaiser94bd7742001-07-14 00:13:28 +00001044
David Scherer7aced172000-08-15 01:13:23 +00001045 def begin(self):
1046 self.resetoutput()
Kurt B. Kaiser7f38ec02003-05-15 03:19:42 +00001047 if use_subprocess:
1048 nosub = ''
Kurt B. Kaiseraf3eb872004-01-21 18:54:30 +00001049 client = self.interp.start_subprocess()
1050 if not client:
1051 self.close()
Kurt B. Kaiser76637292004-01-21 22:10:01 +00001052 return False
Kurt B. Kaiser7f38ec02003-05-15 03:19:42 +00001053 else:
1054 nosub = "==== No Subprocess ===="
Raymond Hettingerbf3f69e2009-01-26 23:29:09 +00001055 self.write("Python %s on %s\n%s\n%s" %
1056 (sys.version, sys.platform, self.COPYRIGHT, nosub))
Terry Jan Reedybaf9ef92015-09-07 01:58:05 -04001057 self.text.focus_force()
David Scherer7aced172000-08-15 01:13:23 +00001058 self.showprompt()
Georg Brandl6634bf22008-05-20 07:13:37 +00001059 import Tkinter
1060 Tkinter._default_root = None # 03Jan04 KBK What's this?
Kurt B. Kaiser76637292004-01-21 22:10:01 +00001061 return True
David Scherer7aced172000-08-15 01:13:23 +00001062
Roger Serwyad8cad32013-04-03 00:42:24 -05001063 def stop_readline(self):
1064 if not self.reading: # no nested mainloop to exit.
1065 return
1066 self._stop_readline_flag = True
1067 self.top.quit()
1068
David Scherer7aced172000-08-15 01:13:23 +00001069 def readline(self):
1070 save = self.reading
1071 try:
1072 self.reading = 1
Kurt B. Kaiser5c3df352004-12-23 04:20:59 +00001073 self.top.mainloop() # nested mainloop()
David Scherer7aced172000-08-15 01:13:23 +00001074 finally:
1075 self.reading = save
Roger Serwyad8cad32013-04-03 00:42:24 -05001076 if self._stop_readline_flag:
1077 self._stop_readline_flag = False
1078 return ""
David Scherer7aced172000-08-15 01:13:23 +00001079 line = self.text.get("iomark", "end-1c")
Kurt B. Kaiser5c3df352004-12-23 04:20:59 +00001080 if len(line) == 0: # may be EOF if we quit our mainloop with Ctrl-C
1081 line = "\n"
Martin v. Löwisbcc651a2003-06-22 07:52:56 +00001082 if isinstance(line, unicode):
Florent Xiclunad630c042010-04-02 07:24:52 +00001083 from idlelib import IOBinding
Martin v. Löwisbcc651a2003-06-22 07:52:56 +00001084 try:
1085 line = line.encode(IOBinding.encoding)
1086 except UnicodeError:
1087 pass
David Scherer7aced172000-08-15 01:13:23 +00001088 self.resetoutput()
1089 if self.canceled:
1090 self.canceled = 0
Kurt B. Kaiser5c3df352004-12-23 04:20:59 +00001091 if not use_subprocess:
1092 raise KeyboardInterrupt
David Scherer7aced172000-08-15 01:13:23 +00001093 if self.endoffile:
1094 self.endoffile = 0
Kurt B. Kaiser5c3df352004-12-23 04:20:59 +00001095 line = ""
David Scherer7aced172000-08-15 01:13:23 +00001096 return line
1097
1098 def isatty(self):
Kurt B. Kaiser837d15c2002-09-18 02:29:59 +00001099 return True
David Scherer7aced172000-08-15 01:13:23 +00001100
Kurt B. Kaiser003091c2003-02-17 18:57:16 +00001101 def cancel_callback(self, event=None):
David Scherer7aced172000-08-15 01:13:23 +00001102 try:
1103 if self.text.compare("sel.first", "!=", "sel.last"):
1104 return # Active selection -- always use default binding
1105 except:
1106 pass
1107 if not (self.executing or self.reading):
1108 self.resetoutput()
Kurt B. Kaiser7f38ec02003-05-15 03:19:42 +00001109 self.interp.write("KeyboardInterrupt\n")
David Scherer7aced172000-08-15 01:13:23 +00001110 self.showprompt()
1111 return "break"
1112 self.endoffile = 0
Kurt B. Kaiser003091c2003-02-17 18:57:16 +00001113 self.canceled = 1
Kurt B. Kaiser5c3df352004-12-23 04:20:59 +00001114 if (self.executing and self.interp.rpcclt):
Kurt B. Kaiser67fd0ea2003-05-24 20:59:15 +00001115 if self.interp.getdebugger():
1116 self.interp.restart_subprocess()
1117 else:
1118 self.interp.interrupt_subprocess()
Kurt B. Kaiser5c3df352004-12-23 04:20:59 +00001119 if self.reading:
1120 self.top.quit() # exit the nested mainloop() in readline()
David Scherer7aced172000-08-15 01:13:23 +00001121 return "break"
1122
1123 def eof_callback(self, event):
1124 if self.executing and not self.reading:
1125 return # Let the default binding (delete next char) take over
1126 if not (self.text.compare("iomark", "==", "insert") and
1127 self.text.compare("insert", "==", "end-1c")):
1128 return # Let the default binding (delete next char) take over
1129 if not self.executing:
David Scherer7aced172000-08-15 01:13:23 +00001130 self.resetoutput()
1131 self.close()
1132 else:
1133 self.canceled = 0
1134 self.endoffile = 1
1135 self.top.quit()
1136 return "break"
1137
David Scherer7aced172000-08-15 01:13:23 +00001138 def linefeed_callback(self, event):
1139 # Insert a linefeed without entering anything (still autoindented)
1140 if self.reading:
1141 self.text.insert("insert", "\n")
1142 self.text.see("insert")
1143 else:
Kurt B. Kaiser822a77f2002-12-16 02:07:11 +00001144 self.newline_and_indent_event(event)
David Scherer7aced172000-08-15 01:13:23 +00001145 return "break"
1146
1147 def enter_callback(self, event):
1148 if self.executing and not self.reading:
1149 return # Let the default binding (insert '\n') take over
1150 # If some text is selected, recall the selection
1151 # (but only if this before the I/O mark)
1152 try:
1153 sel = self.text.get("sel.first", "sel.last")
1154 if sel:
1155 if self.text.compare("sel.last", "<=", "iomark"):
Kurt B. Kaisera7daba62005-06-19 18:56:15 +00001156 self.recall(sel, event)
David Scherer7aced172000-08-15 01:13:23 +00001157 return "break"
1158 except:
1159 pass
1160 # If we're strictly before the line containing iomark, recall
1161 # the current line, less a leading prompt, less leading or
1162 # trailing whitespace
1163 if self.text.compare("insert", "<", "iomark linestart"):
1164 # Check if there's a relevant stdin range -- if so, use it
1165 prev = self.text.tag_prevrange("stdin", "insert")
1166 if prev and self.text.compare("insert", "<", prev[1]):
Kurt B. Kaisera7daba62005-06-19 18:56:15 +00001167 self.recall(self.text.get(prev[0], prev[1]), event)
David Scherer7aced172000-08-15 01:13:23 +00001168 return "break"
1169 next = self.text.tag_nextrange("stdin", "insert")
1170 if next and self.text.compare("insert lineend", ">=", next[0]):
Kurt B. Kaisera7daba62005-06-19 18:56:15 +00001171 self.recall(self.text.get(next[0], next[1]), event)
David Scherer7aced172000-08-15 01:13:23 +00001172 return "break"
Kurt B. Kaiser4ada7ad2002-12-29 22:03:38 +00001173 # No stdin mark -- just get the current line, less any prompt
Kurt B. Kaiserb1754452005-11-18 22:05:48 +00001174 indices = self.text.tag_nextrange("console", "insert linestart")
1175 if indices and \
1176 self.text.compare(indices[0], "<=", "insert linestart"):
1177 self.recall(self.text.get(indices[1], "insert lineend"), event)
1178 else:
1179 self.recall(self.text.get("insert linestart", "insert lineend"), event)
David Scherer7aced172000-08-15 01:13:23 +00001180 return "break"
Kurt B. Kaiser822a77f2002-12-16 02:07:11 +00001181 # If we're between the beginning of the line and the iomark, i.e.
Kurt B. Kaiser4ada7ad2002-12-29 22:03:38 +00001182 # in the prompt area, move to the end of the prompt
Kurt B. Kaiser822a77f2002-12-16 02:07:11 +00001183 if self.text.compare("insert", "<", "iomark"):
Kurt B. Kaiser4ada7ad2002-12-29 22:03:38 +00001184 self.text.mark_set("insert", "iomark")
David Scherer7aced172000-08-15 01:13:23 +00001185 # If we're in the current input and there's only whitespace
1186 # beyond the cursor, erase that whitespace first
1187 s = self.text.get("insert", "end-1c")
Kurt B. Kaiser837d15c2002-09-18 02:29:59 +00001188 if s and not s.strip():
David Scherer7aced172000-08-15 01:13:23 +00001189 self.text.delete("insert", "end-1c")
1190 # If we're in the current input before its last line,
1191 # insert a newline right at the insert point
1192 if self.text.compare("insert", "<", "end-1c linestart"):
Kurt B. Kaiser822a77f2002-12-16 02:07:11 +00001193 self.newline_and_indent_event(event)
David Scherer7aced172000-08-15 01:13:23 +00001194 return "break"
1195 # We're in the last line; append a newline and submit it
1196 self.text.mark_set("insert", "end-1c")
1197 if self.reading:
1198 self.text.insert("insert", "\n")
1199 self.text.see("insert")
1200 else:
Kurt B. Kaiser822a77f2002-12-16 02:07:11 +00001201 self.newline_and_indent_event(event)
David Scherer7aced172000-08-15 01:13:23 +00001202 self.text.tag_add("stdin", "iomark", "end-1c")
1203 self.text.update_idletasks()
1204 if self.reading:
1205 self.top.quit() # Break out of recursive mainloop() in raw_input()
1206 else:
1207 self.runit()
1208 return "break"
1209
Kurt B. Kaisera7daba62005-06-19 18:56:15 +00001210 def recall(self, s, event):
Kurt B. Kaisercd3d8be2006-08-10 17:11:09 +00001211 # remove leading and trailing empty or whitespace lines
1212 s = re.sub(r'^\s*\n', '' , s)
1213 s = re.sub(r'\n\s*$', '', s)
1214 lines = s.split('\n')
Kurt B. Kaisera7daba62005-06-19 18:56:15 +00001215 self.text.undo_block_start()
1216 try:
1217 self.text.tag_remove("sel", "1.0", "end")
1218 self.text.mark_set("insert", "end-1c")
Kurt B. Kaisercd3d8be2006-08-10 17:11:09 +00001219 prefix = self.text.get("insert linestart", "insert")
1220 if prefix.rstrip().endswith(':'):
Kurt B. Kaiser8fa7eb52005-06-21 02:42:17 +00001221 self.newline_and_indent_event(event)
Kurt B. Kaisercd3d8be2006-08-10 17:11:09 +00001222 prefix = self.text.get("insert linestart", "insert")
1223 self.text.insert("insert", lines[0].strip())
Kurt B. Kaiser8fa7eb52005-06-21 02:42:17 +00001224 if len(lines) > 1:
Kurt B. Kaisercd3d8be2006-08-10 17:11:09 +00001225 orig_base_indent = re.search(r'^([ \t]*)', lines[0]).group(0)
1226 new_base_indent = re.search(r'^([ \t]*)', prefix).group(0)
Kurt B. Kaiser8fa7eb52005-06-21 02:42:17 +00001227 for line in lines[1:]:
Kurt B. Kaisercd3d8be2006-08-10 17:11:09 +00001228 if line.startswith(orig_base_indent):
1229 # replace orig base indentation with new indentation
1230 line = new_base_indent + line[len(orig_base_indent):]
1231 self.text.insert('insert', '\n'+line.rstrip())
Kurt B. Kaisera7daba62005-06-19 18:56:15 +00001232 finally:
1233 self.text.see("insert")
1234 self.text.undo_block_stop()
David Scherer7aced172000-08-15 01:13:23 +00001235
1236 def runit(self):
1237 line = self.text.get("iomark", "end-1c")
1238 # Strip off last newline and surrounding whitespace.
1239 # (To allow you to hit return twice to end a statement.)
1240 i = len(line)
1241 while i > 0 and line[i-1] in " \t":
1242 i = i-1
1243 if i > 0 and line[i-1] == "\n":
1244 i = i-1
1245 while i > 0 and line[i-1] in " \t":
1246 i = i-1
1247 line = line[:i]
Terry Jan Reedy28489252015-05-15 23:03:11 -04001248 self.interp.runsource(line)
David Scherer7aced172000-08-15 01:13:23 +00001249
David Scherer7aced172000-08-15 01:13:23 +00001250 def open_stack_viewer(self, event=None):
Chui Tey5d2af632002-05-26 13:36:41 +00001251 if self.interp.rpcclt:
1252 return self.interp.remote_stack_viewer()
David Scherer7aced172000-08-15 01:13:23 +00001253 try:
1254 sys.last_traceback
1255 except:
1256 tkMessageBox.showerror("No stack trace",
1257 "There is no stack trace yet.\n"
1258 "(sys.last_traceback is not defined)",
Terry Jan Reedy8bfacc72015-09-25 22:22:48 -04001259 parent=self.text)
David Scherer7aced172000-08-15 01:13:23 +00001260 return
Florent Xiclunad630c042010-04-02 07:24:52 +00001261 from idlelib.StackViewer import StackBrowser
Terry Jan Reedy28489252015-05-15 23:03:11 -04001262 StackBrowser(self.root, self.flist)
David Scherer7aced172000-08-15 01:13:23 +00001263
Kurt B. Kaiser1061e722003-01-04 01:43:53 +00001264 def view_restart_mark(self, event=None):
1265 self.text.see("iomark")
1266 self.text.see("restart")
1267
1268 def restart_shell(self, event=None):
Terry Jan Reedyb98000a2012-01-31 02:09:25 -05001269 "Callback for Run/Restart Shell Cntl-F6"
1270 self.interp.restart_subprocess(with_cwd=True)
Kurt B. Kaiser1061e722003-01-04 01:43:53 +00001271
David Scherer7aced172000-08-15 01:13:23 +00001272 def showprompt(self):
1273 self.resetoutput()
1274 try:
1275 s = str(sys.ps1)
1276 except:
1277 s = ""
1278 self.console.write(s)
1279 self.text.mark_set("insert", "end-1c")
Chui Tey5d2af632002-05-26 13:36:41 +00001280 self.set_line_and_column()
Kurt B. Kaiserdc1e7092002-07-11 04:33:41 +00001281 self.io.reset_undo()
David Scherer7aced172000-08-15 01:13:23 +00001282
1283 def resetoutput(self):
1284 source = self.text.get("iomark", "end-1c")
1285 if self.history:
Terry Jan Reedyb638a382013-08-13 19:51:04 -04001286 self.history.store(source)
David Scherer7aced172000-08-15 01:13:23 +00001287 if self.text.get("end-2c") != "\n":
1288 self.text.insert("end-1c", "\n")
1289 self.text.mark_set("iomark", "end-1c")
Chui Tey5d2af632002-05-26 13:36:41 +00001290 self.set_line_and_column()
David Scherer7aced172000-08-15 01:13:23 +00001291 sys.stdout.softspace = 0
1292
1293 def write(self, s, tags=()):
Kurt B. Kaiser003091c2003-02-17 18:57:16 +00001294 try:
1295 self.text.mark_gravity("iomark", "right")
1296 OutputWindow.write(self, s, tags, "iomark")
1297 self.text.mark_gravity("iomark", "left")
1298 except:
1299 pass
David Scherer7aced172000-08-15 01:13:23 +00001300 if self.canceled:
1301 self.canceled = 0
Kurt B. Kaiser7f38ec02003-05-15 03:19:42 +00001302 if not use_subprocess:
1303 raise KeyboardInterrupt
David Scherer7aced172000-08-15 01:13:23 +00001304
Andrew Svetlov5018db72012-11-01 22:39:14 +02001305 def rmenu_check_cut(self):
1306 try:
1307 if self.text.compare('sel.first', '<', 'iomark'):
1308 return 'disabled'
1309 except TclError: # no selection, so the index 'sel.first' doesn't exist
1310 return 'disabled'
1311 return super(PyShell, self).rmenu_check_cut()
1312
1313 def rmenu_check_paste(self):
1314 if self.text.compare('insert', '<', 'iomark'):
1315 return 'disabled'
1316 return super(PyShell, self).rmenu_check_paste()
1317
Serhiy Storchaka9abc8302013-01-25 15:30:35 +02001318class PseudoFile(io.TextIOBase):
David Scherer7aced172000-08-15 01:13:23 +00001319
Martin v. Löwisbcc651a2003-06-22 07:52:56 +00001320 def __init__(self, shell, tags, encoding=None):
David Scherer7aced172000-08-15 01:13:23 +00001321 self.shell = shell
1322 self.tags = tags
Chui Tey5d2af632002-05-26 13:36:41 +00001323 self.softspace = 0
Serhiy Storchaka9abc8302013-01-25 15:30:35 +02001324 self._encoding = encoding
David Scherer7aced172000-08-15 01:13:23 +00001325
Serhiy Storchaka9abc8302013-01-25 15:30:35 +02001326 @property
1327 def encoding(self):
1328 return self._encoding
David Scherer7aced172000-08-15 01:13:23 +00001329
Serhiy Storchaka9abc8302013-01-25 15:30:35 +02001330 @property
1331 def name(self):
1332 return '<%s>' % self.tags
David Scherer7aced172000-08-15 01:13:23 +00001333
1334 def isatty(self):
Kurt B. Kaiser837d15c2002-09-18 02:29:59 +00001335 return True
David Scherer7aced172000-08-15 01:13:23 +00001336
Serhiy Storchaka9abc8302013-01-25 15:30:35 +02001337
1338class PseudoOutputFile(PseudoFile):
1339
1340 def writable(self):
1341 return True
Martin v. Löwise2b56242012-07-25 10:56:22 +02001342
1343 def write(self, s):
Serhiy Storchaka9abc8302013-01-25 15:30:35 +02001344 if self.closed:
1345 raise ValueError("write to closed file")
Serhiy Storchaka7057f3f2013-12-10 10:04:41 +02001346 if type(s) not in (unicode, str, bytearray):
1347 # See issue #19481
1348 if isinstance(s, unicode):
Serhiy Storchakaac5164d2015-03-24 19:42:15 +02001349 s = unicode.__getitem__(s, slice(None))
Serhiy Storchaka7057f3f2013-12-10 10:04:41 +02001350 elif isinstance(s, str):
1351 s = str.__str__(s)
1352 elif isinstance(s, bytearray):
1353 s = bytearray.__str__(s)
1354 else:
1355 raise TypeError('must be string, not ' + type(s).__name__)
Serhiy Storchaka9abc8302013-01-25 15:30:35 +02001356 return self.shell.write(s, self.tags)
1357
1358
1359class PseudoInputFile(PseudoFile):
1360
1361 def __init__(self, shell, tags, encoding=None):
1362 PseudoFile.__init__(self, shell, tags, encoding)
1363 self._line_buffer = ''
1364
1365 def readable(self):
1366 return True
1367
1368 def read(self, size=-1):
1369 if self.closed:
1370 raise ValueError("read from closed file")
1371 if size is None:
1372 size = -1
1373 elif not isinstance(size, int):
1374 raise TypeError('must be int, not ' + type(size).__name__)
1375 result = self._line_buffer
1376 self._line_buffer = ''
1377 if size < 0:
1378 while True:
1379 line = self.shell.readline()
1380 if not line: break
1381 result += line
1382 else:
1383 while len(result) < size:
1384 line = self.shell.readline()
1385 if not line: break
1386 result += line
1387 self._line_buffer = result[size:]
1388 result = result[:size]
1389 return result
1390
1391 def readline(self, size=-1):
1392 if self.closed:
1393 raise ValueError("read from closed file")
1394 if size is None:
1395 size = -1
1396 elif not isinstance(size, int):
1397 raise TypeError('must be int, not ' + type(size).__name__)
1398 line = self._line_buffer or self.shell.readline()
1399 if size < 0:
1400 size = len(line)
Serhiy Storchaka0b6b3352013-12-25 14:24:17 +02001401 eol = line.find('\n', 0, size)
1402 if eol >= 0:
1403 size = eol + 1
Serhiy Storchaka9abc8302013-01-25 15:30:35 +02001404 self._line_buffer = line[size:]
1405 return line[:size]
Martin v. Löwise2b56242012-07-25 10:56:22 +02001406
Roger Serwy53dc4f02013-04-11 19:13:21 -05001407 def close(self):
1408 self.shell.close()
1409
Kurt B. Kaiser969de452002-06-12 03:28:57 +00001410
David Scherer7aced172000-08-15 01:13:23 +00001411usage_msg = """\
David Scherer7aced172000-08-15 01:13:23 +00001412
Kurt B. Kaiser11659ad2003-05-15 23:23:21 +00001413USAGE: idle [-deins] [-t title] [file]*
1414 idle [-dns] [-t title] (-c cmd | -r file) [arg]*
1415 idle [-dns] [-t title] - [arg]*
Kurt B. Kaiser6655e4b2002-12-31 16:03:23 +00001416
Kurt B. Kaiserf06eed02002-12-11 04:42:04 +00001417 -h print this help message and exit
Kurt B. Kaiser8f570a72003-05-15 18:52:51 +00001418 -n run IDLE without a subprocess (see Help/IDLE Help for details)
David Scherer7aced172000-08-15 01:13:23 +00001419
Kurt B. Kaiserf06eed02002-12-11 04:42:04 +00001420The following options will override the IDLE 'settings' configuration:
Kurt B. Kaiser96d88422001-07-17 04:59:01 +00001421
Kurt B. Kaiserf06eed02002-12-11 04:42:04 +00001422 -e open an edit window
1423 -i open a shell window
1424
1425The following options imply -i and will open a shell:
1426
1427 -c cmd run the command in a shell, or
1428 -r file run script from file
1429
1430 -d enable the debugger
1431 -s run $IDLESTARTUP or $PYTHONSTARTUP before anything else
1432 -t title set title of shell window
1433
1434A default edit window will be bypassed when -c, -r, or - are used.
1435
1436[arg]* are passed to the command (-c) or script (-r) in sys.argv[1:].
1437
1438Examples:
1439
1440idle
1441 Open an edit window or shell depending on IDLE's configuration.
1442
1443idle foo.py foobar.py
1444 Edit the files, also open a shell if configured to start with shell.
1445
1446idle -est "Baz" foo.py
1447 Run $IDLESTARTUP or $PYTHONSTARTUP, edit foo.py, and open a shell
1448 window with the title "Baz".
1449
1450idle -c "import sys; print sys.argv" "foo"
1451 Open a shell window and run the command, passing "-c" in sys.argv[0]
1452 and "foo" in sys.argv[1].
1453
1454idle -d -s -r foo.py "Hello World"
1455 Open a shell window, run a startup script, enable the debugger, and
1456 run foo.py, passing "foo.py" in sys.argv[0] and "Hello World" in
1457 sys.argv[1].
1458
1459echo "import sys; print sys.argv" | idle - "foobar"
1460 Open a shell window, run the script piped in, passing '' in sys.argv[0]
1461 and "foobar" in sys.argv[1].
David Scherer7aced172000-08-15 01:13:23 +00001462"""
1463
Kurt B. Kaiser969de452002-06-12 03:28:57 +00001464def main():
Kurt B. Kaiserf06eed02002-12-11 04:42:04 +00001465 global flist, root, use_subprocess
David Scherer7aced172000-08-15 01:13:23 +00001466
Terry Jan Reedy8eab0082013-06-28 23:51:34 -04001467 capture_warnings(True)
Kurt B. Kaiser8f570a72003-05-15 18:52:51 +00001468 use_subprocess = True
Roger Serwy34d0c662013-03-31 23:28:55 -05001469 enable_shell = False
Kurt B. Kaiserf06eed02002-12-11 04:42:04 +00001470 enable_edit = False
1471 debug = False
1472 cmd = None
1473 script = None
1474 startup = False
Kurt B. Kaiser969de452002-06-12 03:28:57 +00001475 try:
Kurt B. Kaiser8f570a72003-05-15 18:52:51 +00001476 opts, args = getopt.getopt(sys.argv[1:], "c:deihnr:st:")
Terry Jan Reedy2b149862013-06-29 00:59:34 -04001477 except getopt.error as msg:
Terry Jan Reedybee003c2014-09-19 22:37:24 -04001478 print("Error: %s\n%s" % (msg, usage_msg), file=sys.stderr)
Kurt B. Kaiser969de452002-06-12 03:28:57 +00001479 sys.exit(2)
Kurt B. Kaiser969de452002-06-12 03:28:57 +00001480 for o, a in opts:
1481 if o == '-c':
1482 cmd = a
Kurt B. Kaiserf06eed02002-12-11 04:42:04 +00001483 enable_shell = True
Kurt B. Kaiser969de452002-06-12 03:28:57 +00001484 if o == '-d':
Kurt B. Kaiserf06eed02002-12-11 04:42:04 +00001485 debug = True
1486 enable_shell = True
Kurt B. Kaiser969de452002-06-12 03:28:57 +00001487 if o == '-e':
Kurt B. Kaiserf06eed02002-12-11 04:42:04 +00001488 enable_edit = True
1489 if o == '-h':
1490 sys.stdout.write(usage_msg)
1491 sys.exit()
1492 if o == '-i':
1493 enable_shell = True
Kurt B. Kaiser8f570a72003-05-15 18:52:51 +00001494 if o == '-n':
1495 use_subprocess = False
Kurt B. Kaiser969de452002-06-12 03:28:57 +00001496 if o == '-r':
1497 script = a
Kurt B. Kaiserf06eed02002-12-11 04:42:04 +00001498 if os.path.isfile(script):
1499 pass
1500 else:
Terry Jan Reedybee003c2014-09-19 22:37:24 -04001501 print("No script file: ", script, file=sys.stderr)
Kurt B. Kaiserf06eed02002-12-11 04:42:04 +00001502 sys.exit()
1503 enable_shell = True
Kurt B. Kaiser969de452002-06-12 03:28:57 +00001504 if o == '-s':
Kurt B. Kaiserf06eed02002-12-11 04:42:04 +00001505 startup = True
1506 enable_shell = True
Kurt B. Kaiser969de452002-06-12 03:28:57 +00001507 if o == '-t':
1508 PyShell.shell_title = a
Kurt B. Kaiserf06eed02002-12-11 04:42:04 +00001509 enable_shell = True
1510 if args and args[0] == '-':
1511 cmd = sys.stdin.read()
1512 enable_shell = True
Kurt B. Kaiserf06eed02002-12-11 04:42:04 +00001513 # process sys.argv and sys.path:
Kurt B. Kaiser969de452002-06-12 03:28:57 +00001514 for i in range(len(sys.path)):
1515 sys.path[i] = os.path.abspath(sys.path[i])
Kurt B. Kaiserf06eed02002-12-11 04:42:04 +00001516 if args and args[0] == '-':
1517 sys.argv = [''] + args[1:]
1518 elif cmd:
1519 sys.argv = ['-c'] + args
1520 elif script:
1521 sys.argv = [script] + args
1522 elif args:
1523 enable_edit = True
1524 pathx = []
Kurt B. Kaiser969de452002-06-12 03:28:57 +00001525 for filename in args:
1526 pathx.append(os.path.dirname(filename))
Kurt B. Kaiserf06eed02002-12-11 04:42:04 +00001527 for dir in pathx:
1528 dir = os.path.abspath(dir)
Florent Xiclunad630c042010-04-02 07:24:52 +00001529 if dir not in sys.path:
Kurt B. Kaiserf06eed02002-12-11 04:42:04 +00001530 sys.path.insert(0, dir)
Kurt B. Kaiserff002b92002-12-21 21:39:11 +00001531 else:
1532 dir = os.getcwd()
1533 if not dir in sys.path:
1534 sys.path.insert(0, dir)
Kurt B. Kaiserf06eed02002-12-11 04:42:04 +00001535 # check the IDLE settings configuration (but command line overrides)
1536 edit_start = idleConf.GetOption('main', 'General',
Kurt B. Kaiser6655e4b2002-12-31 16:03:23 +00001537 'editor-on-startup', type='bool')
Kurt B. Kaiserf06eed02002-12-11 04:42:04 +00001538 enable_edit = enable_edit or edit_start
Roger Serwy34d0c662013-03-31 23:28:55 -05001539 enable_shell = enable_shell or not enable_edit
Kurt B. Kaiserf06eed02002-12-11 04:42:04 +00001540 # start editor and/or shell windows:
Kurt B. Kaiser969de452002-06-12 03:28:57 +00001541 root = Tk(className="Idle")
Ronald Oussoren19302d92006-06-11 14:33:36 +00001542
Terry Jan Reedy4ade2d22014-02-08 09:39:51 -05001543 # set application icon
1544 icondir = os.path.join(os.path.dirname(__file__), 'Icons')
1545 if system() == 'Windows':
1546 iconfile = os.path.join(icondir, 'idle.ico')
1547 root.wm_iconbitmap(default=iconfile)
1548 elif TkVersion >= 8.5:
1549 ext = '.png' if TkVersion >= 8.6 else '.gif'
1550 iconfiles = [os.path.join(icondir, 'idle_%d%s' % (size, ext))
1551 for size in (16, 32, 48)]
1552 icons = [PhotoImage(file=iconfile) for iconfile in iconfiles]
1553 root.tk.call('wm', 'iconphoto', str(root), "-default", *icons)
1554
Kurt B. Kaiser969de452002-06-12 03:28:57 +00001555 fixwordbreaks(root)
1556 root.withdraw()
1557 flist = PyShellFileList(root)
Ronald Oussoren19302d92006-06-11 14:33:36 +00001558 macosxSupport.setupApp(root, flist)
Terry Jan Reedyb60d1032015-09-22 21:13:09 -04001559
Terry Jan Reedyca33d562015-09-22 21:10:22 -04001560 if macosxSupport.isAquaTk():
1561 # There are some screwed up <2> class bindings for text
1562 # widgets defined in Tk which we need to do away with.
1563 # See issue #24801.
1564 root.unbind_class('Text', '<B2>')
1565 root.unbind_class('Text', '<B2-Motion>')
1566 root.unbind_class('Text', '<<PasteSelection>>')
Ronald Oussoren19302d92006-06-11 14:33:36 +00001567
Kurt B. Kaiserf06eed02002-12-11 04:42:04 +00001568 if enable_edit:
1569 if not (cmd or script):
Andrew Svetlov7c010ee2012-03-21 13:35:08 +02001570 for filename in args[:]:
1571 if flist.open(filename) is None:
1572 # filename is a directory actually, disconsider it
1573 args.remove(filename)
Kurt B. Kaiserf06eed02002-12-11 04:42:04 +00001574 if not args:
1575 flist.new()
Ned Deily278543d2013-12-10 16:21:58 -08001576
Kurt B. Kaiseraf3eb872004-01-21 18:54:30 +00001577 if enable_shell:
Ronald Oussoren19302d92006-06-11 14:33:36 +00001578 shell = flist.open_shell()
1579 if not shell:
Kurt B. Kaiseraf3eb872004-01-21 18:54:30 +00001580 return # couldn't open shell
Ned Deily57847df2014-03-27 20:47:04 -07001581 if macosxSupport.isAquaTk() and flist.dict:
Ronald Oussoren19302d92006-06-11 14:33:36 +00001582 # On OSX: when the user has double-clicked on a file that causes
Tim Peters4f96f1f2006-06-11 19:42:51 +00001583 # IDLE to be launched the shell window will open just in front of
1584 # the file she wants to see. Lower the interpreter window when
Ronald Oussoren19302d92006-06-11 14:33:36 +00001585 # there are open files.
1586 shell.top.lower()
Ned Deily278543d2013-12-10 16:21:58 -08001587 else:
1588 shell = flist.pyshell
Ronald Oussoren19302d92006-06-11 14:33:36 +00001589
Ned Deily278543d2013-12-10 16:21:58 -08001590 # Handle remaining options. If any of these are set, enable_shell
1591 # was set also, so shell must be true to reach here.
Kurt B. Kaiserf06eed02002-12-11 04:42:04 +00001592 if debug:
1593 shell.open_debugger()
Kurt B. Kaiser969de452002-06-12 03:28:57 +00001594 if startup:
1595 filename = os.environ.get("IDLESTARTUP") or \
1596 os.environ.get("PYTHONSTARTUP")
1597 if filename and os.path.isfile(filename):
Kurt B. Kaiserf06eed02002-12-11 04:42:04 +00001598 shell.interp.execfile(filename)
Ned Deily278543d2013-12-10 16:21:58 -08001599 if cmd or script:
Kurt B. Kaiserf06eed02002-12-11 04:42:04 +00001600 shell.interp.runcommand("""if 1:
1601 import sys as _sys
Walter Dörwald70a6b492004-02-12 17:35:32 +00001602 _sys.argv = %r
Kurt B. Kaiserf06eed02002-12-11 04:42:04 +00001603 del _sys
Walter Dörwald70a6b492004-02-12 17:35:32 +00001604 \n""" % (sys.argv,))
Kurt B. Kaiserf06eed02002-12-11 04:42:04 +00001605 if cmd:
1606 shell.interp.execsource(cmd)
1607 elif script:
Kurt B. Kaiser11659ad2003-05-15 23:23:21 +00001608 shell.interp.prepend_syspath(script)
Kurt B. Kaiserf06eed02002-12-11 04:42:04 +00001609 shell.interp.execfile(script)
Ned Deily278543d2013-12-10 16:21:58 -08001610 elif shell:
1611 # If there is a shell window and no cmd or script in progress,
1612 # check for problematic OS X Tk versions and print a warning
1613 # message in the IDLE shell window; this is less intrusive
1614 # than always opening a separate window.
1615 tkversionwarning = macosxSupport.tkVersionWarning(root)
1616 if tkversionwarning:
1617 shell.interp.runcommand("print('%s')" % tkversionwarning)
Ned Deily2a6f4b32011-01-30 00:18:47 +00001618
Terry Jan Reedyeaa7e782012-05-26 20:33:32 -04001619 while flist.inversedict: # keep IDLE running while files are open.
1620 root.mainloop()
Kurt B. Kaiser969de452002-06-12 03:28:57 +00001621 root.destroy()
Terry Jan Reedy8eab0082013-06-28 23:51:34 -04001622 capture_warnings(False)
Kurt B. Kaiser969de452002-06-12 03:28:57 +00001623
David Scherer7aced172000-08-15 01:13:23 +00001624if __name__ == "__main__":
Kurt B. Kaiser9e8b8282003-06-15 17:38:45 +00001625 sys.modules['PyShell'] = sys.modules['__main__']
David Scherer7aced172000-08-15 01:13:23 +00001626 main()
Terry Jan Reedy8eab0082013-06-28 23:51:34 -04001627
1628capture_warnings(False) # Make sure turned off; see issue 18081