How to access the calling source line from interactive shell

Posted by TJD on Stack Overflow See other posts from Stack Overflow or by TJD
Published on 2012-11-02T22:57:01Z Indexed on 2012/11/02 23:00 UTC
Read the original article Hit count: 169

Filed under:

I want to make a function that can determine the source code of how it was called. I'm aware of how to do this generally with the inspect module. For example, this question, works well and provides my desired output in the lines variable as shown below:

def hello(x):
   frame,filename,line_number,function_name,lines,index=\
       inspect.getouterframes(inspect.currentframe())[1]
   print(frame,filename,line_number,function_name,lines,index)

The problem is that this solution doesn't work in an interactive command line session. For example, from a command line, the result looks like:

>>> y = hello(7)
(<frame object at 0x01ECA9E8>, '<stdin>', 1, '<module>', None, None)

The problem is that the source file is '<stdin>', so the lines variable is None. How can I access the calling line to find the result containing the string y = hello(7) during an interactive session?

© Stack Overflow or respective owner

Related posts about python