【问题标题】:Running Python scripts in Java在 Java 中运行 Python 脚本
【发布时间】:2012-01-25 16:46:13
【问题描述】:

我正在尝试在执行我的 java 代码期间运行 python 脚本,因为它取决于从 python 脚本接收到的输出。到目前为止,我已经尝试使用 jythonc,不幸的是没有成功,现在我尝试使用 java Runtime 和 java Process 来执行 python 脚本。

现在我在尝试调用 python 脚本时遇到了问题。我觉得它甚至没有调用脚本,因为它只需不到几秒钟就可以进入下一页......

问题可能是我如何调用 python 脚本?我正在尝试通过 Web 应用程序运行它...

这是我的一些代码:

    String run = "cmd /c python duplicatetestingoriginal.py" ;

    boolean isCreated = fwr.writeFile(BugFile, GD, 500, true, 5, "LET");

    if(isCreated){
        try{
            r = Runtime.getRuntime();
            p = r.exec(run);
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
    BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

    String line = "";
    while ((line = stdInput.readLine()) != null) {
                System.out.println(line);
    }
    while ((line = stdError.readLine()) != null) {
               errorW.write(line);
    }

            int exitVal = p.waitFor();
            arrayList = fwr.readResults();
        }catch(Exception e){

        }
    }
    else{
        // troubleshoot....

    }

【问题讨论】:

  • 您在 Windows 下运行,是吗? 'python' 在你的 PATH 上吗?如果在 Start -> Run... 中键入 cmd /c python duplicatetestingoriginal.py 会发生什么?
  • 您可能还想重新考虑您是如何阅读 stdInput/stdError 的。请参阅“当 Runtime.exec 不会时”:javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
  • 是的,我在 Windows 中运行,python 在我的 PATH 中。当我在 cmdline 或 Run 中键入代码时,代码就会运行
  • 运行 Java 代码时,duplicatetestingoriginal.py 是否可能不在当前目录中?也许把完整的绝对路径放在那里?
  • 另一个想法:你catch (Exception e)然后放下它。也许正在抛出异常?在调试时添加e.printStackTrace(); 不会有什么坏处。

标签: java python process runtime


【解决方案1】:

代替命令的字符串,将其拆分为块并创建一个字符串[]。我认为不需要声明cmd /c。

这是来自我的应用程序的示例代码:

//Running on windows
command = new String[4];
command[0]=directory.getCanonicalPath()+"/data/ExtenalApp.exe"; //extenal commandline app, not placed in path, but in subfolder
command[1]=directory.getCanonicalPath()+"/data/SomeFile.txt"; //file needed for the external app, sent as an argument
command[2]=arg1; //argument for the app
command[3]=arg2; //argument for the app

//Running on Mac
command = new String[6];
command[0]="python";
command[1]=directory.getCanonicalPath()+"/data/wp.py"; //path to the script
command[2]="-F"; //argument/Flag/option
command[3]="--dir="+path; //argument/option
command[4]="--filename="+filename; //argument/option 
command[5]=argument; //argument/option


Process process = Runtime.getRuntime().exec(command);
process.waitFor();
process.destroy();

我不处理输入/输出流,因为脚本/应用程序不需要输入,只有在完成时才输出,没什么重要的。对你来说可能不是这样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-13
    • 2015-10-06
    • 1970-01-01
    • 2017-01-06
    • 2018-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多