如何检查是否已从控制台调用函数? [英] How to check if a function has been called from the console?
问题描述
我试图跟踪从控制台调用某些功能的次数.我的计划是添加一个简单的功能,例如"trackFunction"在每个可以检查是否已从控制台调用它们还是作为基础函数调用的函数中.
尽管问题听起来很简单,但由于我对函数编程的知识有限,所以我找不到很好的解决方案.我一直在看调用堆栈和rlang :: trace_back,但是对此没有很好的解决方案.
感谢您的帮助.
谢谢
一种简单的方法是查看当前框架位于哪个级别.也就是说,如果直接在解释器中调用函数,则 sys.nframe()
返回 1
,否则返回 2
或更高.>
相关:
myfunc<-function(...){如果(sys.nframe()== 1){消息(从控制台调用")} 别的 {消息(从其他地方呼叫")}}myfunc()#从控制台调用g<-function()myfunc()G()#从其他地方调用
不幸的是,这可能并不总是很直观:
ign<-lapply(1,myfunc)#从其他地方调用对于(ign in 1)myfunc()#从控制台调用
尽管 lapply
-family和 for
循环在许多方面是相似的,但它们在这里的行为是分开的.如果这是一个问题,减轻这种情况的唯一方法可能是分析/解析调用堆栈,并可能忽略"消息.某些功能.如果这是您需要的要求,那么也许这更合适:
A simple approach would be to see on which level the current frame lies. That is, if a function is called directly in the interpreter, then sys.nframe()
returns 1
, otherwise 2
or higher.
Relate:
Rscript detect if R script is being called/sourced from another script
myfunc <- function(...) {
if (sys.nframe() == 1) {
message("called from the console")
} else {
message("called from elsewhere")
}
}
myfunc()
# called from the console
g <- function() myfunc()
g()
# called from elsewhere
Unfortunately, this may not always be intuitive:
ign <- lapply(1, myfunc)
# called from elsewhere
for (ign in 1) myfunc()
# called from the console
While for many things the lapply
-family and for
loops are similar, they behave separately here. If this is a problem, perhaps the only way to mitigate this is the analyze/parse the call stack and perhaps "ignore" certain functions. If this is what you need, then perhaps this is more appropriate:
R How to check that a custom function is called within a specific function from a certain package
这篇关于如何检查是否已从控制台调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!