在TCL中获取从另一个脚本调用的proc的路径

时间:2011-03-04 11:43:43

标签: tcl

我是TCL编程的新手

我在两个不同的

中分别有一个名为test1.tcl和test2.tcl的tcl脚本

目录F:\ TCLPrograms \ SamplePrograms \ test1.tcl和F:\ TCLPrograms \ test2.tcl

我想知道test2.tcl的完整路径,这是一个proc

如果我在proc disp {}中提供info [script],则返回调用它的路径

即F:\ TCLPrograms \ SamplePrograms \ test1.tcl

亲切地告诉我要获得proc的路径

test1.tcl:

puts "Processing test1..."
source "F:\\TCLPrograms\\test2.tcl"
set rc [disp]
puts "Executed...."

test2.tcl:

proc disp { } {
puts "Successfully executed test2.tcl"
set path [info script]
puts "Script is invoked from the path: $path"
}

提前致谢

1 个答案:

答案 0 :(得分:6)

info script的结果取决于当前最内层source,并且过程不会保留该信息。 (好吧,它保存在8.6的调试信息和来自ActiveState的8.5版本中,但访问真的很难。)

最简单的方法是使用变量来保存文件的名称,如下所示:

variable dispScriptFile [file normalize [info script]]
proc disp {} {
    variable dispScriptFile
    puts "Successfully executed test2.tcl"
    set path [file dirname $dispScriptFile]
    puts "Script is invoked from the path: $path"
}

请注意,我们使用规范化的文件名,因此即使您使用相对路径名,然后使用cd到其他目录,它仍然有效。 (我还建议将test2.tcl的全部内容放在它自己的命名空间中;这样可以更容易地将事物分开。)

相关问题