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?

HumanTorch
  • 349
  • 2
  • 5
  • 16
  • 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. – Amadan Dec 20 '18 at 04: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? – HumanTorch Dec 20 '18 at 04:09
  • how is the file2 and the file1 are connected. Could you please post full example – Laser Dec 20 '18 at 04:10
  • @Arseniy They are 2 separate files. File2.py could be accessed through File1.py like so: https://stackoverflow.com/questions/1186789/what-is-the-best-way-to-call-a-script-from-another-script – HumanTorch Dec 20 '18 at 04:12

1 Answers1

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.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
Laser
  • 6,652
  • 8
  • 54
  • 85