How to print python exception thrown inside exec() function from outside
Asked Answered
R

2

7

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.

Recluse answered 5/12, 2019 at 18:44 Comment(1)
F
-1

try this :

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

This would work!

Fukuoka answered 5/12, 2019 at 18:46 Comment(3)
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.Recluse
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!Fukuoka
add this line traceback.print_exc() see my following answerFukuoka
F
-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!

Fukuoka answered 5/12, 2019 at 19:4 Comment(2)
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 crashRecluse
Try to take the code out of function, try to execute it in as plain pythonFukuoka

© 2022 - 2024 — McMap. All rights reserved.