【问题标题】:How to use getopts in TCL如何在 TCL 中使用 getopts
【发布时间】:2021-08-26 23:28:41
【问题描述】:

我想使用 get opts 来运行文件名。

我希望能够输入这样的命令:

tclsh -f application_report.txt delete_file.tcl 

然后可以在我的脚本中打印:

application_report.txt 

【问题讨论】:

标签: tcl


【解决方案1】:

您必须先输入脚本的名称,因为它是由tclsh 自己处理的,以知道要运行什么命令。选项随之而来。 (事实上​​,tclsh 本身确实接受少量选项,但您几乎不想提供它们,除非脚本编码的自动检测出错。)

当您使用cmdline package 时,请按以下步骤操作:

脚本:

package require cmdline

# Description of the options
set OPTIONS {
    {f.arg   "output file"}
}

# Part of the usage message; feel free to tweak
set USAGE ": tclsh delete_file.tcl \[options]\noptions:"

# Initialise some defaults; totally not necessary...
dict set opts {
    f "default_file.txt"
}

# Process the options
try {
    array set opts [cmdline::getoptions argv $OPTIONS $USAGE]
} trap {CMDLINE USAGE} {msg} {
    puts stderr $msg
    exit 1
}

# Now, we can just use them; $::argv is everything not processed
set filename $opts(f)
# ...

如何调用:

tclsh delete_file.tcl -f application_report.txt

如果您在脚本顶部使用#! 行,您可能需要调整USAGE 行。

【讨论】:

    猜你喜欢
    • 2016-07-14
    • 2011-11-30
    • 1970-01-01
    • 2013-05-05
    • 1970-01-01
    • 2018-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多