I'm writing a Tcl开发者_如何转开发 script, and I want to get the directory where the script is saved (Not the current dir, so $env(PWD)
is not what I want).
Is that possible?
When the script is executing directly, you use:
set theDir [file normalize [file dirname [info script]]]
This must be run at the top level of the script or inside a namespace eval
(where you should use variable
instead of set
for technical reasons). In particular, it should not be placed inside a procedure and invoked later because by that point the info script
call will return something else. Thus, a typical package implementation script might look like this:
namespace eval ::samplePackage {
variable theDir [file normalize [file dirname [info script]]]
source $theDir/foo.tcl
source $theDir/bar.tcl
load $theDir/grill[info sharedlibextension]
package provide samplePackage 1.0
}
If this is the main application, you can also use $::argv0
in place of info script
. That will not change throughout the run of your code (unless you manually set it).
Use info script combined with file dirname
I'm not very much up to speed with tcl (anymore)
You'd get the script name as $argv0
I'd simply apply the functions/utilities realpath
followed by dirname
to get it's directory
file normalize [file dirname [info script]]
won't work reliably if you call a script through a relative symlink. I use this to mitigate possible problems:
proc script_dir {} {
set r [info script]
if {![catch {file link $r} symlink]} {
set r [file join [file dirname $r] $symlink]
}
return [file dirname [file normalize $r]]
}
精彩评论