[英]How do I know where is a function was executed in Python?
Let's imagine, I've got a module foo.py
with declared a function foofunc
: 让我们想象一下,我有一个模块
foo.py
与声明的函数foofunc
:
def foofunc():
# smart things
return
And two different modules — bar.py
and spam.py
, where exists code which directly executes the function from foo
module. 还有两个不同的模块
bar.py
和spam.py
,其中存在直接从foo
模块执行功能的代码。
# `bar` module. All rights reserved.
from foo import foofunc
def run_foofunc():
return foofunc()
The same thing in another module: 另一个模块中的相同内容:
# `spam` module. All rights reserved.
from foo import foofunc
def run_foofunc():
return foofunc()
I need to know where is executed the function without knowledge of possible places. 我需要知道在不知道可能位置的情况下在何处执行该功能。 Something like:
就像是:
def foofunc():
print inspect.executedfrom()
Will do something like that in standard output 将在标准输出中执行类似的操作
<pack.bar.run_foofunc>
Does it something similar in real world? 在现实世界中是否类似?
Running the risk of not answering the actual question, you wrote that you need it for research and debugging. 冒着无法回答实际问题的风险,您写道,您需要它进行研究和调试。
I think the traceback
module is just great for that. 我认为
traceback
模块对此非常traceback
。
import traceback
traceback.print_stack()
Also take a look at pdb
, it allows you to interactively step through your code during runtime. 还要看一下
pdb
,它使您可以在运行时交互式地逐步执行代码。
test.py: test.py:
import inspect
def foofunc():
frame, filename, line_number, function_name, lines, index = inspect.getouterframes(
inspect.currentframe())[1]
print(filename, line_number, function_name)
return
foo.py: foo.py:
import test
def run_foofunc():
test.foofunc()
run_foofunc()
yields 产量
('/tmp/foo.py', 3, 'run_foofunc')
Here is a possible implementation of executed_from
: 这里是一个可能实现的
executed_from
:
import inspect
def executed_from():
f = inspect.currentframe().f_back.f_back
return "%s.%s" % (inspect.getmodule(f).__name__, f.f_code.co_name)
During wait for your answers I found my own answer. 在等待您的答案期间,我找到了自己的答案。 This issue possible to resolve by raising an exception in debugged function and make out the traceback layer by layer.
通过在调试函数中引发异常并逐层找出回溯,可以解决此问题。 This approach is bad in general because it is stops execution, but not bad in the my particular case.
这种方法通常是不好的,因为它会停止执行,但在我的特定情况下却并不坏。 And besides it is very pythonic and easy to clean.
而且它非常pythonic,易于清理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.