我有一个期望例程,它需要生成一个进程并将我传递给期望例程的命令行参数传递给生成的进程。
我的期望例程有以下几行
spawn myProcess $argv
Run Code Online (Sandbox Code Playgroud)
当我调用我的期望例程时,我从命令行调用它,如下所示
expect myRoutine <arg1> <arg2> <arg3>
Run Code Online (Sandbox Code Playgroud)
当我这样做时,期望抛出以下错误
Can't open input file <arg1> <arg2> <arg3> for reading
Run Code Online (Sandbox Code Playgroud)
但是,如果我按如下方式更改我的期望例程
spawn myProcess [lindex $argv 0] [lindex $argv 1] [lindex $argv 2]
Run Code Online (Sandbox Code Playgroud)
myProcess 生成时没有任何错误。然而,这对我没有用,因为我不能保证我总是将三个参数传递给期望例程。
如何将命令行参数从 unix shell 的命令行传递到 expect 中生成的进程?
如果您不确定要传递的参数数量,则可以使用eval或 参数扩展运算符{*}。
如果您Tcl的版本是 8.5 或以上,
spawn <program-name> {*}$argv
Run Code Online (Sandbox Code Playgroud)
别的,
eval spawn <program-name> $argv
Run Code Online (Sandbox Code Playgroud)
让我们考虑以下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"
Run Code Online (Sandbox Code Playgroud)
该程序将接收任意数量的命令行参数。为了运行这个程序,我们在 shell 中执行以下命令
dinesh@PC:~/stackoverflow$ tclsh cmdlinearg STACK OVER FLOW
Run Code Online (Sandbox Code Playgroud)
这将使输出为
0 : STACK
1 : OVER
2 : FLOW
THE END
Run Code Online (Sandbox Code Playgroud)
现在,让我们再编写一个程序,该程序将生成该程序以及任意数量的命令行参数。
我的程序
#!/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
Run Code Online (Sandbox Code Playgroud)
如果假设您想将程序名称本身作为参数传递,那也是可能的。
# 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
Run Code Online (Sandbox Code Playgroud)