Debian Codegraph @

cpython27/Lib/idlelib/run.py

raw symbols SCIP
1 import sys
2 import linecache
3 import time
4 import socket
5 import traceback
6 import thread
7 import threading
8 import Queue
9
10 from idlelib import CallTips
11 from idlelib import AutoComplete
12
13 from idlelib import RemoteDebugger
14 from idlelib import RemoteObjectBrowser
15 from idlelib import StackViewer
16 from idlelib import rpc
17 from idlelib import PyShell
18 from idlelib import IOBinding
19
20 import __main__
21
22 LOCALHOST = '127.0.0.1'
23
24 import warnings
25
26 def idle_showwarning_subproc(
27 message, category, filename, lineno, file=None, line=None):
28 """Show Idle-format warning after replacing warnings.showwarning.
29
30 The only difference is the formatter called.
31 """
32 if file is None:
33 file = sys.stderr
34 try:
35 file.write(PyShell.idle_formatwarning(
36 message, category, filename, lineno, line))
37 except IOError:
38 pass # the file (probably stderr) is invalid - this warning gets lost.
39
40 _warnings_showwarning = None
41
42 def capture_warnings(capture):
43 "Replace warning.showwarning with idle_showwarning_subproc, or reverse."
44
45 global _warnings_showwarning
46 if capture:
47 if _warnings_showwarning is None:
48 _warnings_showwarning = warnings.showwarning
49 warnings.showwarning = idle_showwarning_subproc
50 else:
51 if _warnings_showwarning is not None:
52 warnings.showwarning = _warnings_showwarning
53 _warnings_showwarning = None
54
55 capture_warnings(True)
56
57 # Thread shared globals: Establish a queue between a subthread (which handles
58 # the socket) and the main thread (which runs user code), plus global
59 # completion, exit and interruptable (the main thread) flags:
60
61 exit_now = False
62 quitting = False
63 interruptable = False
64
65 def main(del_exitfunc=False):
66 """Start the Python execution server in a subprocess
67
68 In the Python subprocess, RPCServer is instantiated with handlerclass
69 MyHandler, which inherits register/unregister methods from RPCHandler via
70 the mix-in class SocketIO.
71
72 When the RPCServer 'server' is instantiated, the TCPServer initialization
73 creates an instance of run.MyHandler and calls its handle() method.
74 handle() instantiates a run.Executive object, passing it a reference to the
75 MyHandler object. That reference is saved as attribute rpchandler of the
76 Executive instance. The Executive methods have access to the reference and
77 can pass it on to entities that they command
78 (e.g. RemoteDebugger.Debugger.start_debugger()). The latter, in turn, can
79 call MyHandler(SocketIO) register/unregister methods via the reference to
80 register and unregister themselves.
81
82 """
83 global exit_now
84 global quitting
85 global no_exitfunc
86 no_exitfunc = del_exitfunc
87 #time.sleep(15) # test subprocess not responding
88 try:
89 assert(len(sys.argv) > 1)
90 port = int(sys.argv[-1])
91 except:
92 print>>sys.stderr, "IDLE Subprocess: no IP port passed in sys.argv."
93 return
94
95 capture_warnings(True)
96 sys.argv[:] = [""]
97 sockthread = threading.Thread(target=manage_socket,
98 name='SockThread',
99 args=((LOCALHOST, port),))
100 sockthread.setDaemon(True)
101 sockthread.start()
102 while 1:
103 try:
104 if exit_now:
105 try:
106 exit()
107 except KeyboardInterrupt:
108 # exiting but got an extra KBI? Try again!
109 continue
110 try:
111 seq, request = rpc.request_queue.get(block=True, timeout=0.05)
112 except Queue.Empty:
113 continue
114 method, args, kwargs = request
115 ret = method(*args, **kwargs)
116 rpc.response_queue.put((seq, ret))
117 except KeyboardInterrupt:
118 if quitting:
119 exit_now = True
120 continue
121 except SystemExit:
122 capture_warnings(False)
123 raise
124 except:
125 type, value, tb = sys.exc_info()
126 try:
127 print_exception()
128 rpc.response_queue.put((seq, None))
129 except:
130 # Link didn't work, print same exception to __stderr__
131 traceback.print_exception(type, value, tb, file=sys.__stderr__)
132 exit()
133 else:
134 continue
135
136 def manage_socket(address):
137 for i in range(3):
138 time.sleep(i)
139 try:
140 server = MyRPCServer(address, MyHandler)
141 break
142 except socket.error as err:
143 print>>sys.__stderr__,"IDLE Subprocess: socket error: "\
144 + err.args[1] + ", retrying...."
145 else:
146 print>>sys.__stderr__, "IDLE Subprocess: Connection to "\
147 "IDLE GUI failed, exiting."
148 show_socket_error(err, address)
149 global exit_now
150 exit_now = True
151 return
152 server.handle_request() # A single request only
153
154 def show_socket_error(err, address):
155 import Tkinter
156 import tkMessageBox
157 root = Tkinter.Tk()
158 fix_scaling(root)
159 root.withdraw()
160 if err.args[0] == 61: # connection refused
161 msg = "IDLE's subprocess can't connect to %s:%d. This may be due "\
162 "to your personal firewall configuration. It is safe to "\
163 "allow this internal connection because no data is visible on "\
164 "external ports." % address
165 tkMessageBox.showerror("IDLE Subprocess Error", msg, parent=root)
166 else:
167 tkMessageBox.showerror("IDLE Subprocess Error",
168 "Socket Error: %s" % err.args[1], parent=root)
169 root.destroy()
170
171 def print_exception():
172 import linecache
173 linecache.checkcache()
174 flush_stdout()
175 efile = sys.stderr
176 typ, val, tb = excinfo = sys.exc_info()
177 sys.last_type, sys.last_value, sys.last_traceback = excinfo
178 tbe = traceback.extract_tb(tb)
179 print>>efile, '\nTraceback (most recent call last):'
180 exclude = ("run.py", "rpc.py", "threading.py", "Queue.py",
181 "RemoteDebugger.py", "bdb.py")
182 cleanup_traceback(tbe, exclude)
183 traceback.print_list(tbe, file=efile)
184 lines = traceback.format_exception_only(typ, val)
185 for line in lines:
186 print>>efile, line,
187
188 def cleanup_traceback(tb, exclude):
189 "Remove excluded traces from beginning/end of tb; get cached lines"
190 orig_tb = tb[:]
191 while tb:
192 for rpcfile in exclude:
193 if tb[0][0].count(rpcfile):
194 break # found an exclude, break for: and delete tb[0]
195 else:
196 break # no excludes, have left RPC code, break while:
197 del tb[0]
198 while tb:
199 for rpcfile in exclude:
200 if tb[-1][0].count(rpcfile):
201 break
202 else:
203 break
204 del tb[-1]
205 if len(tb) == 0:
206 # exception was in IDLE internals, don't prune!
207 tb[:] = orig_tb[:]
208 print>>sys.stderr, "** IDLE Internal Exception: "
209 rpchandler = rpc.objecttable['exec'].rpchandler
210 for i in range(len(tb)):
211 fn, ln, nm, line = tb[i]
212 if nm == '?':
213 nm = "-toplevel-"
214 if fn.startswith("<pyshell#") and IOBinding.encoding != 'utf-8':
215 ln -= 1 # correction for coding cookie
216 if not line and fn.startswith("<pyshell#"):
217 line = rpchandler.remotecall('linecache', 'getline',
218 (fn, ln), {})
219 tb[i] = fn, ln, nm, line
220
221 def flush_stdout():
222 try:
223 if sys.stdout.softspace:
224 sys.stdout.softspace = 0
225 sys.stdout.write("\n")
226 except (AttributeError, EOFError):
227 pass
228
229 def exit():
230 """Exit subprocess, possibly after first deleting sys.exitfunc
231
232 If config-main.cfg/.def 'General' 'delete-exitfunc' is True, then any
233 sys.exitfunc will be removed before exiting. (VPython support)
234
235 """
236 if no_exitfunc:
237 try:
238 del sys.exitfunc
239 except AttributeError:
240 pass
241 capture_warnings(False)
242 sys.exit(0)
243
244
245 def fix_scaling(root):
246 """Scale fonts on HiDPI displays."""
247 import tkFont
248 scaling = float(root.tk.call('tk', 'scaling'))
249 if scaling > 1.4:
250 for name in tkFont.names(root):
251 font = tkFont.Font(root=root, name=name, exists=True)
252 size = int(font['size'])
253 if size < 0:
254 font['size'] = int(round(-0.75*size))
255
256
257 class MyRPCServer(rpc.RPCServer):
258
259 def handle_error(self, request, client_address):
260 """Override RPCServer method for IDLE
261
262 Interrupt the MainThread and exit server if link is dropped.
263
264 """
265 global quitting
266 try:
267 raise
268 except SystemExit:
269 raise
270 except EOFError:
271 global exit_now
272 exit_now = True
273 thread.interrupt_main()
274 except:
275 erf = sys.__stderr__
276 print>>erf, '\n' + '-'*40
277 print>>erf, 'Unhandled server exception!'
278 print>>erf, 'Thread: %s' % threading.currentThread().getName()
279 print>>erf, 'Client Address: ', client_address
280 print>>erf, 'Request: ', repr(request)
281 traceback.print_exc(file=erf)
282 print>>erf, '\n*** Unrecoverable, server exiting!'
283 print>>erf, '-'*40
284 quitting = True
285 thread.interrupt_main()
286
287 class MyHandler(rpc.RPCHandler):
288
289 def handle(self):
290 """Override base method"""
291 executive = Executive(self)
292 self.register("exec", executive)
293 self.console = self.get_remote_proxy("console")
294 sys.stdin = PyShell.PseudoInputFile(self.console, "stdin",
295 IOBinding.encoding)
296 sys.stdout = PyShell.PseudoOutputFile(self.console, "stdout",
297 IOBinding.encoding)
298 sys.stderr = PyShell.PseudoOutputFile(self.console, "stderr",
299 IOBinding.encoding)
300
301 # Keep a reference to stdin so that it won't try to exit IDLE if
302 # sys.stdin gets changed from within IDLE's shell. See issue17838.
303 self._keep_stdin = sys.stdin
304
305 self.interp = self.get_remote_proxy("interp")
306 rpc.RPCHandler.getresponse(self, myseq=None, wait=0.05)
307
308 def exithook(self):
309 "override SocketIO method - wait for MainThread to shut us down"
310 time.sleep(10)
311
312 def EOFhook(self):
313 "Override SocketIO method - terminate wait on callback and exit thread"
314 global quitting
315 quitting = True
316 thread.interrupt_main()
317
318 def decode_interrupthook(self):
319 "interrupt awakened thread"
320 global quitting
321 quitting = True
322 thread.interrupt_main()
323
324
325 class Executive(object):
326
327 def __init__(self, rpchandler):
328 self.rpchandler = rpchandler
329 self.locals = __main__.__dict__
330 self.calltip = CallTips.CallTips()
331 self.autocomplete = AutoComplete.AutoComplete()
332
333 def runcode(self, code):
334 global interruptable
335 try:
336 self.usr_exc_info = None
337 interruptable = True
338 try:
339 exec code in self.locals
340 finally:
341 interruptable = False
342 except SystemExit:
343 # Scripts that raise SystemExit should just
344 # return to the interactive prompt
345 pass
346 except:
347 self.usr_exc_info = sys.exc_info()
348 if quitting:
349 exit()
350 print_exception()
351 jit = self.rpchandler.console.getvar("<<toggle-jit-stack-viewer>>")
352 if jit:
353 self.rpchandler.interp.open_remote_stack_viewer()
354 else:
355 flush_stdout()
356
357 def interrupt_the_server(self):
358 if interruptable:
359 thread.interrupt_main()
360
361 def start_the_debugger(self, gui_adap_oid):
362 return RemoteDebugger.start_debugger(self.rpchandler, gui_adap_oid)
363
364 def stop_the_debugger(self, idb_adap_oid):
365 "Unregister the Idb Adapter. Link objects and Idb then subject to GC"
366 self.rpchandler.unregister(idb_adap_oid)
367
368 def get_the_calltip(self, name):
369 return self.calltip.fetch_tip(name)
370
371 def get_the_completion_list(self, what, mode):
372 return self.autocomplete.fetch_completions(what, mode)
373
374 def stackviewer(self, flist_oid=None):
375 if self.usr_exc_info:
376 typ, val, tb = self.usr_exc_info
377 else:
378 return None
379 flist = None
380 if flist_oid is not None:
381 flist = self.rpchandler.get_remote_proxy(flist_oid)
382 while tb and tb.tb_frame.f_globals["__name__"] in ["rpc", "run"]:
383 tb = tb.tb_next
384 sys.last_type = typ
385 sys.last_value = val
386 item = StackViewer.StackTreeItem(flist, tb)
387 return RemoteObjectBrowser.remote_object_tree_item(item)
388
389 capture_warnings(False) # Make sure turned off; see issue 18081