2

I want File1.py to return the error line in File2.py

File1.py:

def find_errors(file_path_of_File2):
    print(f'the error is on line {}')

the error is on line 2

File2.py:

print('this is line 1')
print(5/0)

ZeroDivisionError: integer division or modulo by zero

Is this possible?

4
  • 1
    Not possible: ZeroDivisionError is a runtime error, not a compile-time error. The only way to know it will be raised is to execute the code, and see it raised. Commented Dec 20, 2018 at 4:05
  • What's wrong if I executed File2.py through File1.py and saved the output of File2.py (which results in the error) and then returned that error line in File1.py? Commented Dec 20, 2018 at 4:09
  • how is the file2 and the file1 are connected. Could you please post full example Commented Dec 20, 2018 at 4:10
  • @Arseniy They are 2 separate files. File2.py could be accessed through File1.py like so: stackoverflow.com/questions/1186789/… Commented Dec 20, 2018 at 4:12

1 Answer 1

3

You can do it a little bit ugly with the traceback module.

File1.py

print('this is line 1')
print(5/0)

File2.py

import sys
import traceback
try:
    import test
except Exception as e:
    (exc_type, exc_value, exc_traceback) = sys.exc_info()
    trace_back = [traceback.extract_tb(sys.exc_info()[2])[-1]][0]
    print("Exception {} is on line {}".format(exc_type, trace_back[1]))

output

this is line 1
Exception <type 'exceptions.ZeroDivisionError'> is on line 2

In this case, you will catch all exceptions raised during importing your file, then you will take the last one from the trace_back.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.