gpt4 book ai didi

java - Groovy/Java 进程管理拦截/监听输出

转载 作者:行者123 更新时间:2023-11-30 12:01:02 25 4
gpt4 key购买 nike

Groovy 有一个很好的流程执行引擎,我想使用它。
有一个方法 consumeProcessOutput 可以完成所有必要的工作。但我想要的是在每次 consumeProcessOutput 调用 appendout 实例时注入(inject)我的附加功能.

public class ProcessExecutor {
static public void execute(IOutput output, String processName) {
def process = processName.execute()

def out = new StringBuffer()
process.consumeProcessOutput(out, out)

process.waitFor()
}
}

我知道

use (MyStringBufferIntercept) {
process.consumeProcessOutput(out, out)
}

但它们似乎只适用于当前线程,consumeProcessOutput 会创建额外的线程。

那么有没有办法监听行添加并调用output.addLine(line)output.addErrorLine(line)

到目前为止,我只有一种解决方案,当错误输出与正常输出相当快时效果不佳:顺序更改。

  def process = processName.execute()

def inThread = Thread.start {
process.in.eachLine{ line -> output.addLine(line)}
}

def errThread = Thread.start {
process.err.eachLine{ line -> output.addErrorLine(line)}
}

inThread.join()
errThread.join()

process.waitFor()

我同意 Java 解决方案。但我倾向于认为 groovy 的必须更优雅。

最佳答案

我不喜欢 Groovy 使用的从 process.in 和 process.err 读取并写入 process.out 的约定。 Javadocs 应该更清楚。看起来 errout 是同类中的两个,in 是奇怪的 out。

由于您将进程的 stdout 和 stderr 多路复用到单个输出字符串中,所以个别行可能会出现乱码是对的。我不相信您可以将 synchronized 关键字与闭包一起使用,因此也许可以执行与下面的代码类似的操作,但可以使用锁定机制或者将大纲闭包包装在同步方法中。

class P {
static public void execute( String processName) {
def process = processName.execute()
def output = new StringBuffer()

def outline = { line -> output += line + '\n' }

def inThread = Thread.start {
process.in.eachLine{ outline it }
}

def errThread = Thread.start {
process.err.eachLine{ outline it }
}

inThread.join()
errThread.join()
process.waitFor()
println output
}
}

def p = new P();
p.execute("ls -l");

关于java - Groovy/Java 进程管理拦截/监听输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1252212/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com