出于调试目的,我想打印调用当前函数的位置的行号(和函数名称)。我如何在 R 中得到这个?
我看过 getting the source file name 的解决方案
但是如何获取行号和函数名?]
编辑:我找到了如何从 traceback()
获取这些数据以某种形式,回溯能够将其打印出来,但我不确定如何从中解码信息:
f <- function () {
traceback(x = 3, max.lines = 1)
}
g <- function()
{
f()
}
x <- g()
source("file.R") # file with this code
# 5: g() at file.R#20
# 4: eval(ei, envir)
# 3: eval(ei, envir)
# 2: withVisible(eval(ei, envir))
# 1: source("file.R")
str(x[[1]])
# chr "g()"
# - attr(*, "srcref")= 'srcref' int [1:8] 20 1 20 8 1 8 20 20
# ..- attr(*, "srcfile")=Classes 'srcfilecopy', 'srcfile' <environment: 0x0000000013a31700>
最佳答案
找到了解决办法!从 traceback() 的代码中得到:
f <- function ()
{
x <- .traceback(x = 1)
srcloc <- if (!is.null(srcref <- attr(x[[1]], "srcref"))) {
srcfile <- attr(srcref, "srcfile")
paste0("Called from ", x[[2]], ", at ", basename(srcfile$filename), "#", srcref[1])
}
cat(srcloc, "\n")
}
g <- function()
{
f()
}
g()
# Called from g(), at file.R#15
为它编写了一个很好的包装函数:
# returns a list, unless fmtstring is specified
# level: 1 - caller of the caller of this function; 2 - its parent, 3 - its grand-parent etc.
# fmtstring: return format string: %f (function), %s (source file), %l (line)
#
# example: str <- caller_info("Called from %f at %s#%l\n")
# !!! it won't work with e.g. cat(caller_info("Called from %f at %s#%l\n"))
# or cat(paste0(caller_info("Called from %f at %s#%l\n"))) !!!
caller_info <- function (fmtstring = NULL, level = 1) # https://stackoverflow.com/q/59537482/684229
{
x <- .traceback(x = level + 1)
i <- 1
repeat { # loop for subexpressions case; find the first one with source reference
srcref <- getSrcref(x[[i]])
if (is.null(srcref)) {
if (i < length(x)) {
i <- i + 1
next;
} else {
warning("caller_info(): not found\n")
return (NULL)
}
}
srcloc <- list(fun = getSrcref(x[[i+1]]), file = getSrcFilename(x[[i]]), line = getSrcLocation(x[[i]]))
break;
}
if (is.null(fmtstring))
return (srcloc)
fmtstring <- sub("%f", paste0(srcloc$fun, collapse = ""), fmtstring)
fmtstring <- sub("%s", srcloc$file, fmtstring)
fmtstring <- sub("%l", srcloc$line, fmtstring)
fmtstring
}
这是它的使用方式:
f <- function ()
{
str <- caller_info("Called from %f at %s#%l\n")
cat(str)
}
唯一的(次要)限制是当在像
cat(caller_info("Called from %f at %s#%l\n"))
这样的子表达式中调用时或 cat(paste0(caller_info("Called from %f at %s#%l\n")))
, R 混淆地将这些子表达式的东西算作堆栈级别,这把它搞砸了。所以最好避免在表达式中使用这个包装器。
关于r - 如何在R中获取函数调用的行号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59537482/