【问题标题】:TCL obtain the proc name in which I amTCL获取我所在的proc名称
【发布时间】:2012-04-18 06:19:08
【问题描述】:

如何知道我所在的 proc 的名称是什么。我的意思是我需要这个:

proc nameOfTheProc {} {

    #a lot of code here
    puts "ERROR: You are using 'nameOfTheProc' proc wrongly"
}

所以我想获得“nameOfTheProc”,但不是硬编码。这样当有人更改 proc 名称时,它仍然可以正常工作。

【问题讨论】:

  • +1 个很好的问题,它产生了很多有趣的答案。

标签: tcl proc


【解决方案1】:

您可以使用info level 命令解决您的问题:

proc nameOfTheProc {} {

    #a lot of code here
    puts "ERROR: You are using '[lindex [info level 0] 0]' proc wrongly"
    puts "INFO:  You specified the arguments: '[lrange [info level [info level]] 1 end]'"
}

使用内部info level,您将获得当前所处的过程调用深度级别。外部将返回过程本身的名称。

【讨论】:

  • [info level [info level]] 可以写成[info level 0]...
【解决方案2】:

在您的问题中实现暗示的正确惯用方法是像这样使用return -code error $message

proc nameOfTheProc {} {
    #a lot of code here
    return -code error "Wrong sequence of blorbs passed"
}

这样,您的过程将完全按照普通 Tcl 命令的方式运行,当它们对被调用的内容不满意时:这会导致调用站点出错。

【讨论】:

  • 这并没有告诉我调用了什么 proc,是吗?
  • @Narek,您将从堆栈跟踪中看到这一点,其中包括错误消息和返回错误的过程名称。如果您能捕捉到该错误(即不允许运行时终止程序并转储堆栈跟踪),您将能够使用return 手册(errorInfo 等)中描述的工具检查情况。
  • @Narek,基本上建议学习专业人士编写的 Tcl 代码(tcllib 中的模块就是很好的例子)。您会看到他们大量使用了 return -code error 习语,因为调用 error(或使用其他错误报告方式)是为了表示“外部”运行时错误,例如无法获取资源或完成请求的操作等,而return -code error 用于报告“静态”语义错误,例如以错误的方式调用命令。
【解决方案3】:

如果您正在运行 Tcl 8.5 或更高版本,info frame 命令将返回一个字典而不是一个列表。所以修改代码如下:

proc nameOfTheProc {} {
   puts "This is [dict get [info frame [info frame]] proc]"
}

【讨论】:

  • 这并不完全正确。 info level 仍将返回一个列表(至少在 8.5 版中)。但是info frame 返回一个字典。
  • @bmk 你说得对——我已经修正了答案,所以它是文本中的信息框。
  • 信息级别是关于参数列表的,信息框架是关于一般框架描述符的。两者相辅相成。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-06
  • 2011-09-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-10
相关资源
最近更新 更多