6

I am writing a little software for executing python codes and I want to print exceptions. The following function gets executed:

def run(self, mode='activate'):
    try:
        exec(self.mycode)
    except Exception:
        print(traceback.format_exc())

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 mycode.

mep
  • 341
  • 2
  • 11

2 Answers2

-1

try this :

def run(self, mode='activate'):
    try:
        exec(your_code)
    except Exception as e: 
        print(e)

This would work!

  • Thanks, but that gives me only the actual error output but not the line of code that crashed. F.ex. 'must be str, not int'. But I am looking for 1. the whole traceback and 2. including the line of code that caused the crash. – mep Dec 05 '19 at 18:55
  • Superb try to speculate first where do you see this happening. Once the speculation is done try to print the line where execution ran, the line where it is not running can be your faulty line, or simply run the code through debugger. Hope this could help! – Shantanu Deshmukh Dec 05 '19 at 18:59
  • add this line `traceback.print_exc()` see my following answer – Shantanu Deshmukh Dec 05 '19 at 19:04
-1

add this line traceback.print_exc()

def run(self, mode='activate'):
    try:
        exec(your_code)
    except Exception as e: 
        print(e)
        traceback.print_exc()

This would give you the exception information and also will give you line number where the exception/error occurred!

  • 1
    Yeah, also tried that, but it still gives the code from the executing app ('exec(self.mycode)'), but not the code in _self.mycode_ that caused the crash – mep Dec 05 '19 at 19:11
  • Try to take the code out of function, try to execute it in as plain python – Shantanu Deshmukh Dec 05 '19 at 19:16