logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

run.py (21396B)


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