1

I have the following python code shown with line numbers is a file called "myFile.py".

 1:   import traceback
 2:   import sys
 3:   
 4:   def a():
 5:       print "-" * 80
 6:       print "A: %s" % "SOMETHING_1"
 7:       print "-" * 80
 8:   
 9:   
10:   def b():
11:       print "*" * 80
12:       print "B: %s" % SOMETHING_2
13:       a()
14:       print "*" * 80
15:   
16:   
17:   b()

Currently it simply prints:

B: SOMETHING_2
A: SOMETHING_1

However, I would like to change it such that SOMETHING_1 and SOMETHING_2 are replaced by the filename and line number from which their function was called. So I would like it to produce the following output:

B: myFile.py:17
A: myFile.py:12

How can I do that? What do I need to replace SOMETHING_1 and SOMETHING_2 to make it work? I have experimented a bit with the traceback and sys modules but haven't yet landed on a suitable solution.

Saqib Ali
  • 11,931
  • 41
  • 133
  • 272

0 Answers0