run.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. """ idlelib.run
  2. Simplified, pyshell.ModifiedInterpreter spawns a subprocess with
  3. f'''{sys.executable} -c "__import__('idlelib.run').run.main()"'''
  4. '.run' is needed because __import__ returns idlelib, not idlelib.run.
  5. """
  6. import contextlib
  7. import functools
  8. import io
  9. import linecache
  10. import queue
  11. import sys
  12. import textwrap
  13. import time
  14. import traceback
  15. import _thread as thread
  16. import threading
  17. import warnings
  18. import idlelib # testing
  19. from idlelib import autocomplete # AutoComplete, fetch_encodings
  20. from idlelib import calltip # Calltip
  21. from idlelib import debugger_r # start_debugger
  22. from idlelib import debugobj_r # remote_object_tree_item
  23. from idlelib import iomenu # encoding
  24. from idlelib import rpc # multiple objects
  25. from idlelib import stackviewer # StackTreeItem
  26. import __main__
  27. import tkinter # Use tcl and, if startup fails, messagebox.
  28. if not hasattr(sys.modules['idlelib.run'], 'firstrun'):
  29. # Undo modifications of tkinter by idlelib imports; see bpo-25507.
  30. for mod in ('simpledialog', 'messagebox', 'font',
  31. 'dialog', 'filedialog', 'commondialog',
  32. 'ttk'):
  33. delattr(tkinter, mod)
  34. del sys.modules['tkinter.' + mod]
  35. # Avoid AttributeError if run again; see bpo-37038.
  36. sys.modules['idlelib.run'].firstrun = False
  37. LOCALHOST = '127.0.0.1'
  38. try:
  39. eof = 'Ctrl-D (end-of-file)'
  40. exit.eof = eof
  41. quit.eof = eof
  42. except NameError: # In case subprocess started with -S (maybe in future).
  43. pass
  44. def idle_formatwarning(message, category, filename, lineno, line=None):
  45. """Format warnings the IDLE way."""
  46. s = "\nWarning (from warnings module):\n"
  47. s += f' File \"{filename}\", line {lineno}\n'
  48. if line is None:
  49. line = linecache.getline(filename, lineno)
  50. line = line.strip()
  51. if line:
  52. s += " %s\n" % line
  53. s += f"{category.__name__}: {message}\n"
  54. return s
  55. def idle_showwarning_subproc(
  56. message, category, filename, lineno, file=None, line=None):
  57. """Show Idle-format warning after replacing warnings.showwarning.
  58. The only difference is the formatter called.
  59. """
  60. if file is None:
  61. file = sys.stderr
  62. try:
  63. file.write(idle_formatwarning(
  64. message, category, filename, lineno, line))
  65. except OSError:
  66. pass # the file (probably stderr) is invalid - this warning gets lost.
  67. _warnings_showwarning = None
  68. def capture_warnings(capture):
  69. "Replace warning.showwarning with idle_showwarning_subproc, or reverse."
  70. global _warnings_showwarning
  71. if capture:
  72. if _warnings_showwarning is None:
  73. _warnings_showwarning = warnings.showwarning
  74. warnings.showwarning = idle_showwarning_subproc
  75. else:
  76. if _warnings_showwarning is not None:
  77. warnings.showwarning = _warnings_showwarning
  78. _warnings_showwarning = None
  79. capture_warnings(True)
  80. tcl = tkinter.Tcl()
  81. def handle_tk_events(tcl=tcl):
  82. """Process any tk events that are ready to be dispatched if tkinter
  83. has been imported, a tcl interpreter has been created and tk has been
  84. loaded."""
  85. tcl.eval("update")
  86. # Thread shared globals: Establish a queue between a subthread (which handles
  87. # the socket) and the main thread (which runs user code), plus global
  88. # completion, exit and interruptable (the main thread) flags:
  89. exit_now = False
  90. quitting = False
  91. interruptable = False
  92. def main(del_exitfunc=False):
  93. """Start the Python execution server in a subprocess
  94. In the Python subprocess, RPCServer is instantiated with handlerclass
  95. MyHandler, which inherits register/unregister methods from RPCHandler via
  96. the mix-in class SocketIO.
  97. When the RPCServer 'server' is instantiated, the TCPServer initialization
  98. creates an instance of run.MyHandler and calls its handle() method.
  99. handle() instantiates a run.Executive object, passing it a reference to the
  100. MyHandler object. That reference is saved as attribute rpchandler of the
  101. Executive instance. The Executive methods have access to the reference and
  102. can pass it on to entities that they command
  103. (e.g. debugger_r.Debugger.start_debugger()). The latter, in turn, can
  104. call MyHandler(SocketIO) register/unregister methods via the reference to
  105. register and unregister themselves.
  106. """
  107. global exit_now
  108. global quitting
  109. global no_exitfunc
  110. no_exitfunc = del_exitfunc
  111. #time.sleep(15) # test subprocess not responding
  112. try:
  113. assert(len(sys.argv) > 1)
  114. port = int(sys.argv[-1])
  115. except:
  116. print("IDLE Subprocess: no IP port passed in sys.argv.",
  117. file=sys.__stderr__)
  118. return
  119. capture_warnings(True)
  120. sys.argv[:] = [""]
  121. threading.Thread(target=manage_socket,
  122. name='SockThread',
  123. args=((LOCALHOST, port),),
  124. daemon=True,
  125. ).start()
  126. while True:
  127. try:
  128. if exit_now:
  129. try:
  130. exit()
  131. except KeyboardInterrupt:
  132. # exiting but got an extra KBI? Try again!
  133. continue
  134. try:
  135. request = rpc.request_queue.get(block=True, timeout=0.05)
  136. except queue.Empty:
  137. request = None
  138. # Issue 32207: calling handle_tk_events here adds spurious
  139. # queue.Empty traceback to event handling exceptions.
  140. if request:
  141. seq, (method, args, kwargs) = request
  142. ret = method(*args, **kwargs)
  143. rpc.response_queue.put((seq, ret))
  144. else:
  145. handle_tk_events()
  146. except KeyboardInterrupt:
  147. if quitting:
  148. exit_now = True
  149. continue
  150. except SystemExit:
  151. capture_warnings(False)
  152. raise
  153. except:
  154. type, value, tb = sys.exc_info()
  155. try:
  156. print_exception()
  157. rpc.response_queue.put((seq, None))
  158. except:
  159. # Link didn't work, print same exception to __stderr__
  160. traceback.print_exception(type, value, tb, file=sys.__stderr__)
  161. exit()
  162. else:
  163. continue
  164. def manage_socket(address):
  165. for i in range(3):
  166. time.sleep(i)
  167. try:
  168. server = MyRPCServer(address, MyHandler)
  169. break
  170. except OSError as err:
  171. print("IDLE Subprocess: OSError: " + err.args[1] +
  172. ", retrying....", file=sys.__stderr__)
  173. socket_error = err
  174. else:
  175. print("IDLE Subprocess: Connection to "
  176. "IDLE GUI failed, exiting.", file=sys.__stderr__)
  177. show_socket_error(socket_error, address)
  178. global exit_now
  179. exit_now = True
  180. return
  181. server.handle_request() # A single request only
  182. def show_socket_error(err, address):
  183. "Display socket error from manage_socket."
  184. import tkinter
  185. from tkinter.messagebox import showerror
  186. root = tkinter.Tk()
  187. fix_scaling(root)
  188. root.withdraw()
  189. showerror(
  190. "Subprocess Connection Error",
  191. f"IDLE's subprocess can't connect to {address[0]}:{address[1]}.\n"
  192. f"Fatal OSError #{err.errno}: {err.strerror}.\n"
  193. "See the 'Startup failure' section of the IDLE doc, online at\n"
  194. "https://docs.python.org/3/library/idle.html#startup-failure",
  195. parent=root)
  196. root.destroy()
  197. def get_message_lines(typ, exc, tb):
  198. "Return line composing the exception message."
  199. if typ in (AttributeError, NameError):
  200. # 3.10+ hints are not directly accessible from python (#44026).
  201. err = io.StringIO()
  202. with contextlib.redirect_stderr(err):
  203. sys.__excepthook__(typ, exc, tb)
  204. return [err.getvalue().split("\n")[-2] + "\n"]
  205. else:
  206. return traceback.format_exception_only(typ, exc)
  207. def print_exception():
  208. import linecache
  209. linecache.checkcache()
  210. flush_stdout()
  211. efile = sys.stderr
  212. typ, val, tb = excinfo = sys.exc_info()
  213. sys.last_type, sys.last_value, sys.last_traceback = excinfo
  214. sys.last_exc = val
  215. seen = set()
  216. def print_exc(typ, exc, tb):
  217. seen.add(id(exc))
  218. context = exc.__context__
  219. cause = exc.__cause__
  220. if cause is not None and id(cause) not in seen:
  221. print_exc(type(cause), cause, cause.__traceback__)
  222. print("\nThe above exception was the direct cause "
  223. "of the following exception:\n", file=efile)
  224. elif (context is not None and
  225. not exc.__suppress_context__ and
  226. id(context) not in seen):
  227. print_exc(type(context), context, context.__traceback__)
  228. print("\nDuring handling of the above exception, "
  229. "another exception occurred:\n", file=efile)
  230. if tb:
  231. tbe = traceback.extract_tb(tb)
  232. print('Traceback (most recent call last):', file=efile)
  233. exclude = ("run.py", "rpc.py", "threading.py", "queue.py",
  234. "debugger_r.py", "bdb.py")
  235. cleanup_traceback(tbe, exclude)
  236. traceback.print_list(tbe, file=efile)
  237. lines = get_message_lines(typ, exc, tb)
  238. for line in lines:
  239. print(line, end='', file=efile)
  240. print_exc(typ, val, tb)
  241. def cleanup_traceback(tb, exclude):
  242. "Remove excluded traces from beginning/end of tb; get cached lines"
  243. orig_tb = tb[:]
  244. while tb:
  245. for rpcfile in exclude:
  246. if tb[0][0].count(rpcfile):
  247. break # found an exclude, break for: and delete tb[0]
  248. else:
  249. break # no excludes, have left RPC code, break while:
  250. del tb[0]
  251. while tb:
  252. for rpcfile in exclude:
  253. if tb[-1][0].count(rpcfile):
  254. break
  255. else:
  256. break
  257. del tb[-1]
  258. if len(tb) == 0:
  259. # exception was in IDLE internals, don't prune!
  260. tb[:] = orig_tb[:]
  261. print("** IDLE Internal Exception: ", file=sys.stderr)
  262. rpchandler = rpc.objecttable['exec'].rpchandler
  263. for i in range(len(tb)):
  264. fn, ln, nm, line = tb[i]
  265. if nm == '?':
  266. nm = "-toplevel-"
  267. if not line and fn.startswith("<pyshell#"):
  268. line = rpchandler.remotecall('linecache', 'getline',
  269. (fn, ln), {})
  270. tb[i] = fn, ln, nm, line
  271. def flush_stdout():
  272. """XXX How to do this now?"""
  273. def exit():
  274. """Exit subprocess, possibly after first clearing exit functions.
  275. If config-main.cfg/.def 'General' 'delete-exitfunc' is True, then any
  276. functions registered with atexit will be removed before exiting.
  277. (VPython support)
  278. """
  279. if no_exitfunc:
  280. import atexit
  281. atexit._clear()
  282. capture_warnings(False)
  283. sys.exit(0)
  284. def fix_scaling(root):
  285. """Scale fonts on HiDPI displays."""
  286. import tkinter.font
  287. scaling = float(root.tk.call('tk', 'scaling'))
  288. if scaling > 1.4:
  289. for name in tkinter.font.names(root):
  290. font = tkinter.font.Font(root=root, name=name, exists=True)
  291. size = int(font['size'])
  292. if size < 0:
  293. font['size'] = round(-0.75*size)
  294. def fixdoc(fun, text):
  295. tem = (fun.__doc__ + '\n\n') if fun.__doc__ is not None else ''
  296. fun.__doc__ = tem + textwrap.fill(textwrap.dedent(text))
  297. RECURSIONLIMIT_DELTA = 30
  298. def install_recursionlimit_wrappers():
  299. """Install wrappers to always add 30 to the recursion limit."""
  300. # see: bpo-26806
  301. @functools.wraps(sys.setrecursionlimit)
  302. def setrecursionlimit(*args, **kwargs):
  303. # mimic the original sys.setrecursionlimit()'s input handling
  304. if kwargs:
  305. raise TypeError(
  306. "setrecursionlimit() takes no keyword arguments")
  307. try:
  308. limit, = args
  309. except ValueError:
  310. raise TypeError(f"setrecursionlimit() takes exactly one "
  311. f"argument ({len(args)} given)")
  312. if not limit > 0:
  313. raise ValueError(
  314. "recursion limit must be greater or equal than 1")
  315. return setrecursionlimit.__wrapped__(limit + RECURSIONLIMIT_DELTA)
  316. fixdoc(setrecursionlimit, f"""\
  317. This IDLE wrapper adds {RECURSIONLIMIT_DELTA} to prevent possible
  318. uninterruptible loops.""")
  319. @functools.wraps(sys.getrecursionlimit)
  320. def getrecursionlimit():
  321. return getrecursionlimit.__wrapped__() - RECURSIONLIMIT_DELTA
  322. fixdoc(getrecursionlimit, f"""\
  323. This IDLE wrapper subtracts {RECURSIONLIMIT_DELTA} to compensate
  324. for the {RECURSIONLIMIT_DELTA} IDLE adds when setting the limit.""")
  325. # add the delta to the default recursion limit, to compensate
  326. sys.setrecursionlimit(sys.getrecursionlimit() + RECURSIONLIMIT_DELTA)
  327. sys.setrecursionlimit = setrecursionlimit
  328. sys.getrecursionlimit = getrecursionlimit
  329. def uninstall_recursionlimit_wrappers():
  330. """Uninstall the recursion limit wrappers from the sys module.
  331. IDLE only uses this for tests. Users can import run and call
  332. this to remove the wrapping.
  333. """
  334. if (
  335. getattr(sys.setrecursionlimit, '__wrapped__', None) and
  336. getattr(sys.getrecursionlimit, '__wrapped__', None)
  337. ):
  338. sys.setrecursionlimit = sys.setrecursionlimit.__wrapped__
  339. sys.getrecursionlimit = sys.getrecursionlimit.__wrapped__
  340. sys.setrecursionlimit(sys.getrecursionlimit() - RECURSIONLIMIT_DELTA)
  341. class MyRPCServer(rpc.RPCServer):
  342. def handle_error(self, request, client_address):
  343. """Override RPCServer method for IDLE
  344. Interrupt the MainThread and exit server if link is dropped.
  345. """
  346. global quitting
  347. try:
  348. raise
  349. except SystemExit:
  350. raise
  351. except EOFError:
  352. global exit_now
  353. exit_now = True
  354. thread.interrupt_main()
  355. except:
  356. erf = sys.__stderr__
  357. print(textwrap.dedent(f"""
  358. {'-'*40}
  359. Unhandled exception in user code execution server!'
  360. Thread: {threading.current_thread().name}
  361. IDLE Client Address: {client_address}
  362. Request: {request!r}
  363. """), file=erf)
  364. traceback.print_exc(limit=-20, file=erf)
  365. print(textwrap.dedent(f"""
  366. *** Unrecoverable, server exiting!
  367. Users should never see this message; it is likely transient.
  368. If this recurs, report this with a copy of the message
  369. and an explanation of how to make it repeat.
  370. {'-'*40}"""), file=erf)
  371. quitting = True
  372. thread.interrupt_main()
  373. # Pseudofiles for shell-remote communication (also used in pyshell)
  374. class StdioFile(io.TextIOBase):
  375. def __init__(self, shell, tags, encoding='utf-8', errors='strict'):
  376. self.shell = shell
  377. self.tags = tags
  378. self._encoding = encoding
  379. self._errors = errors
  380. @property
  381. def encoding(self):
  382. return self._encoding
  383. @property
  384. def errors(self):
  385. return self._errors
  386. @property
  387. def name(self):
  388. return '<%s>' % self.tags
  389. def isatty(self):
  390. return True
  391. class StdOutputFile(StdioFile):
  392. def writable(self):
  393. return True
  394. def write(self, s):
  395. if self.closed:
  396. raise ValueError("write to closed file")
  397. s = str.encode(s, self.encoding, self.errors).decode(self.encoding, self.errors)
  398. return self.shell.write(s, self.tags)
  399. class StdInputFile(StdioFile):
  400. _line_buffer = ''
  401. def readable(self):
  402. return True
  403. def read(self, size=-1):
  404. if self.closed:
  405. raise ValueError("read from closed file")
  406. if size is None:
  407. size = -1
  408. elif not isinstance(size, int):
  409. raise TypeError('must be int, not ' + type(size).__name__)
  410. result = self._line_buffer
  411. self._line_buffer = ''
  412. if size < 0:
  413. while line := self.shell.readline():
  414. result += line
  415. else:
  416. while len(result) < size:
  417. line = self.shell.readline()
  418. if not line: break
  419. result += line
  420. self._line_buffer = result[size:]
  421. result = result[:size]
  422. return result
  423. def readline(self, size=-1):
  424. if self.closed:
  425. raise ValueError("read from closed file")
  426. if size is None:
  427. size = -1
  428. elif not isinstance(size, int):
  429. raise TypeError('must be int, not ' + type(size).__name__)
  430. line = self._line_buffer or self.shell.readline()
  431. if size < 0:
  432. size = len(line)
  433. eol = line.find('\n', 0, size)
  434. if eol >= 0:
  435. size = eol + 1
  436. self._line_buffer = line[size:]
  437. return line[:size]
  438. def close(self):
  439. self.shell.close()
  440. class MyHandler(rpc.RPCHandler):
  441. def handle(self):
  442. """Override base method"""
  443. executive = Executive(self)
  444. self.register("exec", executive)
  445. self.console = self.get_remote_proxy("console")
  446. sys.stdin = StdInputFile(self.console, "stdin",
  447. iomenu.encoding, iomenu.errors)
  448. sys.stdout = StdOutputFile(self.console, "stdout",
  449. iomenu.encoding, iomenu.errors)
  450. sys.stderr = StdOutputFile(self.console, "stderr",
  451. iomenu.encoding, "backslashreplace")
  452. sys.displayhook = rpc.displayhook
  453. # page help() text to shell.
  454. import pydoc # import must be done here to capture i/o binding
  455. pydoc.pager = pydoc.plainpager
  456. # Keep a reference to stdin so that it won't try to exit IDLE if
  457. # sys.stdin gets changed from within IDLE's shell. See issue17838.
  458. self._keep_stdin = sys.stdin
  459. install_recursionlimit_wrappers()
  460. self.interp = self.get_remote_proxy("interp")
  461. rpc.RPCHandler.getresponse(self, myseq=None, wait=0.05)
  462. def exithook(self):
  463. "override SocketIO method - wait for MainThread to shut us down"
  464. time.sleep(10)
  465. def EOFhook(self):
  466. "Override SocketIO method - terminate wait on callback and exit thread"
  467. global quitting
  468. quitting = True
  469. thread.interrupt_main()
  470. def decode_interrupthook(self):
  471. "interrupt awakened thread"
  472. global quitting
  473. quitting = True
  474. thread.interrupt_main()
  475. class Executive:
  476. def __init__(self, rpchandler):
  477. self.rpchandler = rpchandler
  478. if idlelib.testing is False:
  479. self.locals = __main__.__dict__
  480. self.calltip = calltip.Calltip()
  481. self.autocomplete = autocomplete.AutoComplete()
  482. else:
  483. self.locals = {}
  484. def runcode(self, code):
  485. global interruptable
  486. try:
  487. self.user_exc_info = None
  488. interruptable = True
  489. try:
  490. exec(code, self.locals)
  491. finally:
  492. interruptable = False
  493. except SystemExit as e:
  494. if e.args: # SystemExit called with an argument.
  495. ob = e.args[0]
  496. if not isinstance(ob, (type(None), int)):
  497. print('SystemExit: ' + str(ob), file=sys.stderr)
  498. # Return to the interactive prompt.
  499. except:
  500. self.user_exc_info = sys.exc_info() # For testing, hook, viewer.
  501. if quitting:
  502. exit()
  503. if sys.excepthook is sys.__excepthook__:
  504. print_exception()
  505. else:
  506. try:
  507. sys.excepthook(*self.user_exc_info)
  508. except:
  509. self.user_exc_info = sys.exc_info() # For testing.
  510. print_exception()
  511. jit = self.rpchandler.console.getvar("<<toggle-jit-stack-viewer>>")
  512. if jit:
  513. self.rpchandler.interp.open_remote_stack_viewer()
  514. else:
  515. flush_stdout()
  516. def interrupt_the_server(self):
  517. if interruptable:
  518. thread.interrupt_main()
  519. def start_the_debugger(self, gui_adap_oid):
  520. return debugger_r.start_debugger(self.rpchandler, gui_adap_oid)
  521. def stop_the_debugger(self, idb_adap_oid):
  522. "Unregister the Idb Adapter. Link objects and Idb then subject to GC"
  523. self.rpchandler.unregister(idb_adap_oid)
  524. def get_the_calltip(self, name):
  525. return self.calltip.fetch_tip(name)
  526. def get_the_completion_list(self, what, mode):
  527. return self.autocomplete.fetch_completions(what, mode)
  528. def stackviewer(self, flist_oid=None):
  529. if self.user_exc_info:
  530. _, exc, tb = self.user_exc_info
  531. else:
  532. return None
  533. flist = None
  534. if flist_oid is not None:
  535. flist = self.rpchandler.get_remote_proxy(flist_oid)
  536. while tb and tb.tb_frame.f_globals["__name__"] in ["rpc", "run"]:
  537. tb = tb.tb_next
  538. exc.__traceback__ = tb
  539. item = stackviewer.StackTreeItem(exc, flist)
  540. return debugobj_r.remote_object_tree_item(item)
  541. if __name__ == '__main__':
  542. from unittest import main
  543. main('idlelib.idle_test.test_run', verbosity=2)
  544. capture_warnings(False) # Make sure turned off; see bpo-18081.