filename of calling function?

P

Phlip

Consider these two python modules:

aa.py

def a():
print '?'

bb.py
import aa

def bb():
aa.a()

bb()

How do I make the print line emit the filename of bb.py? (It could be
anything.)

I am currently playing with sys.exc_info, but it seems to only emit
the stack between the raise and the except. Could be pilot error, of
course. Thanks for any help!
 
P

Phlip

Consider these two python modules:

aa.py

def a():
    print '?'

bb.py
  import aa

def bb():
  aa.a()

bb()

How do I make the print line emit the filename of bb.py? (It could be
anything.)

try:
raise None
except:
import sys
from traceback import extract_tb, extract_stack
frame = sys.exc_info()[2].tb_frame.f_back
calling_file = extract_stack(frame, 2)[1][0]
 
J

Joel Davis

Consider these two python modules:

def a():
    print '?'
bb.py
  import aa
def bb():
  aa.a()

How do I make the print line emit the filename of bb.py? (It could be
anything.)

        try:
            raise None
        except:
            import sys
            from traceback import extract_tb, extract_stack
            frame = sys.exc_info()[2].tb_frame.f_back
            calling_file = extract_stack(frame, 2)[1][0]

code works perfectly except on my system both the indexes need to be 0
(eg: "extract_stack(frame, 2)[0][0]")
 
P

Phlip

        try:
            raise None
        except:
            import sys
            from traceback import extract_tb, extract_stack
            frame = sys.exc_info()[2].tb_frame.f_back
            calling_file = extract_stack(frame, 2)[1][0]

code works perfectly except on my system both the indexes need to be 0
(eg: "extract_stack(frame, 2)[0][0]")

I thought the 0 was myself, 1 my caller, etc. But tx for trying it
 
G

Gerard Flanagan

Phlip said:
Consider these two python modules:

aa.py

def a():
print '?'

bb.py
import aa

def bb():
aa.a()

bb()

How do I make the print line emit the filename of bb.py? (It could be
anything.)

Possibly not very reliable in every situation (doctests, other pythons,
....) but this is what I do:


--------- aa.py --------------
import __main__ as CALLER

def mynameis():
print CALLER.__file__

--------- bb.py --------------

import aa

def whosthere():
aa.mynameis()

whosthere()

-------------------------------

OUTPUT: bb.py


hth

G.F.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,183
Messages
2,570,969
Members
47,524
Latest member
ecomwebdesign

Latest Threads

Top