title: How to print python exception thrown inside exec() function from outside
body: <p>I am writing a little software for executing python codes and I want to print exceptions. The following function gets executed:</p>
  
  <pre><code>def run(self, mode='activate'):
      try:
          exec(self.mycode)
      except Exception:
          print(traceback.format_exc())
  </code></pre>
  
  <p>There is no information about what exactly will be executed in the exec() function, it can literally be any python code. I want to print an exception thrown (mostly automatically by python due to code errors) somehow like shown, while executing via exec() including the line of code passed into the exec() function where the exception has been thrown.
  I so far only managed to get the 'exec(mycode)' as exception code output, but I want the actual line of code that crashed in <em>mycode</em>.</p>