I recently wanted this functionality to set up some unit tests for my HDL build scripts suite. This is what i ended up with for Vivado:
proc is_main_script {} { ;# +1 frame
set frame [info frame [expr [info frame] -3]]
if {![dict exists $frame file]} {
set command [file normalize [lindex [dict get $frame cmd] 1]]
set script [file normalize [info script]]
if {$script eq $command} {
return 1
} else {
return 0
}
} else {
return 0
}
}
if {is_main_script} { ;# +1 frame
puts "do your thing"
}
As I consider this for test/demo i consider the main use case to be something in the line with if {is_main_script} {puts "do something"}
"un nested" at the end of the file.
If a need to make it more general a dynamic handle for the frame
reference -3
could probably be developed. All though this has covered all my use cases so far.
frame
-3
is used as proc
and if
creates extra frames and to evaluate this we want to check the call before.
dict exists
is used to check if file
exists within the frame. This would indicate the call was from a higher hierarchical level script and would there for not be the "main_script"
The solution if {[info exists ::argv0] && $::argv0 eq [info script]}
works great if run as vivado -source TCLSCRIPT.tcl
but the solution above covers source TCLSCRIPT.tcl
in gui or tcl mode (this is something i often se my self doing when debugging a automation tcl).
I guess this is a niche case. But since I couldn't find any other solution for this problem I wanted to leave this here.
if {[info exists ::argv0] && $::argv0 eq [info script]}
, just to make your script does not throw up in environments that don't runTcl_Main
(e.g., NaviServer, some embedded Tcl). – Polka