-
定义函数的行号。
使用:inspect.getsourcelines(THE_NAME_OF_YOUR_FUNCTION)[1]
-
函数所在的行。
使用:called.inspect.stack()[1][2]
-
调用/调用函数。
使用:inspect.stack()[1][3]
-
(可选)包含它的模块。
使用:THE_NAME_OF_YOUR_FUNCTION.__module__
举个例子……(我添加了一个额外的函数X)
import inspect
def foo(msg):
print(msg)
###▼ YOUR INSPECTION CODE ▼###
print("\t«{}»\tLine number in which the function is defined.".
format(inspect.getsourcelines(foo)[1]))
print("\t«{}»\tLine from which the function has been called.".
format(inspect.stack()[1][2]))
print("\t«{}»\tInvoking/calling function.".format(inspect.stack()[1][3]))
print("\t«{}»\tModule in which it is contained.\n".format(foo.__module__))
def suma(a, b):
foo("Call from [suma()], on the line [14]")
return a+b
def difference(a, b):
foo("Call from [difference()], on the line [18]")
return a-b
def main():
foo("Call from [main()], on the line [22]")
suma(3,6)
foo("Call from [main()], on the line [24]")
difference(5,2)
if __name__ == "__main__":
main()
如果我们列出前面的行,代码如下:
01 import inspect
02
03 def foo(msg):
04 print(msg)
05 ###▼ YOUR INSPECTION CODE ▼###
06 print("\t«{}»\tLine number in which the function is defined.".
07 format(inspect.getsourcelines(foo)[1]))
08 print("\t«{}»\tLine from which the function has been called.".
09 format(inspect.stack()[1][2]))
10 print("\t«{}»\tInvoking/calling function.".format(inspect.stack()[1][3]))
11 print("\t«{}»\tModule in which it is contained.\n".format(foo.__module__))
12
13 def suma(a, b):
14 foo("Call from [suma()], on the line [14]")
15 return a+b
16
17 def difference(a, b):
18 foo("Call from [difference()], on the line [18]")
19 return a-b
20
21 def main():
22 foo("Call from [main()], on the line [22]")
23 suma(3,6)
24 foo("Call from [main()], on the line [24]")
25 difference(5,2)
26
27 if __name__ == "__main__":
28 main()
你会得到这样的结果:
Call from [main()], on the line [22]
«3» Line number in which the function is defined.
«22» Line from which the function has been called.
«main» Invoking/calling function.
«__main__» Module in which it is contained.
Call from [suma()], on the line [14]
«3» Line number in which the function is defined.
«14» Line from which the function has been called.
«suma» Invoking/calling function.
«__main__» Module in which it is contained.
Call from [main()], on the line [24]
«3» Line number in which the function is defined.
«24» Line from which the function has been called.
«main» Invoking/calling function.
«__main__» Module in which it is contained.
Call from [difference()], on the line [18]
«3» Line number in which the function is defined.
«18» Line from which the function has been called.
«difference» Invoking/calling function.
«__main__» Module in which it is contained.