pyshell.py 56 KB

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