annotate CSP2/CSP2_env/env-d9b9114564458d9d-741b3de822f2aaca6c6caa4325c4afce/lib/python3.8/idlelib/pyshell.py @ 69:33d812a61356

planemo upload commit 2e9511a184a1ca667c7be0c6321a36dc4e3d116d
author jpayne
date Tue, 18 Mar 2025 17:55:14 -0400
parents
children
rev   line source
jpayne@69 1 #! /usr/bin/env python3
jpayne@69 2
jpayne@69 3 import sys
jpayne@69 4 if __name__ == "__main__":
jpayne@69 5 sys.modules['idlelib.pyshell'] = sys.modules['__main__']
jpayne@69 6
jpayne@69 7 try:
jpayne@69 8 from tkinter import *
jpayne@69 9 except ImportError:
jpayne@69 10 print("** IDLE can't import Tkinter.\n"
jpayne@69 11 "Your Python may not be configured for Tk. **", file=sys.__stderr__)
jpayne@69 12 raise SystemExit(1)
jpayne@69 13
jpayne@69 14 # Valid arguments for the ...Awareness call below are defined in the following.
jpayne@69 15 # https://msdn.microsoft.com/en-us/library/windows/desktop/dn280512(v=vs.85).aspx
jpayne@69 16 if sys.platform == 'win32':
jpayne@69 17 try:
jpayne@69 18 import ctypes
jpayne@69 19 PROCESS_SYSTEM_DPI_AWARE = 1
jpayne@69 20 ctypes.OleDLL('shcore').SetProcessDpiAwareness(PROCESS_SYSTEM_DPI_AWARE)
jpayne@69 21 except (ImportError, AttributeError, OSError):
jpayne@69 22 pass
jpayne@69 23
jpayne@69 24 import tkinter.messagebox as tkMessageBox
jpayne@69 25 if TkVersion < 8.5:
jpayne@69 26 root = Tk() # otherwise create root in main
jpayne@69 27 root.withdraw()
jpayne@69 28 from idlelib.run import fix_scaling
jpayne@69 29 fix_scaling(root)
jpayne@69 30 tkMessageBox.showerror("Idle Cannot Start",
jpayne@69 31 "Idle requires tcl/tk 8.5+, not %s." % TkVersion,
jpayne@69 32 parent=root)
jpayne@69 33 raise SystemExit(1)
jpayne@69 34
jpayne@69 35 from code import InteractiveInterpreter
jpayne@69 36 import linecache
jpayne@69 37 import os
jpayne@69 38 import os.path
jpayne@69 39 from platform import python_version
jpayne@69 40 import re
jpayne@69 41 import socket
jpayne@69 42 import subprocess
jpayne@69 43 from textwrap import TextWrapper
jpayne@69 44 import threading
jpayne@69 45 import time
jpayne@69 46 import tokenize
jpayne@69 47 import warnings
jpayne@69 48
jpayne@69 49 from idlelib.colorizer import ColorDelegator
jpayne@69 50 from idlelib.config import idleConf
jpayne@69 51 from idlelib import debugger
jpayne@69 52 from idlelib import debugger_r
jpayne@69 53 from idlelib.editor import EditorWindow, fixwordbreaks
jpayne@69 54 from idlelib.filelist import FileList
jpayne@69 55 from idlelib.outwin import OutputWindow
jpayne@69 56 from idlelib import rpc
jpayne@69 57 from idlelib.run import idle_formatwarning, StdInputFile, StdOutputFile
jpayne@69 58 from idlelib.undo import UndoDelegator
jpayne@69 59
jpayne@69 60 HOST = '127.0.0.1' # python execution server on localhost loopback
jpayne@69 61 PORT = 0 # someday pass in host, port for remote debug capability
jpayne@69 62
jpayne@69 63 # Override warnings module to write to warning_stream. Initialize to send IDLE
jpayne@69 64 # internal warnings to the console. ScriptBinding.check_syntax() will
jpayne@69 65 # temporarily redirect the stream to the shell window to display warnings when
jpayne@69 66 # checking user's code.
jpayne@69 67 warning_stream = sys.__stderr__ # None, at least on Windows, if no console.
jpayne@69 68
jpayne@69 69 def idle_showwarning(
jpayne@69 70 message, category, filename, lineno, file=None, line=None):
jpayne@69 71 """Show Idle-format warning (after replacing warnings.showwarning).
jpayne@69 72
jpayne@69 73 The differences are the formatter called, the file=None replacement,
jpayne@69 74 which can be None, the capture of the consequence AttributeError,
jpayne@69 75 and the output of a hard-coded prompt.
jpayne@69 76 """
jpayne@69 77 if file is None:
jpayne@69 78 file = warning_stream
jpayne@69 79 try:
jpayne@69 80 file.write(idle_formatwarning(
jpayne@69 81 message, category, filename, lineno, line=line))
jpayne@69 82 file.write(">>> ")
jpayne@69 83 except (AttributeError, OSError):
jpayne@69 84 pass # if file (probably __stderr__) is invalid, skip warning.
jpayne@69 85
jpayne@69 86 _warnings_showwarning = None
jpayne@69 87
jpayne@69 88 def capture_warnings(capture):
jpayne@69 89 "Replace warning.showwarning with idle_showwarning, or reverse."
jpayne@69 90
jpayne@69 91 global _warnings_showwarning
jpayne@69 92 if capture:
jpayne@69 93 if _warnings_showwarning is None:
jpayne@69 94 _warnings_showwarning = warnings.showwarning
jpayne@69 95 warnings.showwarning = idle_showwarning
jpayne@69 96 else:
jpayne@69 97 if _warnings_showwarning is not None:
jpayne@69 98 warnings.showwarning = _warnings_showwarning
jpayne@69 99 _warnings_showwarning = None
jpayne@69 100
jpayne@69 101 capture_warnings(True)
jpayne@69 102
jpayne@69 103 def extended_linecache_checkcache(filename=None,
jpayne@69 104 orig_checkcache=linecache.checkcache):
jpayne@69 105 """Extend linecache.checkcache to preserve the <pyshell#...> entries
jpayne@69 106
jpayne@69 107 Rather than repeating the linecache code, patch it to save the
jpayne@69 108 <pyshell#...> entries, call the original linecache.checkcache()
jpayne@69 109 (skipping them), and then restore the saved entries.
jpayne@69 110
jpayne@69 111 orig_checkcache is bound at definition time to the original
jpayne@69 112 method, allowing it to be patched.
jpayne@69 113 """
jpayne@69 114 cache = linecache.cache
jpayne@69 115 save = {}
jpayne@69 116 for key in list(cache):
jpayne@69 117 if key[:1] + key[-1:] == '<>':
jpayne@69 118 save[key] = cache.pop(key)
jpayne@69 119 orig_checkcache(filename)
jpayne@69 120 cache.update(save)
jpayne@69 121
jpayne@69 122 # Patch linecache.checkcache():
jpayne@69 123 linecache.checkcache = extended_linecache_checkcache
jpayne@69 124
jpayne@69 125
jpayne@69 126 class PyShellEditorWindow(EditorWindow):
jpayne@69 127 "Regular text edit window in IDLE, supports breakpoints"
jpayne@69 128
jpayne@69 129 def __init__(self, *args):
jpayne@69 130 self.breakpoints = []
jpayne@69 131 EditorWindow.__init__(self, *args)
jpayne@69 132 self.text.bind("<<set-breakpoint-here>>", self.set_breakpoint_here)
jpayne@69 133 self.text.bind("<<clear-breakpoint-here>>", self.clear_breakpoint_here)
jpayne@69 134 self.text.bind("<<open-python-shell>>", self.flist.open_shell)
jpayne@69 135
jpayne@69 136 #TODO: don't read/write this from/to .idlerc when testing
jpayne@69 137 self.breakpointPath = os.path.join(
jpayne@69 138 idleConf.userdir, 'breakpoints.lst')
jpayne@69 139 # whenever a file is changed, restore breakpoints
jpayne@69 140 def filename_changed_hook(old_hook=self.io.filename_change_hook,
jpayne@69 141 self=self):
jpayne@69 142 self.restore_file_breaks()
jpayne@69 143 old_hook()
jpayne@69 144 self.io.set_filename_change_hook(filename_changed_hook)
jpayne@69 145 if self.io.filename:
jpayne@69 146 self.restore_file_breaks()
jpayne@69 147 self.color_breakpoint_text()
jpayne@69 148
jpayne@69 149 rmenu_specs = [
jpayne@69 150 ("Cut", "<<cut>>", "rmenu_check_cut"),
jpayne@69 151 ("Copy", "<<copy>>", "rmenu_check_copy"),
jpayne@69 152 ("Paste", "<<paste>>", "rmenu_check_paste"),
jpayne@69 153 (None, None, None),
jpayne@69 154 ("Set Breakpoint", "<<set-breakpoint-here>>", None),
jpayne@69 155 ("Clear Breakpoint", "<<clear-breakpoint-here>>", None)
jpayne@69 156 ]
jpayne@69 157
jpayne@69 158 def color_breakpoint_text(self, color=True):
jpayne@69 159 "Turn colorizing of breakpoint text on or off"
jpayne@69 160 if self.io is None:
jpayne@69 161 # possible due to update in restore_file_breaks
jpayne@69 162 return
jpayne@69 163 if color:
jpayne@69 164 theme = idleConf.CurrentTheme()
jpayne@69 165 cfg = idleConf.GetHighlight(theme, "break")
jpayne@69 166 else:
jpayne@69 167 cfg = {'foreground': '', 'background': ''}
jpayne@69 168 self.text.tag_config('BREAK', cfg)
jpayne@69 169
jpayne@69 170 def set_breakpoint(self, lineno):
jpayne@69 171 text = self.text
jpayne@69 172 filename = self.io.filename
jpayne@69 173 text.tag_add("BREAK", "%d.0" % lineno, "%d.0" % (lineno+1))
jpayne@69 174 try:
jpayne@69 175 self.breakpoints.index(lineno)
jpayne@69 176 except ValueError: # only add if missing, i.e. do once
jpayne@69 177 self.breakpoints.append(lineno)
jpayne@69 178 try: # update the subprocess debugger
jpayne@69 179 debug = self.flist.pyshell.interp.debugger
jpayne@69 180 debug.set_breakpoint_here(filename, lineno)
jpayne@69 181 except: # but debugger may not be active right now....
jpayne@69 182 pass
jpayne@69 183
jpayne@69 184 def set_breakpoint_here(self, event=None):
jpayne@69 185 text = self.text
jpayne@69 186 filename = self.io.filename
jpayne@69 187 if not filename:
jpayne@69 188 text.bell()
jpayne@69 189 return
jpayne@69 190 lineno = int(float(text.index("insert")))
jpayne@69 191 self.set_breakpoint(lineno)
jpayne@69 192
jpayne@69 193 def clear_breakpoint_here(self, event=None):
jpayne@69 194 text = self.text
jpayne@69 195 filename = self.io.filename
jpayne@69 196 if not filename:
jpayne@69 197 text.bell()
jpayne@69 198 return
jpayne@69 199 lineno = int(float(text.index("insert")))
jpayne@69 200 try:
jpayne@69 201 self.breakpoints.remove(lineno)
jpayne@69 202 except:
jpayne@69 203 pass
jpayne@69 204 text.tag_remove("BREAK", "insert linestart",\
jpayne@69 205 "insert lineend +1char")
jpayne@69 206 try:
jpayne@69 207 debug = self.flist.pyshell.interp.debugger
jpayne@69 208 debug.clear_breakpoint_here(filename, lineno)
jpayne@69 209 except:
jpayne@69 210 pass
jpayne@69 211
jpayne@69 212 def clear_file_breaks(self):
jpayne@69 213 if self.breakpoints:
jpayne@69 214 text = self.text
jpayne@69 215 filename = self.io.filename
jpayne@69 216 if not filename:
jpayne@69 217 text.bell()
jpayne@69 218 return
jpayne@69 219 self.breakpoints = []
jpayne@69 220 text.tag_remove("BREAK", "1.0", END)
jpayne@69 221 try:
jpayne@69 222 debug = self.flist.pyshell.interp.debugger
jpayne@69 223 debug.clear_file_breaks(filename)
jpayne@69 224 except:
jpayne@69 225 pass
jpayne@69 226
jpayne@69 227 def store_file_breaks(self):
jpayne@69 228 "Save breakpoints when file is saved"
jpayne@69 229 # XXX 13 Dec 2002 KBK Currently the file must be saved before it can
jpayne@69 230 # be run. The breaks are saved at that time. If we introduce
jpayne@69 231 # a temporary file save feature the save breaks functionality
jpayne@69 232 # needs to be re-verified, since the breaks at the time the
jpayne@69 233 # temp file is created may differ from the breaks at the last
jpayne@69 234 # permanent save of the file. Currently, a break introduced
jpayne@69 235 # after a save will be effective, but not persistent.
jpayne@69 236 # This is necessary to keep the saved breaks synched with the
jpayne@69 237 # saved file.
jpayne@69 238 #
jpayne@69 239 # Breakpoints are set as tagged ranges in the text.
jpayne@69 240 # Since a modified file has to be saved before it is
jpayne@69 241 # run, and since self.breakpoints (from which the subprocess
jpayne@69 242 # debugger is loaded) is updated during the save, the visible
jpayne@69 243 # breaks stay synched with the subprocess even if one of these
jpayne@69 244 # unexpected breakpoint deletions occurs.
jpayne@69 245 breaks = self.breakpoints
jpayne@69 246 filename = self.io.filename
jpayne@69 247 try:
jpayne@69 248 with open(self.breakpointPath, "r") as fp:
jpayne@69 249 lines = fp.readlines()
jpayne@69 250 except OSError:
jpayne@69 251 lines = []
jpayne@69 252 try:
jpayne@69 253 with open(self.breakpointPath, "w") as new_file:
jpayne@69 254 for line in lines:
jpayne@69 255 if not line.startswith(filename + '='):
jpayne@69 256 new_file.write(line)
jpayne@69 257 self.update_breakpoints()
jpayne@69 258 breaks = self.breakpoints
jpayne@69 259 if breaks:
jpayne@69 260 new_file.write(filename + '=' + str(breaks) + '\n')
jpayne@69 261 except OSError as err:
jpayne@69 262 if not getattr(self.root, "breakpoint_error_displayed", False):
jpayne@69 263 self.root.breakpoint_error_displayed = True
jpayne@69 264 tkMessageBox.showerror(title='IDLE Error',
jpayne@69 265 message='Unable to update breakpoint list:\n%s'
jpayne@69 266 % str(err),
jpayne@69 267 parent=self.text)
jpayne@69 268
jpayne@69 269 def restore_file_breaks(self):
jpayne@69 270 self.text.update() # this enables setting "BREAK" tags to be visible
jpayne@69 271 if self.io is None:
jpayne@69 272 # can happen if IDLE closes due to the .update() call
jpayne@69 273 return
jpayne@69 274 filename = self.io.filename
jpayne@69 275 if filename is None:
jpayne@69 276 return
jpayne@69 277 if os.path.isfile(self.breakpointPath):
jpayne@69 278 with open(self.breakpointPath, "r") as fp:
jpayne@69 279 lines = fp.readlines()
jpayne@69 280 for line in lines:
jpayne@69 281 if line.startswith(filename + '='):
jpayne@69 282 breakpoint_linenumbers = eval(line[len(filename)+1:])
jpayne@69 283 for breakpoint_linenumber in breakpoint_linenumbers:
jpayne@69 284 self.set_breakpoint(breakpoint_linenumber)
jpayne@69 285
jpayne@69 286 def update_breakpoints(self):
jpayne@69 287 "Retrieves all the breakpoints in the current window"
jpayne@69 288 text = self.text
jpayne@69 289 ranges = text.tag_ranges("BREAK")
jpayne@69 290 linenumber_list = self.ranges_to_linenumbers(ranges)
jpayne@69 291 self.breakpoints = linenumber_list
jpayne@69 292
jpayne@69 293 def ranges_to_linenumbers(self, ranges):
jpayne@69 294 lines = []
jpayne@69 295 for index in range(0, len(ranges), 2):
jpayne@69 296 lineno = int(float(ranges[index].string))
jpayne@69 297 end = int(float(ranges[index+1].string))
jpayne@69 298 while lineno < end:
jpayne@69 299 lines.append(lineno)
jpayne@69 300 lineno += 1
jpayne@69 301 return lines
jpayne@69 302
jpayne@69 303 # XXX 13 Dec 2002 KBK Not used currently
jpayne@69 304 # def saved_change_hook(self):
jpayne@69 305 # "Extend base method - clear breaks if module is modified"
jpayne@69 306 # if not self.get_saved():
jpayne@69 307 # self.clear_file_breaks()
jpayne@69 308 # EditorWindow.saved_change_hook(self)
jpayne@69 309
jpayne@69 310 def _close(self):
jpayne@69 311 "Extend base method - clear breaks when module is closed"
jpayne@69 312 self.clear_file_breaks()
jpayne@69 313 EditorWindow._close(self)
jpayne@69 314
jpayne@69 315
jpayne@69 316 class PyShellFileList(FileList):
jpayne@69 317 "Extend base class: IDLE supports a shell and breakpoints"
jpayne@69 318
jpayne@69 319 # override FileList's class variable, instances return PyShellEditorWindow
jpayne@69 320 # instead of EditorWindow when new edit windows are created.
jpayne@69 321 EditorWindow = PyShellEditorWindow
jpayne@69 322
jpayne@69 323 pyshell = None
jpayne@69 324
jpayne@69 325 def open_shell(self, event=None):
jpayne@69 326 if self.pyshell:
jpayne@69 327 self.pyshell.top.wakeup()
jpayne@69 328 else:
jpayne@69 329 self.pyshell = PyShell(self)
jpayne@69 330 if self.pyshell:
jpayne@69 331 if not self.pyshell.begin():
jpayne@69 332 return None
jpayne@69 333 return self.pyshell
jpayne@69 334
jpayne@69 335
jpayne@69 336 class ModifiedColorDelegator(ColorDelegator):
jpayne@69 337 "Extend base class: colorizer for the shell window itself"
jpayne@69 338
jpayne@69 339 def __init__(self):
jpayne@69 340 ColorDelegator.__init__(self)
jpayne@69 341 self.LoadTagDefs()
jpayne@69 342
jpayne@69 343 def recolorize_main(self):
jpayne@69 344 self.tag_remove("TODO", "1.0", "iomark")
jpayne@69 345 self.tag_add("SYNC", "1.0", "iomark")
jpayne@69 346 ColorDelegator.recolorize_main(self)
jpayne@69 347
jpayne@69 348 def LoadTagDefs(self):
jpayne@69 349 ColorDelegator.LoadTagDefs(self)
jpayne@69 350 theme = idleConf.CurrentTheme()
jpayne@69 351 self.tagdefs.update({
jpayne@69 352 "stdin": {'background':None,'foreground':None},
jpayne@69 353 "stdout": idleConf.GetHighlight(theme, "stdout"),
jpayne@69 354 "stderr": idleConf.GetHighlight(theme, "stderr"),
jpayne@69 355 "console": idleConf.GetHighlight(theme, "console"),
jpayne@69 356 })
jpayne@69 357
jpayne@69 358 def removecolors(self):
jpayne@69 359 # Don't remove shell color tags before "iomark"
jpayne@69 360 for tag in self.tagdefs:
jpayne@69 361 self.tag_remove(tag, "iomark", "end")
jpayne@69 362
jpayne@69 363 class ModifiedUndoDelegator(UndoDelegator):
jpayne@69 364 "Extend base class: forbid insert/delete before the I/O mark"
jpayne@69 365
jpayne@69 366 def insert(self, index, chars, tags=None):
jpayne@69 367 try:
jpayne@69 368 if self.delegate.compare(index, "<", "iomark"):
jpayne@69 369 self.delegate.bell()
jpayne@69 370 return
jpayne@69 371 except TclError:
jpayne@69 372 pass
jpayne@69 373 UndoDelegator.insert(self, index, chars, tags)
jpayne@69 374
jpayne@69 375 def delete(self, index1, index2=None):
jpayne@69 376 try:
jpayne@69 377 if self.delegate.compare(index1, "<", "iomark"):
jpayne@69 378 self.delegate.bell()
jpayne@69 379 return
jpayne@69 380 except TclError:
jpayne@69 381 pass
jpayne@69 382 UndoDelegator.delete(self, index1, index2)
jpayne@69 383
jpayne@69 384
jpayne@69 385 class MyRPCClient(rpc.RPCClient):
jpayne@69 386
jpayne@69 387 def handle_EOF(self):
jpayne@69 388 "Override the base class - just re-raise EOFError"
jpayne@69 389 raise EOFError
jpayne@69 390
jpayne@69 391 def restart_line(width, filename): # See bpo-38141.
jpayne@69 392 """Return width long restart line formatted with filename.
jpayne@69 393
jpayne@69 394 Fill line with balanced '='s, with any extras and at least one at
jpayne@69 395 the beginning. Do not end with a trailing space.
jpayne@69 396 """
jpayne@69 397 tag = f"= RESTART: {filename or 'Shell'} ="
jpayne@69 398 if width >= len(tag):
jpayne@69 399 div, mod = divmod((width -len(tag)), 2)
jpayne@69 400 return f"{(div+mod)*'='}{tag}{div*'='}"
jpayne@69 401 else:
jpayne@69 402 return tag[:-2] # Remove ' ='.
jpayne@69 403
jpayne@69 404
jpayne@69 405 class ModifiedInterpreter(InteractiveInterpreter):
jpayne@69 406
jpayne@69 407 def __init__(self, tkconsole):
jpayne@69 408 self.tkconsole = tkconsole
jpayne@69 409 locals = sys.modules['__main__'].__dict__
jpayne@69 410 InteractiveInterpreter.__init__(self, locals=locals)
jpayne@69 411 self.restarting = False
jpayne@69 412 self.subprocess_arglist = None
jpayne@69 413 self.port = PORT
jpayne@69 414 self.original_compiler_flags = self.compile.compiler.flags
jpayne@69 415
jpayne@69 416 _afterid = None
jpayne@69 417 rpcclt = None
jpayne@69 418 rpcsubproc = None
jpayne@69 419
jpayne@69 420 def spawn_subprocess(self):
jpayne@69 421 if self.subprocess_arglist is None:
jpayne@69 422 self.subprocess_arglist = self.build_subprocess_arglist()
jpayne@69 423 self.rpcsubproc = subprocess.Popen(self.subprocess_arglist)
jpayne@69 424
jpayne@69 425 def build_subprocess_arglist(self):
jpayne@69 426 assert (self.port!=0), (
jpayne@69 427 "Socket should have been assigned a port number.")
jpayne@69 428 w = ['-W' + s for s in sys.warnoptions]
jpayne@69 429 # Maybe IDLE is installed and is being accessed via sys.path,
jpayne@69 430 # or maybe it's not installed and the idle.py script is being
jpayne@69 431 # run from the IDLE source directory.
jpayne@69 432 del_exitf = idleConf.GetOption('main', 'General', 'delete-exitfunc',
jpayne@69 433 default=False, type='bool')
jpayne@69 434 command = "__import__('idlelib.run').run.main(%r)" % (del_exitf,)
jpayne@69 435 return [sys.executable] + w + ["-c", command, str(self.port)]
jpayne@69 436
jpayne@69 437 def start_subprocess(self):
jpayne@69 438 addr = (HOST, self.port)
jpayne@69 439 # GUI makes several attempts to acquire socket, listens for connection
jpayne@69 440 for i in range(3):
jpayne@69 441 time.sleep(i)
jpayne@69 442 try:
jpayne@69 443 self.rpcclt = MyRPCClient(addr)
jpayne@69 444 break
jpayne@69 445 except OSError:
jpayne@69 446 pass
jpayne@69 447 else:
jpayne@69 448 self.display_port_binding_error()
jpayne@69 449 return None
jpayne@69 450 # if PORT was 0, system will assign an 'ephemeral' port. Find it out:
jpayne@69 451 self.port = self.rpcclt.listening_sock.getsockname()[1]
jpayne@69 452 # if PORT was not 0, probably working with a remote execution server
jpayne@69 453 if PORT != 0:
jpayne@69 454 # To allow reconnection within the 2MSL wait (cf. Stevens TCP
jpayne@69 455 # V1, 18.6), set SO_REUSEADDR. Note that this can be problematic
jpayne@69 456 # on Windows since the implementation allows two active sockets on
jpayne@69 457 # the same address!
jpayne@69 458 self.rpcclt.listening_sock.setsockopt(socket.SOL_SOCKET,
jpayne@69 459 socket.SO_REUSEADDR, 1)
jpayne@69 460 self.spawn_subprocess()
jpayne@69 461 #time.sleep(20) # test to simulate GUI not accepting connection
jpayne@69 462 # Accept the connection from the Python execution server
jpayne@69 463 self.rpcclt.listening_sock.settimeout(10)
jpayne@69 464 try:
jpayne@69 465 self.rpcclt.accept()
jpayne@69 466 except socket.timeout:
jpayne@69 467 self.display_no_subprocess_error()
jpayne@69 468 return None
jpayne@69 469 self.rpcclt.register("console", self.tkconsole)
jpayne@69 470 self.rpcclt.register("stdin", self.tkconsole.stdin)
jpayne@69 471 self.rpcclt.register("stdout", self.tkconsole.stdout)
jpayne@69 472 self.rpcclt.register("stderr", self.tkconsole.stderr)
jpayne@69 473 self.rpcclt.register("flist", self.tkconsole.flist)
jpayne@69 474 self.rpcclt.register("linecache", linecache)
jpayne@69 475 self.rpcclt.register("interp", self)
jpayne@69 476 self.transfer_path(with_cwd=True)
jpayne@69 477 self.poll_subprocess()
jpayne@69 478 return self.rpcclt
jpayne@69 479
jpayne@69 480 def restart_subprocess(self, with_cwd=False, filename=''):
jpayne@69 481 if self.restarting:
jpayne@69 482 return self.rpcclt
jpayne@69 483 self.restarting = True
jpayne@69 484 # close only the subprocess debugger
jpayne@69 485 debug = self.getdebugger()
jpayne@69 486 if debug:
jpayne@69 487 try:
jpayne@69 488 # Only close subprocess debugger, don't unregister gui_adap!
jpayne@69 489 debugger_r.close_subprocess_debugger(self.rpcclt)
jpayne@69 490 except:
jpayne@69 491 pass
jpayne@69 492 # Kill subprocess, spawn a new one, accept connection.
jpayne@69 493 self.rpcclt.close()
jpayne@69 494 self.terminate_subprocess()
jpayne@69 495 console = self.tkconsole
jpayne@69 496 was_executing = console.executing
jpayne@69 497 console.executing = False
jpayne@69 498 self.spawn_subprocess()
jpayne@69 499 try:
jpayne@69 500 self.rpcclt.accept()
jpayne@69 501 except socket.timeout:
jpayne@69 502 self.display_no_subprocess_error()
jpayne@69 503 return None
jpayne@69 504 self.transfer_path(with_cwd=with_cwd)
jpayne@69 505 console.stop_readline()
jpayne@69 506 # annotate restart in shell window and mark it
jpayne@69 507 console.text.delete("iomark", "end-1c")
jpayne@69 508 console.write('\n')
jpayne@69 509 console.write(restart_line(console.width, filename))
jpayne@69 510 console.text.mark_set("restart", "end-1c")
jpayne@69 511 console.text.mark_gravity("restart", "left")
jpayne@69 512 if not filename:
jpayne@69 513 console.showprompt()
jpayne@69 514 # restart subprocess debugger
jpayne@69 515 if debug:
jpayne@69 516 # Restarted debugger connects to current instance of debug GUI
jpayne@69 517 debugger_r.restart_subprocess_debugger(self.rpcclt)
jpayne@69 518 # reload remote debugger breakpoints for all PyShellEditWindows
jpayne@69 519 debug.load_breakpoints()
jpayne@69 520 self.compile.compiler.flags = self.original_compiler_flags
jpayne@69 521 self.restarting = False
jpayne@69 522 return self.rpcclt
jpayne@69 523
jpayne@69 524 def __request_interrupt(self):
jpayne@69 525 self.rpcclt.remotecall("exec", "interrupt_the_server", (), {})
jpayne@69 526
jpayne@69 527 def interrupt_subprocess(self):
jpayne@69 528 threading.Thread(target=self.__request_interrupt).start()
jpayne@69 529
jpayne@69 530 def kill_subprocess(self):
jpayne@69 531 if self._afterid is not None:
jpayne@69 532 self.tkconsole.text.after_cancel(self._afterid)
jpayne@69 533 try:
jpayne@69 534 self.rpcclt.listening_sock.close()
jpayne@69 535 except AttributeError: # no socket
jpayne@69 536 pass
jpayne@69 537 try:
jpayne@69 538 self.rpcclt.close()
jpayne@69 539 except AttributeError: # no socket
jpayne@69 540 pass
jpayne@69 541 self.terminate_subprocess()
jpayne@69 542 self.tkconsole.executing = False
jpayne@69 543 self.rpcclt = None
jpayne@69 544
jpayne@69 545 def terminate_subprocess(self):
jpayne@69 546 "Make sure subprocess is terminated"
jpayne@69 547 try:
jpayne@69 548 self.rpcsubproc.kill()
jpayne@69 549 except OSError:
jpayne@69 550 # process already terminated
jpayne@69 551 return
jpayne@69 552 else:
jpayne@69 553 try:
jpayne@69 554 self.rpcsubproc.wait()
jpayne@69 555 except OSError:
jpayne@69 556 return
jpayne@69 557
jpayne@69 558 def transfer_path(self, with_cwd=False):
jpayne@69 559 if with_cwd: # Issue 13506
jpayne@69 560 path = [''] # include Current Working Directory
jpayne@69 561 path.extend(sys.path)
jpayne@69 562 else:
jpayne@69 563 path = sys.path
jpayne@69 564
jpayne@69 565 self.runcommand("""if 1:
jpayne@69 566 import sys as _sys
jpayne@69 567 _sys.path = %r
jpayne@69 568 del _sys
jpayne@69 569 \n""" % (path,))
jpayne@69 570
jpayne@69 571 active_seq = None
jpayne@69 572
jpayne@69 573 def poll_subprocess(self):
jpayne@69 574 clt = self.rpcclt
jpayne@69 575 if clt is None:
jpayne@69 576 return
jpayne@69 577 try:
jpayne@69 578 response = clt.pollresponse(self.active_seq, wait=0.05)
jpayne@69 579 except (EOFError, OSError, KeyboardInterrupt):
jpayne@69 580 # lost connection or subprocess terminated itself, restart
jpayne@69 581 # [the KBI is from rpc.SocketIO.handle_EOF()]
jpayne@69 582 if self.tkconsole.closing:
jpayne@69 583 return
jpayne@69 584 response = None
jpayne@69 585 self.restart_subprocess()
jpayne@69 586 if response:
jpayne@69 587 self.tkconsole.resetoutput()
jpayne@69 588 self.active_seq = None
jpayne@69 589 how, what = response
jpayne@69 590 console = self.tkconsole.console
jpayne@69 591 if how == "OK":
jpayne@69 592 if what is not None:
jpayne@69 593 print(repr(what), file=console)
jpayne@69 594 elif how == "EXCEPTION":
jpayne@69 595 if self.tkconsole.getvar("<<toggle-jit-stack-viewer>>"):
jpayne@69 596 self.remote_stack_viewer()
jpayne@69 597 elif how == "ERROR":
jpayne@69 598 errmsg = "pyshell.ModifiedInterpreter: Subprocess ERROR:\n"
jpayne@69 599 print(errmsg, what, file=sys.__stderr__)
jpayne@69 600 print(errmsg, what, file=console)
jpayne@69 601 # we received a response to the currently active seq number:
jpayne@69 602 try:
jpayne@69 603 self.tkconsole.endexecuting()
jpayne@69 604 except AttributeError: # shell may have closed
jpayne@69 605 pass
jpayne@69 606 # Reschedule myself
jpayne@69 607 if not self.tkconsole.closing:
jpayne@69 608 self._afterid = self.tkconsole.text.after(
jpayne@69 609 self.tkconsole.pollinterval, self.poll_subprocess)
jpayne@69 610
jpayne@69 611 debugger = None
jpayne@69 612
jpayne@69 613 def setdebugger(self, debugger):
jpayne@69 614 self.debugger = debugger
jpayne@69 615
jpayne@69 616 def getdebugger(self):
jpayne@69 617 return self.debugger
jpayne@69 618
jpayne@69 619 def open_remote_stack_viewer(self):
jpayne@69 620 """Initiate the remote stack viewer from a separate thread.
jpayne@69 621
jpayne@69 622 This method is called from the subprocess, and by returning from this
jpayne@69 623 method we allow the subprocess to unblock. After a bit the shell
jpayne@69 624 requests the subprocess to open the remote stack viewer which returns a
jpayne@69 625 static object looking at the last exception. It is queried through
jpayne@69 626 the RPC mechanism.
jpayne@69 627
jpayne@69 628 """
jpayne@69 629 self.tkconsole.text.after(300, self.remote_stack_viewer)
jpayne@69 630 return
jpayne@69 631
jpayne@69 632 def remote_stack_viewer(self):
jpayne@69 633 from idlelib import debugobj_r
jpayne@69 634 oid = self.rpcclt.remotequeue("exec", "stackviewer", ("flist",), {})
jpayne@69 635 if oid is None:
jpayne@69 636 self.tkconsole.root.bell()
jpayne@69 637 return
jpayne@69 638 item = debugobj_r.StubObjectTreeItem(self.rpcclt, oid)
jpayne@69 639 from idlelib.tree import ScrolledCanvas, TreeNode
jpayne@69 640 top = Toplevel(self.tkconsole.root)
jpayne@69 641 theme = idleConf.CurrentTheme()
jpayne@69 642 background = idleConf.GetHighlight(theme, 'normal')['background']
jpayne@69 643 sc = ScrolledCanvas(top, bg=background, highlightthickness=0)
jpayne@69 644 sc.frame.pack(expand=1, fill="both")
jpayne@69 645 node = TreeNode(sc.canvas, None, item)
jpayne@69 646 node.expand()
jpayne@69 647 # XXX Should GC the remote tree when closing the window
jpayne@69 648
jpayne@69 649 gid = 0
jpayne@69 650
jpayne@69 651 def execsource(self, source):
jpayne@69 652 "Like runsource() but assumes complete exec source"
jpayne@69 653 filename = self.stuffsource(source)
jpayne@69 654 self.execfile(filename, source)
jpayne@69 655
jpayne@69 656 def execfile(self, filename, source=None):
jpayne@69 657 "Execute an existing file"
jpayne@69 658 if source is None:
jpayne@69 659 with tokenize.open(filename) as fp:
jpayne@69 660 source = fp.read()
jpayne@69 661 if use_subprocess:
jpayne@69 662 source = (f"__file__ = r'''{os.path.abspath(filename)}'''\n"
jpayne@69 663 + source + "\ndel __file__")
jpayne@69 664 try:
jpayne@69 665 code = compile(source, filename, "exec")
jpayne@69 666 except (OverflowError, SyntaxError):
jpayne@69 667 self.tkconsole.resetoutput()
jpayne@69 668 print('*** Error in script or command!\n'
jpayne@69 669 'Traceback (most recent call last):',
jpayne@69 670 file=self.tkconsole.stderr)
jpayne@69 671 InteractiveInterpreter.showsyntaxerror(self, filename)
jpayne@69 672 self.tkconsole.showprompt()
jpayne@69 673 else:
jpayne@69 674 self.runcode(code)
jpayne@69 675
jpayne@69 676 def runsource(self, source):
jpayne@69 677 "Extend base class method: Stuff the source in the line cache first"
jpayne@69 678 filename = self.stuffsource(source)
jpayne@69 679 self.more = 0
jpayne@69 680 # at the moment, InteractiveInterpreter expects str
jpayne@69 681 assert isinstance(source, str)
jpayne@69 682 # InteractiveInterpreter.runsource() calls its runcode() method,
jpayne@69 683 # which is overridden (see below)
jpayne@69 684 return InteractiveInterpreter.runsource(self, source, filename)
jpayne@69 685
jpayne@69 686 def stuffsource(self, source):
jpayne@69 687 "Stuff source in the filename cache"
jpayne@69 688 filename = "<pyshell#%d>" % self.gid
jpayne@69 689 self.gid = self.gid + 1
jpayne@69 690 lines = source.split("\n")
jpayne@69 691 linecache.cache[filename] = len(source)+1, 0, lines, filename
jpayne@69 692 return filename
jpayne@69 693
jpayne@69 694 def prepend_syspath(self, filename):
jpayne@69 695 "Prepend sys.path with file's directory if not already included"
jpayne@69 696 self.runcommand("""if 1:
jpayne@69 697 _filename = %r
jpayne@69 698 import sys as _sys
jpayne@69 699 from os.path import dirname as _dirname
jpayne@69 700 _dir = _dirname(_filename)
jpayne@69 701 if not _dir in _sys.path:
jpayne@69 702 _sys.path.insert(0, _dir)
jpayne@69 703 del _filename, _sys, _dirname, _dir
jpayne@69 704 \n""" % (filename,))
jpayne@69 705
jpayne@69 706 def showsyntaxerror(self, filename=None):
jpayne@69 707 """Override Interactive Interpreter method: Use Colorizing
jpayne@69 708
jpayne@69 709 Color the offending position instead of printing it and pointing at it
jpayne@69 710 with a caret.
jpayne@69 711
jpayne@69 712 """
jpayne@69 713 tkconsole = self.tkconsole
jpayne@69 714 text = tkconsole.text
jpayne@69 715 text.tag_remove("ERROR", "1.0", "end")
jpayne@69 716 type, value, tb = sys.exc_info()
jpayne@69 717 msg = getattr(value, 'msg', '') or value or "<no detail available>"
jpayne@69 718 lineno = getattr(value, 'lineno', '') or 1
jpayne@69 719 offset = getattr(value, 'offset', '') or 0
jpayne@69 720 if offset == 0:
jpayne@69 721 lineno += 1 #mark end of offending line
jpayne@69 722 if lineno == 1:
jpayne@69 723 pos = "iomark + %d chars" % (offset-1)
jpayne@69 724 else:
jpayne@69 725 pos = "iomark linestart + %d lines + %d chars" % \
jpayne@69 726 (lineno-1, offset-1)
jpayne@69 727 tkconsole.colorize_syntax_error(text, pos)
jpayne@69 728 tkconsole.resetoutput()
jpayne@69 729 self.write("SyntaxError: %s\n" % msg)
jpayne@69 730 tkconsole.showprompt()
jpayne@69 731
jpayne@69 732 def showtraceback(self):
jpayne@69 733 "Extend base class method to reset output properly"
jpayne@69 734 self.tkconsole.resetoutput()
jpayne@69 735 self.checklinecache()
jpayne@69 736 InteractiveInterpreter.showtraceback(self)
jpayne@69 737 if self.tkconsole.getvar("<<toggle-jit-stack-viewer>>"):
jpayne@69 738 self.tkconsole.open_stack_viewer()
jpayne@69 739
jpayne@69 740 def checklinecache(self):
jpayne@69 741 c = linecache.cache
jpayne@69 742 for key in list(c.keys()):
jpayne@69 743 if key[:1] + key[-1:] != "<>":
jpayne@69 744 del c[key]
jpayne@69 745
jpayne@69 746 def runcommand(self, code):
jpayne@69 747 "Run the code without invoking the debugger"
jpayne@69 748 # The code better not raise an exception!
jpayne@69 749 if self.tkconsole.executing:
jpayne@69 750 self.display_executing_dialog()
jpayne@69 751 return 0
jpayne@69 752 if self.rpcclt:
jpayne@69 753 self.rpcclt.remotequeue("exec", "runcode", (code,), {})
jpayne@69 754 else:
jpayne@69 755 exec(code, self.locals)
jpayne@69 756 return 1
jpayne@69 757
jpayne@69 758 def runcode(self, code):
jpayne@69 759 "Override base class method"
jpayne@69 760 if self.tkconsole.executing:
jpayne@69 761 self.interp.restart_subprocess()
jpayne@69 762 self.checklinecache()
jpayne@69 763 debugger = self.debugger
jpayne@69 764 try:
jpayne@69 765 self.tkconsole.beginexecuting()
jpayne@69 766 if not debugger and self.rpcclt is not None:
jpayne@69 767 self.active_seq = self.rpcclt.asyncqueue("exec", "runcode",
jpayne@69 768 (code,), {})
jpayne@69 769 elif debugger:
jpayne@69 770 debugger.run(code, self.locals)
jpayne@69 771 else:
jpayne@69 772 exec(code, self.locals)
jpayne@69 773 except SystemExit:
jpayne@69 774 if not self.tkconsole.closing:
jpayne@69 775 if tkMessageBox.askyesno(
jpayne@69 776 "Exit?",
jpayne@69 777 "Do you want to exit altogether?",
jpayne@69 778 default="yes",
jpayne@69 779 parent=self.tkconsole.text):
jpayne@69 780 raise
jpayne@69 781 else:
jpayne@69 782 self.showtraceback()
jpayne@69 783 else:
jpayne@69 784 raise
jpayne@69 785 except:
jpayne@69 786 if use_subprocess:
jpayne@69 787 print("IDLE internal error in runcode()",
jpayne@69 788 file=self.tkconsole.stderr)
jpayne@69 789 self.showtraceback()
jpayne@69 790 self.tkconsole.endexecuting()
jpayne@69 791 else:
jpayne@69 792 if self.tkconsole.canceled:
jpayne@69 793 self.tkconsole.canceled = False
jpayne@69 794 print("KeyboardInterrupt", file=self.tkconsole.stderr)
jpayne@69 795 else:
jpayne@69 796 self.showtraceback()
jpayne@69 797 finally:
jpayne@69 798 if not use_subprocess:
jpayne@69 799 try:
jpayne@69 800 self.tkconsole.endexecuting()
jpayne@69 801 except AttributeError: # shell may have closed
jpayne@69 802 pass
jpayne@69 803
jpayne@69 804 def write(self, s):
jpayne@69 805 "Override base class method"
jpayne@69 806 return self.tkconsole.stderr.write(s)
jpayne@69 807
jpayne@69 808 def display_port_binding_error(self):
jpayne@69 809 tkMessageBox.showerror(
jpayne@69 810 "Port Binding Error",
jpayne@69 811 "IDLE can't bind to a TCP/IP port, which is necessary to "
jpayne@69 812 "communicate with its Python execution server. This might be "
jpayne@69 813 "because no networking is installed on this computer. "
jpayne@69 814 "Run IDLE with the -n command line switch to start without a "
jpayne@69 815 "subprocess and refer to Help/IDLE Help 'Running without a "
jpayne@69 816 "subprocess' for further details.",
jpayne@69 817 parent=self.tkconsole.text)
jpayne@69 818
jpayne@69 819 def display_no_subprocess_error(self):
jpayne@69 820 tkMessageBox.showerror(
jpayne@69 821 "Subprocess Connection Error",
jpayne@69 822 "IDLE's subprocess didn't make connection.\n"
jpayne@69 823 "See the 'Startup failure' section of the IDLE doc, online at\n"
jpayne@69 824 "https://docs.python.org/3/library/idle.html#startup-failure",
jpayne@69 825 parent=self.tkconsole.text)
jpayne@69 826
jpayne@69 827 def display_executing_dialog(self):
jpayne@69 828 tkMessageBox.showerror(
jpayne@69 829 "Already executing",
jpayne@69 830 "The Python Shell window is already executing a command; "
jpayne@69 831 "please wait until it is finished.",
jpayne@69 832 parent=self.tkconsole.text)
jpayne@69 833
jpayne@69 834
jpayne@69 835 class PyShell(OutputWindow):
jpayne@69 836
jpayne@69 837 shell_title = "Python " + python_version() + " Shell"
jpayne@69 838
jpayne@69 839 # Override classes
jpayne@69 840 ColorDelegator = ModifiedColorDelegator
jpayne@69 841 UndoDelegator = ModifiedUndoDelegator
jpayne@69 842
jpayne@69 843 # Override menus
jpayne@69 844 menu_specs = [
jpayne@69 845 ("file", "_File"),
jpayne@69 846 ("edit", "_Edit"),
jpayne@69 847 ("debug", "_Debug"),
jpayne@69 848 ("options", "_Options"),
jpayne@69 849 ("window", "_Window"),
jpayne@69 850 ("help", "_Help"),
jpayne@69 851 ]
jpayne@69 852
jpayne@69 853 # Extend right-click context menu
jpayne@69 854 rmenu_specs = OutputWindow.rmenu_specs + [
jpayne@69 855 ("Squeeze", "<<squeeze-current-text>>"),
jpayne@69 856 ]
jpayne@69 857
jpayne@69 858 allow_line_numbers = False
jpayne@69 859
jpayne@69 860 # New classes
jpayne@69 861 from idlelib.history import History
jpayne@69 862
jpayne@69 863 def __init__(self, flist=None):
jpayne@69 864 if use_subprocess:
jpayne@69 865 ms = self.menu_specs
jpayne@69 866 if ms[2][0] != "shell":
jpayne@69 867 ms.insert(2, ("shell", "She_ll"))
jpayne@69 868 self.interp = ModifiedInterpreter(self)
jpayne@69 869 if flist is None:
jpayne@69 870 root = Tk()
jpayne@69 871 fixwordbreaks(root)
jpayne@69 872 root.withdraw()
jpayne@69 873 flist = PyShellFileList(root)
jpayne@69 874
jpayne@69 875 OutputWindow.__init__(self, flist, None, None)
jpayne@69 876
jpayne@69 877 self.usetabs = True
jpayne@69 878 # indentwidth must be 8 when using tabs. See note in EditorWindow:
jpayne@69 879 self.indentwidth = 8
jpayne@69 880
jpayne@69 881 self.sys_ps1 = sys.ps1 if hasattr(sys, 'ps1') else '>>> '
jpayne@69 882 self.prompt_last_line = self.sys_ps1.split('\n')[-1]
jpayne@69 883 self.prompt = self.sys_ps1 # Changes when debug active
jpayne@69 884
jpayne@69 885 text = self.text
jpayne@69 886 text.configure(wrap="char")
jpayne@69 887 text.bind("<<newline-and-indent>>", self.enter_callback)
jpayne@69 888 text.bind("<<plain-newline-and-indent>>", self.linefeed_callback)
jpayne@69 889 text.bind("<<interrupt-execution>>", self.cancel_callback)
jpayne@69 890 text.bind("<<end-of-file>>", self.eof_callback)
jpayne@69 891 text.bind("<<open-stack-viewer>>", self.open_stack_viewer)
jpayne@69 892 text.bind("<<toggle-debugger>>", self.toggle_debugger)
jpayne@69 893 text.bind("<<toggle-jit-stack-viewer>>", self.toggle_jit_stack_viewer)
jpayne@69 894 if use_subprocess:
jpayne@69 895 text.bind("<<view-restart>>", self.view_restart_mark)
jpayne@69 896 text.bind("<<restart-shell>>", self.restart_shell)
jpayne@69 897 squeezer = self.Squeezer(self)
jpayne@69 898 text.bind("<<squeeze-current-text>>",
jpayne@69 899 squeezer.squeeze_current_text_event)
jpayne@69 900
jpayne@69 901 self.save_stdout = sys.stdout
jpayne@69 902 self.save_stderr = sys.stderr
jpayne@69 903 self.save_stdin = sys.stdin
jpayne@69 904 from idlelib import iomenu
jpayne@69 905 self.stdin = StdInputFile(self, "stdin",
jpayne@69 906 iomenu.encoding, iomenu.errors)
jpayne@69 907 self.stdout = StdOutputFile(self, "stdout",
jpayne@69 908 iomenu.encoding, iomenu.errors)
jpayne@69 909 self.stderr = StdOutputFile(self, "stderr",
jpayne@69 910 iomenu.encoding, "backslashreplace")
jpayne@69 911 self.console = StdOutputFile(self, "console",
jpayne@69 912 iomenu.encoding, iomenu.errors)
jpayne@69 913 if not use_subprocess:
jpayne@69 914 sys.stdout = self.stdout
jpayne@69 915 sys.stderr = self.stderr
jpayne@69 916 sys.stdin = self.stdin
jpayne@69 917 try:
jpayne@69 918 # page help() text to shell.
jpayne@69 919 import pydoc # import must be done here to capture i/o rebinding.
jpayne@69 920 # XXX KBK 27Dec07 use text viewer someday, but must work w/o subproc
jpayne@69 921 pydoc.pager = pydoc.plainpager
jpayne@69 922 except:
jpayne@69 923 sys.stderr = sys.__stderr__
jpayne@69 924 raise
jpayne@69 925 #
jpayne@69 926 self.history = self.History(self.text)
jpayne@69 927 #
jpayne@69 928 self.pollinterval = 50 # millisec
jpayne@69 929
jpayne@69 930 def get_standard_extension_names(self):
jpayne@69 931 return idleConf.GetExtensions(shell_only=True)
jpayne@69 932
jpayne@69 933 reading = False
jpayne@69 934 executing = False
jpayne@69 935 canceled = False
jpayne@69 936 endoffile = False
jpayne@69 937 closing = False
jpayne@69 938 _stop_readline_flag = False
jpayne@69 939
jpayne@69 940 def set_warning_stream(self, stream):
jpayne@69 941 global warning_stream
jpayne@69 942 warning_stream = stream
jpayne@69 943
jpayne@69 944 def get_warning_stream(self):
jpayne@69 945 return warning_stream
jpayne@69 946
jpayne@69 947 def toggle_debugger(self, event=None):
jpayne@69 948 if self.executing:
jpayne@69 949 tkMessageBox.showerror("Don't debug now",
jpayne@69 950 "You can only toggle the debugger when idle",
jpayne@69 951 parent=self.text)
jpayne@69 952 self.set_debugger_indicator()
jpayne@69 953 return "break"
jpayne@69 954 else:
jpayne@69 955 db = self.interp.getdebugger()
jpayne@69 956 if db:
jpayne@69 957 self.close_debugger()
jpayne@69 958 else:
jpayne@69 959 self.open_debugger()
jpayne@69 960
jpayne@69 961 def set_debugger_indicator(self):
jpayne@69 962 db = self.interp.getdebugger()
jpayne@69 963 self.setvar("<<toggle-debugger>>", not not db)
jpayne@69 964
jpayne@69 965 def toggle_jit_stack_viewer(self, event=None):
jpayne@69 966 pass # All we need is the variable
jpayne@69 967
jpayne@69 968 def close_debugger(self):
jpayne@69 969 db = self.interp.getdebugger()
jpayne@69 970 if db:
jpayne@69 971 self.interp.setdebugger(None)
jpayne@69 972 db.close()
jpayne@69 973 if self.interp.rpcclt:
jpayne@69 974 debugger_r.close_remote_debugger(self.interp.rpcclt)
jpayne@69 975 self.resetoutput()
jpayne@69 976 self.console.write("[DEBUG OFF]\n")
jpayne@69 977 self.prompt = self.sys_ps1
jpayne@69 978 self.showprompt()
jpayne@69 979 self.set_debugger_indicator()
jpayne@69 980
jpayne@69 981 def open_debugger(self):
jpayne@69 982 if self.interp.rpcclt:
jpayne@69 983 dbg_gui = debugger_r.start_remote_debugger(self.interp.rpcclt,
jpayne@69 984 self)
jpayne@69 985 else:
jpayne@69 986 dbg_gui = debugger.Debugger(self)
jpayne@69 987 self.interp.setdebugger(dbg_gui)
jpayne@69 988 dbg_gui.load_breakpoints()
jpayne@69 989 self.prompt = "[DEBUG ON]\n" + self.sys_ps1
jpayne@69 990 self.showprompt()
jpayne@69 991 self.set_debugger_indicator()
jpayne@69 992
jpayne@69 993 def beginexecuting(self):
jpayne@69 994 "Helper for ModifiedInterpreter"
jpayne@69 995 self.resetoutput()
jpayne@69 996 self.executing = 1
jpayne@69 997
jpayne@69 998 def endexecuting(self):
jpayne@69 999 "Helper for ModifiedInterpreter"
jpayne@69 1000 self.executing = 0
jpayne@69 1001 self.canceled = 0
jpayne@69 1002 self.showprompt()
jpayne@69 1003
jpayne@69 1004 def close(self):
jpayne@69 1005 "Extend EditorWindow.close()"
jpayne@69 1006 if self.executing:
jpayne@69 1007 response = tkMessageBox.askokcancel(
jpayne@69 1008 "Kill?",
jpayne@69 1009 "Your program is still running!\n Do you want to kill it?",
jpayne@69 1010 default="ok",
jpayne@69 1011 parent=self.text)
jpayne@69 1012 if response is False:
jpayne@69 1013 return "cancel"
jpayne@69 1014 self.stop_readline()
jpayne@69 1015 self.canceled = True
jpayne@69 1016 self.closing = True
jpayne@69 1017 return EditorWindow.close(self)
jpayne@69 1018
jpayne@69 1019 def _close(self):
jpayne@69 1020 "Extend EditorWindow._close(), shut down debugger and execution server"
jpayne@69 1021 self.close_debugger()
jpayne@69 1022 if use_subprocess:
jpayne@69 1023 self.interp.kill_subprocess()
jpayne@69 1024 # Restore std streams
jpayne@69 1025 sys.stdout = self.save_stdout
jpayne@69 1026 sys.stderr = self.save_stderr
jpayne@69 1027 sys.stdin = self.save_stdin
jpayne@69 1028 # Break cycles
jpayne@69 1029 self.interp = None
jpayne@69 1030 self.console = None
jpayne@69 1031 self.flist.pyshell = None
jpayne@69 1032 self.history = None
jpayne@69 1033 EditorWindow._close(self)
jpayne@69 1034
jpayne@69 1035 def ispythonsource(self, filename):
jpayne@69 1036 "Override EditorWindow method: never remove the colorizer"
jpayne@69 1037 return True
jpayne@69 1038
jpayne@69 1039 def short_title(self):
jpayne@69 1040 return self.shell_title
jpayne@69 1041
jpayne@69 1042 COPYRIGHT = \
jpayne@69 1043 'Type "help", "copyright", "credits" or "license()" for more information.'
jpayne@69 1044
jpayne@69 1045 def begin(self):
jpayne@69 1046 self.text.mark_set("iomark", "insert")
jpayne@69 1047 self.resetoutput()
jpayne@69 1048 if use_subprocess:
jpayne@69 1049 nosub = ''
jpayne@69 1050 client = self.interp.start_subprocess()
jpayne@69 1051 if not client:
jpayne@69 1052 self.close()
jpayne@69 1053 return False
jpayne@69 1054 else:
jpayne@69 1055 nosub = ("==== No Subprocess ====\n\n" +
jpayne@69 1056 "WARNING: Running IDLE without a Subprocess is deprecated\n" +
jpayne@69 1057 "and will be removed in a later version. See Help/IDLE Help\n" +
jpayne@69 1058 "for details.\n\n")
jpayne@69 1059 sys.displayhook = rpc.displayhook
jpayne@69 1060
jpayne@69 1061 self.write("Python %s on %s\n%s\n%s" %
jpayne@69 1062 (sys.version, sys.platform, self.COPYRIGHT, nosub))
jpayne@69 1063 self.text.focus_force()
jpayne@69 1064 self.showprompt()
jpayne@69 1065 import tkinter
jpayne@69 1066 tkinter._default_root = None # 03Jan04 KBK What's this?
jpayne@69 1067 return True
jpayne@69 1068
jpayne@69 1069 def stop_readline(self):
jpayne@69 1070 if not self.reading: # no nested mainloop to exit.
jpayne@69 1071 return
jpayne@69 1072 self._stop_readline_flag = True
jpayne@69 1073 self.top.quit()
jpayne@69 1074
jpayne@69 1075 def readline(self):
jpayne@69 1076 save = self.reading
jpayne@69 1077 try:
jpayne@69 1078 self.reading = 1
jpayne@69 1079 self.top.mainloop() # nested mainloop()
jpayne@69 1080 finally:
jpayne@69 1081 self.reading = save
jpayne@69 1082 if self._stop_readline_flag:
jpayne@69 1083 self._stop_readline_flag = False
jpayne@69 1084 return ""
jpayne@69 1085 line = self.text.get("iomark", "end-1c")
jpayne@69 1086 if len(line) == 0: # may be EOF if we quit our mainloop with Ctrl-C
jpayne@69 1087 line = "\n"
jpayne@69 1088 self.resetoutput()
jpayne@69 1089 if self.canceled:
jpayne@69 1090 self.canceled = 0
jpayne@69 1091 if not use_subprocess:
jpayne@69 1092 raise KeyboardInterrupt
jpayne@69 1093 if self.endoffile:
jpayne@69 1094 self.endoffile = 0
jpayne@69 1095 line = ""
jpayne@69 1096 return line
jpayne@69 1097
jpayne@69 1098 def isatty(self):
jpayne@69 1099 return True
jpayne@69 1100
jpayne@69 1101 def cancel_callback(self, event=None):
jpayne@69 1102 try:
jpayne@69 1103 if self.text.compare("sel.first", "!=", "sel.last"):
jpayne@69 1104 return # Active selection -- always use default binding
jpayne@69 1105 except:
jpayne@69 1106 pass
jpayne@69 1107 if not (self.executing or self.reading):
jpayne@69 1108 self.resetoutput()
jpayne@69 1109 self.interp.write("KeyboardInterrupt\n")
jpayne@69 1110 self.showprompt()
jpayne@69 1111 return "break"
jpayne@69 1112 self.endoffile = 0
jpayne@69 1113 self.canceled = 1
jpayne@69 1114 if (self.executing and self.interp.rpcclt):
jpayne@69 1115 if self.interp.getdebugger():
jpayne@69 1116 self.interp.restart_subprocess()
jpayne@69 1117 else:
jpayne@69 1118 self.interp.interrupt_subprocess()
jpayne@69 1119 if self.reading:
jpayne@69 1120 self.top.quit() # exit the nested mainloop() in readline()
jpayne@69 1121 return "break"
jpayne@69 1122
jpayne@69 1123 def eof_callback(self, event):
jpayne@69 1124 if self.executing and not self.reading:
jpayne@69 1125 return # Let the default binding (delete next char) take over
jpayne@69 1126 if not (self.text.compare("iomark", "==", "insert") and
jpayne@69 1127 self.text.compare("insert", "==", "end-1c")):
jpayne@69 1128 return # Let the default binding (delete next char) take over
jpayne@69 1129 if not self.executing:
jpayne@69 1130 self.resetoutput()
jpayne@69 1131 self.close()
jpayne@69 1132 else:
jpayne@69 1133 self.canceled = 0
jpayne@69 1134 self.endoffile = 1
jpayne@69 1135 self.top.quit()
jpayne@69 1136 return "break"
jpayne@69 1137
jpayne@69 1138 def linefeed_callback(self, event):
jpayne@69 1139 # Insert a linefeed without entering anything (still autoindented)
jpayne@69 1140 if self.reading:
jpayne@69 1141 self.text.insert("insert", "\n")
jpayne@69 1142 self.text.see("insert")
jpayne@69 1143 else:
jpayne@69 1144 self.newline_and_indent_event(event)
jpayne@69 1145 return "break"
jpayne@69 1146
jpayne@69 1147 def enter_callback(self, event):
jpayne@69 1148 if self.executing and not self.reading:
jpayne@69 1149 return # Let the default binding (insert '\n') take over
jpayne@69 1150 # If some text is selected, recall the selection
jpayne@69 1151 # (but only if this before the I/O mark)
jpayne@69 1152 try:
jpayne@69 1153 sel = self.text.get("sel.first", "sel.last")
jpayne@69 1154 if sel:
jpayne@69 1155 if self.text.compare("sel.last", "<=", "iomark"):
jpayne@69 1156 self.recall(sel, event)
jpayne@69 1157 return "break"
jpayne@69 1158 except:
jpayne@69 1159 pass
jpayne@69 1160 # If we're strictly before the line containing iomark, recall
jpayne@69 1161 # the current line, less a leading prompt, less leading or
jpayne@69 1162 # trailing whitespace
jpayne@69 1163 if self.text.compare("insert", "<", "iomark linestart"):
jpayne@69 1164 # Check if there's a relevant stdin range -- if so, use it
jpayne@69 1165 prev = self.text.tag_prevrange("stdin", "insert")
jpayne@69 1166 if prev and self.text.compare("insert", "<", prev[1]):
jpayne@69 1167 self.recall(self.text.get(prev[0], prev[1]), event)
jpayne@69 1168 return "break"
jpayne@69 1169 next = self.text.tag_nextrange("stdin", "insert")
jpayne@69 1170 if next and self.text.compare("insert lineend", ">=", next[0]):
jpayne@69 1171 self.recall(self.text.get(next[0], next[1]), event)
jpayne@69 1172 return "break"
jpayne@69 1173 # No stdin mark -- just get the current line, less any prompt
jpayne@69 1174 indices = self.text.tag_nextrange("console", "insert linestart")
jpayne@69 1175 if indices and \
jpayne@69 1176 self.text.compare(indices[0], "<=", "insert linestart"):
jpayne@69 1177 self.recall(self.text.get(indices[1], "insert lineend"), event)
jpayne@69 1178 else:
jpayne@69 1179 self.recall(self.text.get("insert linestart", "insert lineend"), event)
jpayne@69 1180 return "break"
jpayne@69 1181 # If we're between the beginning of the line and the iomark, i.e.
jpayne@69 1182 # in the prompt area, move to the end of the prompt
jpayne@69 1183 if self.text.compare("insert", "<", "iomark"):
jpayne@69 1184 self.text.mark_set("insert", "iomark")
jpayne@69 1185 # If we're in the current input and there's only whitespace
jpayne@69 1186 # beyond the cursor, erase that whitespace first
jpayne@69 1187 s = self.text.get("insert", "end-1c")
jpayne@69 1188 if s and not s.strip():
jpayne@69 1189 self.text.delete("insert", "end-1c")
jpayne@69 1190 # If we're in the current input before its last line,
jpayne@69 1191 # insert a newline right at the insert point
jpayne@69 1192 if self.text.compare("insert", "<", "end-1c linestart"):
jpayne@69 1193 self.newline_and_indent_event(event)
jpayne@69 1194 return "break"
jpayne@69 1195 # We're in the last line; append a newline and submit it
jpayne@69 1196 self.text.mark_set("insert", "end-1c")
jpayne@69 1197 if self.reading:
jpayne@69 1198 self.text.insert("insert", "\n")
jpayne@69 1199 self.text.see("insert")
jpayne@69 1200 else:
jpayne@69 1201 self.newline_and_indent_event(event)
jpayne@69 1202 self.text.tag_add("stdin", "iomark", "end-1c")
jpayne@69 1203 self.text.update_idletasks()
jpayne@69 1204 if self.reading:
jpayne@69 1205 self.top.quit() # Break out of recursive mainloop()
jpayne@69 1206 else:
jpayne@69 1207 self.runit()
jpayne@69 1208 return "break"
jpayne@69 1209
jpayne@69 1210 def recall(self, s, event):
jpayne@69 1211 # remove leading and trailing empty or whitespace lines
jpayne@69 1212 s = re.sub(r'^\s*\n', '' , s)
jpayne@69 1213 s = re.sub(r'\n\s*$', '', s)
jpayne@69 1214 lines = s.split('\n')
jpayne@69 1215 self.text.undo_block_start()
jpayne@69 1216 try:
jpayne@69 1217 self.text.tag_remove("sel", "1.0", "end")
jpayne@69 1218 self.text.mark_set("insert", "end-1c")
jpayne@69 1219 prefix = self.text.get("insert linestart", "insert")
jpayne@69 1220 if prefix.rstrip().endswith(':'):
jpayne@69 1221 self.newline_and_indent_event(event)
jpayne@69 1222 prefix = self.text.get("insert linestart", "insert")
jpayne@69 1223 self.text.insert("insert", lines[0].strip())
jpayne@69 1224 if len(lines) > 1:
jpayne@69 1225 orig_base_indent = re.search(r'^([ \t]*)', lines[0]).group(0)
jpayne@69 1226 new_base_indent = re.search(r'^([ \t]*)', prefix).group(0)
jpayne@69 1227 for line in lines[1:]:
jpayne@69 1228 if line.startswith(orig_base_indent):
jpayne@69 1229 # replace orig base indentation with new indentation
jpayne@69 1230 line = new_base_indent + line[len(orig_base_indent):]
jpayne@69 1231 self.text.insert('insert', '\n'+line.rstrip())
jpayne@69 1232 finally:
jpayne@69 1233 self.text.see("insert")
jpayne@69 1234 self.text.undo_block_stop()
jpayne@69 1235
jpayne@69 1236 def runit(self):
jpayne@69 1237 line = self.text.get("iomark", "end-1c")
jpayne@69 1238 # Strip off last newline and surrounding whitespace.
jpayne@69 1239 # (To allow you to hit return twice to end a statement.)
jpayne@69 1240 i = len(line)
jpayne@69 1241 while i > 0 and line[i-1] in " \t":
jpayne@69 1242 i = i-1
jpayne@69 1243 if i > 0 and line[i-1] == "\n":
jpayne@69 1244 i = i-1
jpayne@69 1245 while i > 0 and line[i-1] in " \t":
jpayne@69 1246 i = i-1
jpayne@69 1247 line = line[:i]
jpayne@69 1248 self.interp.runsource(line)
jpayne@69 1249
jpayne@69 1250 def open_stack_viewer(self, event=None):
jpayne@69 1251 if self.interp.rpcclt:
jpayne@69 1252 return self.interp.remote_stack_viewer()
jpayne@69 1253 try:
jpayne@69 1254 sys.last_traceback
jpayne@69 1255 except:
jpayne@69 1256 tkMessageBox.showerror("No stack trace",
jpayne@69 1257 "There is no stack trace yet.\n"
jpayne@69 1258 "(sys.last_traceback is not defined)",
jpayne@69 1259 parent=self.text)
jpayne@69 1260 return
jpayne@69 1261 from idlelib.stackviewer import StackBrowser
jpayne@69 1262 StackBrowser(self.root, self.flist)
jpayne@69 1263
jpayne@69 1264 def view_restart_mark(self, event=None):
jpayne@69 1265 self.text.see("iomark")
jpayne@69 1266 self.text.see("restart")
jpayne@69 1267
jpayne@69 1268 def restart_shell(self, event=None):
jpayne@69 1269 "Callback for Run/Restart Shell Cntl-F6"
jpayne@69 1270 self.interp.restart_subprocess(with_cwd=True)
jpayne@69 1271
jpayne@69 1272 def showprompt(self):
jpayne@69 1273 self.resetoutput()
jpayne@69 1274 self.console.write(self.prompt)
jpayne@69 1275 self.text.mark_set("insert", "end-1c")
jpayne@69 1276 self.set_line_and_column()
jpayne@69 1277 self.io.reset_undo()
jpayne@69 1278
jpayne@69 1279 def show_warning(self, msg):
jpayne@69 1280 width = self.interp.tkconsole.width
jpayne@69 1281 wrapper = TextWrapper(width=width, tabsize=8, expand_tabs=True)
jpayne@69 1282 wrapped_msg = '\n'.join(wrapper.wrap(msg))
jpayne@69 1283 if not wrapped_msg.endswith('\n'):
jpayne@69 1284 wrapped_msg += '\n'
jpayne@69 1285 self.per.bottom.insert("iomark linestart", wrapped_msg, "stderr")
jpayne@69 1286
jpayne@69 1287 def resetoutput(self):
jpayne@69 1288 source = self.text.get("iomark", "end-1c")
jpayne@69 1289 if self.history:
jpayne@69 1290 self.history.store(source)
jpayne@69 1291 if self.text.get("end-2c") != "\n":
jpayne@69 1292 self.text.insert("end-1c", "\n")
jpayne@69 1293 self.text.mark_set("iomark", "end-1c")
jpayne@69 1294 self.set_line_and_column()
jpayne@69 1295
jpayne@69 1296 def write(self, s, tags=()):
jpayne@69 1297 try:
jpayne@69 1298 self.text.mark_gravity("iomark", "right")
jpayne@69 1299 count = OutputWindow.write(self, s, tags, "iomark")
jpayne@69 1300 self.text.mark_gravity("iomark", "left")
jpayne@69 1301 except:
jpayne@69 1302 raise ###pass # ### 11Aug07 KBK if we are expecting exceptions
jpayne@69 1303 # let's find out what they are and be specific.
jpayne@69 1304 if self.canceled:
jpayne@69 1305 self.canceled = 0
jpayne@69 1306 if not use_subprocess:
jpayne@69 1307 raise KeyboardInterrupt
jpayne@69 1308 return count
jpayne@69 1309
jpayne@69 1310 def rmenu_check_cut(self):
jpayne@69 1311 try:
jpayne@69 1312 if self.text.compare('sel.first', '<', 'iomark'):
jpayne@69 1313 return 'disabled'
jpayne@69 1314 except TclError: # no selection, so the index 'sel.first' doesn't exist
jpayne@69 1315 return 'disabled'
jpayne@69 1316 return super().rmenu_check_cut()
jpayne@69 1317
jpayne@69 1318 def rmenu_check_paste(self):
jpayne@69 1319 if self.text.compare('insert','<','iomark'):
jpayne@69 1320 return 'disabled'
jpayne@69 1321 return super().rmenu_check_paste()
jpayne@69 1322
jpayne@69 1323
jpayne@69 1324 def fix_x11_paste(root):
jpayne@69 1325 "Make paste replace selection on x11. See issue #5124."
jpayne@69 1326 if root._windowingsystem == 'x11':
jpayne@69 1327 for cls in 'Text', 'Entry', 'Spinbox':
jpayne@69 1328 root.bind_class(
jpayne@69 1329 cls,
jpayne@69 1330 '<<Paste>>',
jpayne@69 1331 'catch {%W delete sel.first sel.last}\n' +
jpayne@69 1332 root.bind_class(cls, '<<Paste>>'))
jpayne@69 1333
jpayne@69 1334
jpayne@69 1335 usage_msg = """\
jpayne@69 1336
jpayne@69 1337 USAGE: idle [-deins] [-t title] [file]*
jpayne@69 1338 idle [-dns] [-t title] (-c cmd | -r file) [arg]*
jpayne@69 1339 idle [-dns] [-t title] - [arg]*
jpayne@69 1340
jpayne@69 1341 -h print this help message and exit
jpayne@69 1342 -n run IDLE without a subprocess (DEPRECATED,
jpayne@69 1343 see Help/IDLE Help for details)
jpayne@69 1344
jpayne@69 1345 The following options will override the IDLE 'settings' configuration:
jpayne@69 1346
jpayne@69 1347 -e open an edit window
jpayne@69 1348 -i open a shell window
jpayne@69 1349
jpayne@69 1350 The following options imply -i and will open a shell:
jpayne@69 1351
jpayne@69 1352 -c cmd run the command in a shell, or
jpayne@69 1353 -r file run script from file
jpayne@69 1354
jpayne@69 1355 -d enable the debugger
jpayne@69 1356 -s run $IDLESTARTUP or $PYTHONSTARTUP before anything else
jpayne@69 1357 -t title set title of shell window
jpayne@69 1358
jpayne@69 1359 A default edit window will be bypassed when -c, -r, or - are used.
jpayne@69 1360
jpayne@69 1361 [arg]* are passed to the command (-c) or script (-r) in sys.argv[1:].
jpayne@69 1362
jpayne@69 1363 Examples:
jpayne@69 1364
jpayne@69 1365 idle
jpayne@69 1366 Open an edit window or shell depending on IDLE's configuration.
jpayne@69 1367
jpayne@69 1368 idle foo.py foobar.py
jpayne@69 1369 Edit the files, also open a shell if configured to start with shell.
jpayne@69 1370
jpayne@69 1371 idle -est "Baz" foo.py
jpayne@69 1372 Run $IDLESTARTUP or $PYTHONSTARTUP, edit foo.py, and open a shell
jpayne@69 1373 window with the title "Baz".
jpayne@69 1374
jpayne@69 1375 idle -c "import sys; print(sys.argv)" "foo"
jpayne@69 1376 Open a shell window and run the command, passing "-c" in sys.argv[0]
jpayne@69 1377 and "foo" in sys.argv[1].
jpayne@69 1378
jpayne@69 1379 idle -d -s -r foo.py "Hello World"
jpayne@69 1380 Open a shell window, run a startup script, enable the debugger, and
jpayne@69 1381 run foo.py, passing "foo.py" in sys.argv[0] and "Hello World" in
jpayne@69 1382 sys.argv[1].
jpayne@69 1383
jpayne@69 1384 echo "import sys; print(sys.argv)" | idle - "foobar"
jpayne@69 1385 Open a shell window, run the script piped in, passing '' in sys.argv[0]
jpayne@69 1386 and "foobar" in sys.argv[1].
jpayne@69 1387 """
jpayne@69 1388
jpayne@69 1389 def main():
jpayne@69 1390 import getopt
jpayne@69 1391 from platform import system
jpayne@69 1392 from idlelib import testing # bool value
jpayne@69 1393 from idlelib import macosx
jpayne@69 1394
jpayne@69 1395 global flist, root, use_subprocess
jpayne@69 1396
jpayne@69 1397 capture_warnings(True)
jpayne@69 1398 use_subprocess = True
jpayne@69 1399 enable_shell = False
jpayne@69 1400 enable_edit = False
jpayne@69 1401 debug = False
jpayne@69 1402 cmd = None
jpayne@69 1403 script = None
jpayne@69 1404 startup = False
jpayne@69 1405 try:
jpayne@69 1406 opts, args = getopt.getopt(sys.argv[1:], "c:deihnr:st:")
jpayne@69 1407 except getopt.error as msg:
jpayne@69 1408 print("Error: %s\n%s" % (msg, usage_msg), file=sys.stderr)
jpayne@69 1409 sys.exit(2)
jpayne@69 1410 for o, a in opts:
jpayne@69 1411 if o == '-c':
jpayne@69 1412 cmd = a
jpayne@69 1413 enable_shell = True
jpayne@69 1414 if o == '-d':
jpayne@69 1415 debug = True
jpayne@69 1416 enable_shell = True
jpayne@69 1417 if o == '-e':
jpayne@69 1418 enable_edit = True
jpayne@69 1419 if o == '-h':
jpayne@69 1420 sys.stdout.write(usage_msg)
jpayne@69 1421 sys.exit()
jpayne@69 1422 if o == '-i':
jpayne@69 1423 enable_shell = True
jpayne@69 1424 if o == '-n':
jpayne@69 1425 print(" Warning: running IDLE without a subprocess is deprecated.",
jpayne@69 1426 file=sys.stderr)
jpayne@69 1427 use_subprocess = False
jpayne@69 1428 if o == '-r':
jpayne@69 1429 script = a
jpayne@69 1430 if os.path.isfile(script):
jpayne@69 1431 pass
jpayne@69 1432 else:
jpayne@69 1433 print("No script file: ", script)
jpayne@69 1434 sys.exit()
jpayne@69 1435 enable_shell = True
jpayne@69 1436 if o == '-s':
jpayne@69 1437 startup = True
jpayne@69 1438 enable_shell = True
jpayne@69 1439 if o == '-t':
jpayne@69 1440 PyShell.shell_title = a
jpayne@69 1441 enable_shell = True
jpayne@69 1442 if args and args[0] == '-':
jpayne@69 1443 cmd = sys.stdin.read()
jpayne@69 1444 enable_shell = True
jpayne@69 1445 # process sys.argv and sys.path:
jpayne@69 1446 for i in range(len(sys.path)):
jpayne@69 1447 sys.path[i] = os.path.abspath(sys.path[i])
jpayne@69 1448 if args and args[0] == '-':
jpayne@69 1449 sys.argv = [''] + args[1:]
jpayne@69 1450 elif cmd:
jpayne@69 1451 sys.argv = ['-c'] + args
jpayne@69 1452 elif script:
jpayne@69 1453 sys.argv = [script] + args
jpayne@69 1454 elif args:
jpayne@69 1455 enable_edit = True
jpayne@69 1456 pathx = []
jpayne@69 1457 for filename in args:
jpayne@69 1458 pathx.append(os.path.dirname(filename))
jpayne@69 1459 for dir in pathx:
jpayne@69 1460 dir = os.path.abspath(dir)
jpayne@69 1461 if not dir in sys.path:
jpayne@69 1462 sys.path.insert(0, dir)
jpayne@69 1463 else:
jpayne@69 1464 dir = os.getcwd()
jpayne@69 1465 if dir not in sys.path:
jpayne@69 1466 sys.path.insert(0, dir)
jpayne@69 1467 # check the IDLE settings configuration (but command line overrides)
jpayne@69 1468 edit_start = idleConf.GetOption('main', 'General',
jpayne@69 1469 'editor-on-startup', type='bool')
jpayne@69 1470 enable_edit = enable_edit or edit_start
jpayne@69 1471 enable_shell = enable_shell or not enable_edit
jpayne@69 1472
jpayne@69 1473 # Setup root. Don't break user code run in IDLE process.
jpayne@69 1474 # Don't change environment when testing.
jpayne@69 1475 if use_subprocess and not testing:
jpayne@69 1476 NoDefaultRoot()
jpayne@69 1477 root = Tk(className="Idle")
jpayne@69 1478 root.withdraw()
jpayne@69 1479 from idlelib.run import fix_scaling
jpayne@69 1480 fix_scaling(root)
jpayne@69 1481
jpayne@69 1482 # set application icon
jpayne@69 1483 icondir = os.path.join(os.path.dirname(__file__), 'Icons')
jpayne@69 1484 if system() == 'Windows':
jpayne@69 1485 iconfile = os.path.join(icondir, 'idle.ico')
jpayne@69 1486 root.wm_iconbitmap(default=iconfile)
jpayne@69 1487 elif not macosx.isAquaTk():
jpayne@69 1488 ext = '.png' if TkVersion >= 8.6 else '.gif'
jpayne@69 1489 iconfiles = [os.path.join(icondir, 'idle_%d%s' % (size, ext))
jpayne@69 1490 for size in (16, 32, 48)]
jpayne@69 1491 icons = [PhotoImage(master=root, file=iconfile)
jpayne@69 1492 for iconfile in iconfiles]
jpayne@69 1493 root.wm_iconphoto(True, *icons)
jpayne@69 1494
jpayne@69 1495 # start editor and/or shell windows:
jpayne@69 1496 fixwordbreaks(root)
jpayne@69 1497 fix_x11_paste(root)
jpayne@69 1498 flist = PyShellFileList(root)
jpayne@69 1499 macosx.setupApp(root, flist)
jpayne@69 1500
jpayne@69 1501 if enable_edit:
jpayne@69 1502 if not (cmd or script):
jpayne@69 1503 for filename in args[:]:
jpayne@69 1504 if flist.open(filename) is None:
jpayne@69 1505 # filename is a directory actually, disconsider it
jpayne@69 1506 args.remove(filename)
jpayne@69 1507 if not args:
jpayne@69 1508 flist.new()
jpayne@69 1509
jpayne@69 1510 if enable_shell:
jpayne@69 1511 shell = flist.open_shell()
jpayne@69 1512 if not shell:
jpayne@69 1513 return # couldn't open shell
jpayne@69 1514 if macosx.isAquaTk() and flist.dict:
jpayne@69 1515 # On OSX: when the user has double-clicked on a file that causes
jpayne@69 1516 # IDLE to be launched the shell window will open just in front of
jpayne@69 1517 # the file she wants to see. Lower the interpreter window when
jpayne@69 1518 # there are open files.
jpayne@69 1519 shell.top.lower()
jpayne@69 1520 else:
jpayne@69 1521 shell = flist.pyshell
jpayne@69 1522
jpayne@69 1523 # Handle remaining options. If any of these are set, enable_shell
jpayne@69 1524 # was set also, so shell must be true to reach here.
jpayne@69 1525 if debug:
jpayne@69 1526 shell.open_debugger()
jpayne@69 1527 if startup:
jpayne@69 1528 filename = os.environ.get("IDLESTARTUP") or \
jpayne@69 1529 os.environ.get("PYTHONSTARTUP")
jpayne@69 1530 if filename and os.path.isfile(filename):
jpayne@69 1531 shell.interp.execfile(filename)
jpayne@69 1532 if cmd or script:
jpayne@69 1533 shell.interp.runcommand("""if 1:
jpayne@69 1534 import sys as _sys
jpayne@69 1535 _sys.argv = %r
jpayne@69 1536 del _sys
jpayne@69 1537 \n""" % (sys.argv,))
jpayne@69 1538 if cmd:
jpayne@69 1539 shell.interp.execsource(cmd)
jpayne@69 1540 elif script:
jpayne@69 1541 shell.interp.prepend_syspath(script)
jpayne@69 1542 shell.interp.execfile(script)
jpayne@69 1543 elif shell:
jpayne@69 1544 # If there is a shell window and no cmd or script in progress,
jpayne@69 1545 # check for problematic issues and print warning message(s) in
jpayne@69 1546 # the IDLE shell window; this is less intrusive than always
jpayne@69 1547 # opening a separate window.
jpayne@69 1548
jpayne@69 1549 # Warn if using a problematic OS X Tk version.
jpayne@69 1550 tkversionwarning = macosx.tkVersionWarning(root)
jpayne@69 1551 if tkversionwarning:
jpayne@69 1552 shell.show_warning(tkversionwarning)
jpayne@69 1553
jpayne@69 1554 # Warn if the "Prefer tabs when opening documents" system
jpayne@69 1555 # preference is set to "Always".
jpayne@69 1556 prefer_tabs_preference_warning = macosx.preferTabsPreferenceWarning()
jpayne@69 1557 if prefer_tabs_preference_warning:
jpayne@69 1558 shell.show_warning(prefer_tabs_preference_warning)
jpayne@69 1559
jpayne@69 1560 while flist.inversedict: # keep IDLE running while files are open.
jpayne@69 1561 root.mainloop()
jpayne@69 1562 root.destroy()
jpayne@69 1563 capture_warnings(False)
jpayne@69 1564
jpayne@69 1565 if __name__ == "__main__":
jpayne@69 1566 main()
jpayne@69 1567
jpayne@69 1568 capture_warnings(False) # Make sure turned off; see issue 18081