如何打印执行TCL脚本的行号?
#! /usr/bin/tclsh
set a "100"
set b "200"
set c [expr $a + $b]
puts [info script] ;# it will display the script name which it is executing.
# similarly I need to print the script line number.
puts $c
Run Code Online (Sandbox Code Playgroud)
你必须使用info frame
简单地完成这项工作.
info frame ?number?
Run Code Online (Sandbox Code Playgroud)
此命令提供对堆栈中所有帧的访问,甚至是从信息级别隐藏的那些帧.如果未指定number,则此命令返回一个数字,给出命令的帧级别.如果在顶层调用该命令,则此值为1.如果指定了number,则结果是一个字典,其中包含堆栈上编号级别的命令的位置信息.
如果number为正(> 0)则它选择一个特定的堆栈级别(1指的是最顶层的活动命令,即info frame
它本身,2指向它被调用的命令,依此类推); 否则它给出一个相对于当前命令的级别(0表示当前命令,即信息帧本身,-1表示其调用者,依此类推).
我们将使用该info frame
命令返回的字典.其中一个关键是'line',它包含脚本的行号.
有一个简单proc
的,
proc printLine {frame_info} {
# Getting value of the key 'line' from the dictionary
# returned by 'info frame'
set result [dict get [info frame $frame_info] line]
}
Run Code Online (Sandbox Code Playgroud)
一般来说,由此产生的字典[info frame $frame_info]
将是,像,
type source line 17 file /home/dinesh/stackoverflow/test cmd {printLine [info frame] } proc ::B level 1
从这一点来说,我们只是获得了关键值'line' dict get
只需使用该上下文的当前帧编号调用此proc,这可以通过info frame
自身实现.
即
set lineNumber [printLine [info frame]]; #Place this line in your code.
Run Code Online (Sandbox Code Playgroud)
该逻辑的演示如下.
printLineNumber.tcl
#!/usr/bin/tclsh
proc printLine {frame_info} {
# Getting value of the key 'line' from the dictionary
# returned by 'info frame'
set result [dict get [info frame $frame_info] line]
}
proc D {} {
puts "proc D"
puts [ printLine [info frame] ]
}
proc C {} {
puts "proc C"
puts [ printLine [info frame] ]
D
}
proc B {} {
puts "proc B"
puts [ printLine [info frame] ]
C
}
proc A {} {
puts "proc A"
puts [ printLine [info frame] ]
B
}
puts "Global"
puts [ printLine [info frame] ]
A
Run Code Online (Sandbox Code Playgroud)