In one executable TCL script I'm defining a variable that I'd like to import in another executable TCL script. In Python one can make a combined library and executable by using the following idiom at the bottom of one's script:
# Library
if __name__ == "__main__":
# Executable that depends on library
pass
Is there something equivalent for TCL? There is for Perl.
The equivalent for Tcl is to compare the ::argv0
global variable to the result of the info script
command.
if {$::argv0 eq [info script]} {
# Do the things for if the script is run as a program...
}
The ::argv0
global (technically a feature of the standard tclsh
and wish
shells, or anything else that calls Tcl_Main
or Tk_Main
at the C level) has the name of the main script, or is the empty string if there is no main script. The info script
command returns the name of the file currently being evaluated, whether that's by source
or because of the main shell is running it as a script. They'll be the same thing when the current script is the main script.
As mrcalvin notes in the comments below, if your library script is sometimes used in contexts where argv0
is not set (custom shells, child interpreters, embedded interpreters, some application servers, etc.) then you should add a bit more of a check first:
if {[info exists ::argv0] && $::argv0 eq [info script]} {
# Do the things for if the script is run as a program...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With