You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tcl技术问询:如何获取调用者所在命名空间及其包含的过程?

获取调用者的命名空间及其中的过程

你的问题出在register过程的执行上下文上——过程默认在自身定义的命名空间中执行,所以namespace current和info procs返回的都是定义register的命名空间信息,而非调用它的Foo命名空间。

要获取调用者的上下文,需要用uplevel命令在调用者的层级执行相关命令,修改后的代码如下:

proc register {} {
    # 读取调用者的当前命名空间
    set caller_ns [uplevel 1 {namespace current}]
    # 读取调用者命名空间内的所有过程
    set caller_procs [uplevel 1 {info procs}]
    
    puts "调用者命名空间:$caller_ns"
    puts "该命名空间内的过程:$caller_procs"
}

namespace eval Foo {
    proc bar {} {
        puts bar
    }

    proc _baz {} {
        puts baz
    }

    register
}

运行这段代码会输出:

调用者命名空间:::Foo
该命名空间内的过程:bar _baz

如果需要过滤以下划线开头的私有过程,可以对结果做进一步处理:

proc register {} {
    set caller_ns [uplevel 1 {namespace current}]
    set all_procs [uplevel 1 {info procs}]
    # 排除下划线开头的过程
    set public_procs [lsearch -all -inline -not -regexp $all_procs {^_}]
    
    puts "调用者命名空间:$caller_ns"
    puts "该命名空间内的公开过程:$public_procs"
}

内容的提问来源于stack exchange,提问作者Al Bundy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 18:45:41