run.py 20 KB

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