inspect: get the calling command (solved)

Hans Georg Krauthaeuser hgk at et.uni-magdeburg.de
Tue Jun 15 07:11:59 EDT 2004


I got a working solution by myself:

import inspect

def call(a,b,c,d,e):
     s = inspector()
     return s

def inspector():
     frame = inspect.currentframe()
     outerframes = inspect.getouterframes(frame)
     ccframe = outerframes[2][0]
     ccmodule = inspect.getmodule(ccframe)
     try:
         slines, start = inspect.getsourcelines(ccmodule)
     except IOError:
         clen = 10
     else:
         clen = len(slines)
     finfo = inspect.getframeinfo(ccframe, clen)
     theindex = finfo[4]
     lines = finfo[3]
     theline = lines[theindex]
     cmd = theline
     for i in range(theindex-1, 0, -1):
         line = lines[i]
         try:
             compile (cmd.lstrip(), '<string>', 'exec')
         except SyntaxError:
             cmd = line + cmd
         else:
             break
     return cmd

if __name__ == '__main__':
     s1 = call (1,2,3,4,5)
     s2 = call (1,\
                2,\
                3,\
                4,\
                5)
     print '-'*10
     print s1
     print '-'*10
     print s2
     print '-'*10



Hans Georg Krauthaeuser wrote:
> Dear all,
> 
> I have a problem to get the command that has called a function if the 
> command was given on multiple lines. E.g.:
> 
> ###################################################
> import inspect
> 
> def call(a,b,c,d,e):
>     s = inspector()
>     return s
> 
> def inspector():
>     frame = inspect.currentframe()
>     outerframes = inspect.getouterframes(frame)
>     cmd = ''
>     for c in outerframes[2][4]:
>         cmd += c
>     return cmd
> 
> if __name__ == '__main__':
>     s1 = call (1,2,3,4,5)
>     s2 = call (1,\
>                2,\
>                3,\
>                4,\
>                5)
>     print '-'*10
>     print s1
>     print '-'*10
>     print s2
>     print '-'*10
> ###################################################
> 
> This gives the output:
> 
> ----------
>     s1 = call (1,2,3,4,5)
> 
> ----------
>                5)
> 
> ----------
> 
> I'm quite new to python and the standard libs. So forgive me, if this is 
> a stupid question.
> 
> Any help is very much appreciated.
> 
> Best regards
> Hans Georg



More information about the Python-list mailing list