0

I'm writing a reporting script that's part of a portable testing package. The user can unzip the package anywhere on their system, which is fine, but it means I can't hardcode a path.

Let's say that on my system, this script lives at C:/projects/testpackage/foo/bar/script.tcl. I need to set a variable, packageLocation, the path to /testpackage. In this example, it would be C:/Projects/testpackage. But when the user gets the package, he or she could put it anywhere, like so:

C:/Users/whatever/testpackage.

So, how can I call two levels up from the location of my currently running script? In Batch, I could do

    :: example.bat
    cd %~dp0
    cd ../..
    set packageLocation=%cd%

In Tcl, I'm lost. I know that the current location of the running script can be called as $::argv0. I've tried using cd ../.., but to no avail. It tries to set packageLocation as "../..C:/Projects/testpackage/foo/bar/script.tcl."

Any help is appreciated. Thanks!

4

1 回答 1

4
set where [file normalize [file dirname [info script]]]
set parts [file split $where]
set pkgloc [file join {*}[lrange $parts 0 end-2]]

应该做你想做的。

它是这样的:

  1. 获取从其中读取当前脚本以进行评估的文件的目录名称,然后对其进行规范化(替换~..)。
  2. 在路径分隔符处拆分获得的完整路径名,生成路径组件列表。
  3. 从路径组件列表中提取一个新列表,该列表包含除最后两个之外的所有路径组件,然后将它们重新连接以生成最终名称。

如果您的 Tcl < 8.5,则必须重写最后一行:

set last [expr {[llength $parts] - 3}]
set pkgloc [eval [list file join] [lrange $parts 0 $last]]
于 2013-08-01T16:49:41.953 回答