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