4

我会提前道歉,我是groovy的新手。我遇到的问题是我有 3 个执行不同功能的 groovy 脚本,我需要从我的主 groovy 脚本中调用它们,使用脚本 1 的输出作为脚本 2 的输入,使用脚本 2 的输出作为脚本 3 的输入。

我试过以下代码:

script = new GroovyShell(binding)
script.run(new File("script1.groovy"), "--p",  "$var" ) | script.run(new File("script2.groovy"), "<",  "$var" )

当我运行上面的代码时,第一个脚本运行成功,但第二个脚本根本没有运行。

脚本 1 使用代码将 int 作为参数"--p", "$var"。这在主脚本中成功运行,使用:script.run(new File("script1.groovy"), "--p", "$var" )- 脚本 1 的输出是一个 xml 文件。

当我script.run(new File("script2.groovy"), "<", "$var" )在主 groovy 脚本中自行运行时,没有任何反应并且系统挂起。

我可以使用从命令行运行脚本 2 groovy script2.groovy < input_file,它工作正常。

任何帮助将不胜感激。

4

2 回答 2

1

您不能将<作为参数传递给脚本,因为当您从命令行运行时,Shell 会处理重定向...

将脚本的输出重定向到其他脚本是出了名的困难,并且基本上依赖于您System.out在每个脚本的持续时间内进行更改(并希望 JVM 中没有其他任何内容会打印并弄乱您的数据)

最好使用如下的 java 进程:

鉴于这 3 个脚本:

script1.groovy

// For each argument
args.each {
  // Wrap it in xml and write it out
  println "<woo>$it</woo>"
}

线长.groovy

// read input
System.in.eachLine { line ->
  // Write out the number of chars in each line
  println line.length()
}

漂亮的.groovy

// For each line print out a nice report
int index = 1
System.in.eachLine { line ->
  println "Line $index contains $line chars (including the <woo></woo> bit)"
  index++
}

然后我们可以编写这样的代码来获得一个新的 groovy 进程来依次运行每个进程,并将输出相互传递(使用or Process 上的重载运算符):

def s1 = 'groovy script1.groovy arg1 andarg2'.execute()
def s2 = 'groovy linelength.groovy'.execute()
def s3 = 'groovy pretty.groovy'.execute()

// pipe the output of process1 to process2, and the output
// of process2 to process3
s1 | s2 | s3

s3.waitForProcessOutput( System.out, System.err )

打印出来:

Line 1 contains 15 chars (including the <woo></woo> bit)
Line 2 contains 18 chars (including the <woo></woo> bit)
于 2012-07-12T08:29:59.293 回答
0
//store standard I/O
PrintStream systemOut = System.out
InputStream systemIn = System.in
//Buffer for exchanging data between scripts
ByteArrayOutputStream buffer = new ByteArrayOutputStream()
PrintStream out = new PrintStream(buffer)
//Redirecting "out" of 1st stream to buffer
System.out = out
//RUN 1st script
evaluate("println 'hello'")
out.flush()
//Redirecting buffer to "in" of 2nd script
System.in = new ByteArrayInputStream(buffer.toByteArray())
//set standard "out"
System.out = systemOut
//RUN 2nd script
evaluate("println 'message from the first script: ' + new Scanner(System.in).next()")
//set standard "in"
System.in = systemIn

结果是:'来自第一个脚本的消息:你好'

于 2017-10-13T23:50:47.193 回答