【问题标题】:Running Scripts with Runtime.exec through Java WebApp通过 Java WebApp 使用 Runtime.exec 运行脚本
【发布时间】:2012-02-19 17:49:37
【问题描述】:

我创建了一个 Java WebApp,更像是我使用 HTTPServlets 来运行一些 Java 代码,具体取决于用户输入的内容。我可以从用户那里获取信息,将其传递给我的 java 程序,然后再将其传递回界面,这没有问题。变得困难(而且相当烦人)的是尝试使用用户输入的信息并调用外部脚本(处理和回答用户请求所需要的)。我已经在一个常规的独立 java 应用程序中测试了我的那部分代码,它工作正常,但是每当我尝试通过我的网络应用程序运行它时,它要么永远挂起(我不知道它是否真的在运行脚本)或甚至不运行脚本,只是继续到结果页面。

这是我的代码:

 public void runScript() throws InterruptedException{

    try{

        chkPy = new BufferedWriter(new FileWriter("Log.txt"));

        chkPy.write("Running Python Script");
        chkPy.newLine();

        runtime = Runtime.getRuntime();
        p = runtime.exec("cmd /c run.bat > python_results.log");

        BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
        BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

        String line = "";
        while ((line = stdInput.readLine()) != null) {
      chkPy.write(line);
              chkPy.newLine();
        }
        while ((line = stdError.readLine()) != null) {
                chkPy.write(line);
                chkPy.newLine();
        }


        int exitVal = p.waitFor();

        chkPy.write("Exit Value" +exitVal);
        chkPy.flush();
        chkPy.close(); 

    }catch(IOException ex){

    }
}

更新

Netbeans 带有 GlassFish 服务器的实现,听起来很愚蠢,这不是我第一次看到的地方(我现在才看到),但脚本正在编译。但似乎我遇到了另一个问题,因为现在 webapp 死锁,即使脚本已经完成了文件的编写......我该如何解决这个问题??

【问题讨论】:

    标签: java python web-applications runtime.exec


    【解决方案1】:

    在分离的线程中读取输入和错误流。

    或使用 Commons Exec 库:http://commons.apache.org/exec/

    【讨论】:

    • 问题是我正在使用 netbeans,它会自动启动 GlassFish 服务器和所有输出......所以我有点想通了,但感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 2016-02-28
    • 1970-01-01
    • 2012-05-31
    • 1970-01-01
    相关资源
    最近更新 更多