pyshell.py 61 KB

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