在期望中使用argc和argv解析命令行 [英] Parsing command line using argc and argv in expect

查看:176
本文介绍了在期望中使用argc和argv解析命令行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Expect例程,它需要产生一个进程并将传递给Expect例程的命令行参数传递给产生的进程.

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时没有任何错误.但是,这对我没有用,因为我不能保证总是将三个参数传递给Expect例程.

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.

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

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

推荐答案

如果不确定要传递的参数数量,则可以使用eval或参数扩展运算符.

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 {*}.

如果您的Tcl版本是8.5或更高版本,

If your Tcl's version is 8.5 or above,

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"

该程序将接收任意数量的命令行参数.要运行该程序,我们在外壳中执行以下命令

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

将输出为

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

这篇关于在期望中使用argc和argv解析命令行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆