在 expect 中使用 argc 和 argv 解析命令行

Parsing command line using argc and argv in expect

我有一个 expect 例程,它需要生成一个进程并将我传递给 expect 例程的命令行参数传递给生成的进程。

我的 expect 例程有以下行

spawn myProcess $argv

当我调用我的 expect 例程时,我从命令行调用它,如下所示

expect myRoutine <arg1> <arg2> <arg3>

当我这样做时,expect 抛出以下错误

Can't open input file <arg1> <arg2> <arg3> for reading

但是,如果我按如下方式更改我的 expect 例程

spawn myProcess [lindex $argv 0] [lindex $argv 1] [lindex $argv 2]

myProcess 生成时没有任何错误。然而,这对我没有用,因为我不能保证我总是将三个参数传递给 expect 例程。

如何将命令行参数从 unix shell 的命令行传递到 expect 中的派生进程?

如果您不确定要传递的参数数量,那么,您可以使用 eval 或参数扩展运算符 {*}.

如果您的Tcl的版本是8.5或以上,

spawn <program-name> {*}$argv

否则,

eval spawn <program-name> $argv

让我们考虑以下 Tcl 程序

cmdlinearg.tcl

#!/usr/bin/tclsh

set count 0;
if { $argc == 0 } {
        puts "No args passed :("
        exit 1
}
foreach arg $argv {
        puts "$count : $arg"
        incr count
}
puts "THE END"

该程序将接收任意数量的命令行参数。为了运行这个程序,我们在shell

执行下面的命令
dinesh@PC:~/Whosebug$ tclsh cmdlinearg STACK OVER FLOW

输出结果为

0 : STACK
1 : OVER
2 : FLOW
THE END

现在,让我们再编写一个程序,它将生成该程序以及任意数量的命令行参数。

MyProgram.tcl

#!/usr/bin/expect

# If your Tcl version is 8.4 or below
eval spawn tclsh $argv
expect eof
# If your Tcl version is 8.5 or above
spawn tclsh {*}$argv
expect eof

如果假设您想将程序名称本身作为参数传递,那也是可以的。

# Taking the first command line arg as the program name and
# using rest of the args to the program
eval spawn [lindex argv 0] [ lrange $argv 0 end ]
expect eof