简体   繁体   English

重定向Nashorn标准输出和标准错误

[英]Redirect Nashorn stdout and stderror

Trying to redirect the Nashorn scripting engine from within a Java class. 尝试从Java类中重定向Nashorn脚本引擎。 This is how I'm initializing it right now. 这就是我现在正在初始化的方式。 I'd like to redirect any output from the scripts the engine runs. 我想重定向引擎运行的脚本的任何输出。

String[] nashornArgs = new String[] {"-strict", "--no-java",
                "--no-syntax-extensions", "-dump-on-error"};
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
ScriptEngine engine = factory.getScriptEngine(nashornArgs);

I know Nashorn has the following args (below) but I'm not sure how to initialize correctly and in a manner where any output is discarded by the program. 我知道Nashorn具有以下args(如下),但是我不确定如何正确初始化以及如何以程序丢弃任何输出的方式进行初始化。 Maybe create a temp file and then delete the temp file once the engine is done? 也许创建一个临时文件,然后在引擎完成后删除该临时文件? Seems messy to me. 对我来说似乎很混乱。


--stderr (Redirect stderr to a filename or to another tty, eg stdout) --stderr(将stderr重定向到文件名或另一个tty,例如stdout)

param: output console 参数:输出控制台

--stdout (Redirect stdout to a filename or to another tty, eg stderr) --stdout(将stdout重定向到文件名或另一个tty,例如stderr)

param: output console 参数:输出控制台

You can redirect output like this: 您可以像这样重定向输出:

package com.example;

import java.io.StringWriter;

import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

import jdk.nashorn.api.scripting.NashornScriptEngineFactory;

public class Nashorn {
    public static void main(String[] args) throws ScriptException {
        String[] arguments = new String[] {"-strict", "--no-java", "--no-syntax-extensions", "-dump-on-error"};
        NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
        ScriptEngine engine = factory.getScriptEngine(arguments);
        StringWriter sw = new StringWriter();
        ScriptContext context = engine.getContext();
        context.setWriter(sw);
        context.setErrorWriter(sw);
        engine.eval("print('hello world')");
        System.out.println("redirected output: " + sw);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM