我如何使用torch REPL进行调试?

有时候为了快速调试,从脚本的某个断点开始启动 REPL 很有用。我发现可以通过以下方式在任意位置启动 Torch REPL:

require "trepl"
repl()

但是,这种方法的唯一问题是 REPL 看不到调用块中的任何局部变量。如果不能检查局部变量,那么 REPL 作为调试器就没有什么用处了。

有可能启动一个能够访问局部变量的 REPL 吗?

免责声明:我已经针对这个问题找到了自己的(新手)解决方案,但我总是愿意接受其他方案/建议。

点赞
用户1804173
用户1804173

一种可能的解决方法是使用包装器,在调用repl()之前使用debug.getlocal将调用范围的本地变量复制到全局范围:

require "trepl"

function debugRepl(restoreGlobals)
  restoreGlobals = restoreGlobals or false

  -- 可选地浅复制_G
  local oldG = {}
  if restoreGlobals then
    for k, v in pairs(_G) do
      oldG[k] = v
    end
  end

  -- 将upvalue复制到_G
  local i = 1
  local func = debug.getinfo(2, "f").func
  while true do
    local k, v = debug.getupvalue(func, i)
    if k ~= nil then
      _G[k] = v
    else
      break
    end
    i = i + 1
  end

  -- 将本地变量复制到_G
  local i = 1
  while true do
    local k, v = debug.getlocal(2, i)
    if k ~= nil then
      _G[k] = v
    else
      break
    end
    i = i + 1
  end

  repl()

  if restoreGlobals then
    _G = oldG
  end
end

注意(因为它在文档中没有提到,只能从源代码中看到):在 REPL 中键入break将返回执行到脚本,而exit(或CTRL + D)则完全终止执行。

2015-10-11 18:31:35