Parsing command line using argc and argv in expect

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-31 01:55:10

问题


I have an expect routine, which needs to spawn a process and pass the command line arguments I passed to the expect routine to the spawned process.

My expect routine has the following line

spawn myProcess $argv

and when I call my expect routine I call it from the command line as follows

expect myRoutine <arg1> <arg2> <arg3>

When I do this, expect throws the following error

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

However if I change my expect routine as follows

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

myProcess is spawned without any errors. However this is not useful to me, as I cannot guarantee that I would always have three arguments passed to the expect routine.

How do I pass command line arguments from the command line of a unix shell to the spawned process in expect?


回答1:


If you are not sure about the number of arguments which is going to be passed, then, you can make use of eval or argument expansion operator {*}.

If your Tcl's version is 8.5 or above,

spawn <program-name> {*}$argv

Else,

eval spawn <program-name> $argv

Lets consider the following Tcl program

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"

This program will receive any number of command line arguments. To run this program, we execute the following command in the shell

dinesh@PC:~/stackoverflow$ tclsh cmdlinearg STACK OVER FLOW

which will give output as

0 : STACK
1 : OVER
2 : FLOW
THE END

Now, lets write one more program which will spawn this program along with any number of command line arguments.

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

If suppose, you want to pass your program name itself as an argument, that is also possible.

# 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


来源:https://stackoverflow.com/questions/30206430/parsing-command-line-using-argc-and-argv-in-expect

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!