pyshell.py 56 KB

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