title: python interrupt infinite loop in exec'd script in thread
body: <p>A GUI application allows the user to write a Python script, then run it (via exec). Problem is that if the user, by mistake (I'm not concerned with ill intention, just honest coding mistakes on the part of the user) the script contains an infinite loop, control will never return to my application. A keyboard interrupt doesn't work because of the GUI. </p>
  
  <p>I have identified four ways to handle this: </p>
  
  <ol>
  <li>Tracing: use sys.settrace so a function gets called at every line; in there, I could put logic that attempts to identify if the same segment of code is being executed over and over (how challenging this would be in practice I don't know yet). I would guess that this could slow down execution speed considerably. </li>
  <li>Asynchronous exception: run the script in a separate thread and, using ctypes, have main thread use PyThreadState_SetAsyncExc to raise an exception in the script thread to kick it out of its loop (see <a href="https://gist.github.com/liuw/2407154" rel="nofollow">https://gist.github.com/liuw/2407154</a> and <a href="http://tomerfiliba.com/recipes/Thread2/" rel="nofollow">http://tomerfiliba.com/recipes/Thread2/</a>). Then the part of thread that called exec would recover control and could take appropriate action (show message to user etc). I know, threads should not be aborted from the outside but here, even if doing this leaves the objects that were being changed by the script in an undefined state, at least it would allow the GUI to throw out the objects that are no longer reliable (it can do that because all modifications accessible to script are in one big object that could be thrown out and reloaded from disk).  </li>
  <li>Separate process: using multiprocessing module, would run the script in a separate process; however the script can contain calls to objects that live in the parent's main thread so this is going to get quite complicated. </li>
  <li>Daemonic thread: run script in daemonic thread, then if script doean't return after a certain period, consider it "hung". When the application exits, the thread will continue to run and the user can forcibly kill it via task manager (or the exiting thread could, by raising SystemException or such). </li>
  </ol>
  
  <p>So the question: If I have to provide this feature, which one of the above methods is the lesser of all evils? Are there other techniques yet, not in the above 4? </p>