为什么:: cmdline :: getoptions会引发错误?

时间:2019-01-09 05:52:03

标签: tcl getopt

为什么要执行以下代码:

#!/usr/bin/env tclsh
package require cmdline;
set options {{d.arg "" "destination directory"}}
set usage ": $::argv0 \[options] filename ...\noptions:"
set params [::cmdline::getoptions ::argv $options $usage]

执行./main.tcl -help时引发以下错误?

main : ./main.tcl [options] filename ...
options:
 -d value             destination directory <>
 -help                Print this message
 -?                   Print this message

    while executing
"error [usage $optlist $usage]"
    (procedure "::cmdline::getoptions" line 15)
    invoked from within
"::cmdline::getoptions ::argv $options $usage"
    invoked from within
"set params [::cmdline::getoptions ::argv $options $usage]"
    (file "./main.tcl" line 8)

它应该显示使用情况信息,但是我没想到以后会出现错误。我做错什么了吗?

1 个答案:

答案 0 :(得分:1)

根据我对docs(重点是我的)的理解:

  

对选项-?-帮助-的理解是隐含的。 前两个中止选项处理通过抛出错误并强制生成用法消息 ,而最后一个中止选项处理则没有错误,所有参数都用于常规处理,即使以破折号开头也是如此。

使用-帮助-?始终引发错误。

在文档的下面,您可以看到一个示例,其中try { ... } trap { ... }::cmdline::getoptions结合使用,这可能是您可能想要的方式:

try {
    array set params [::cmdline::getoptions ::argv $options $usage]
} trap {CMDLINE USAGE} {msg o} {
    # Trap the usage signal, print the message, and exit the application.
    # Note: Other errors are not caught and passed through to higher levels!
    puts $msg
    exit 1
}