ยปCore Development>Code coverage>Lib/idlelib/pyshell.py

Python code coverage for Lib/idlelib/pyshell.py

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