在Java中运行Python脚本

2 投票
1 回答
8537 浏览
提问于 2025-04-17 11:04

我想在运行我的Java代码时执行一个Python脚本,因为我的Java代码需要依赖这个Python脚本的输出。目前为止,我尝试过使用jythonc,但没有成功,现在我打算用Java的RuntimeProcess来执行这个Python脚本。

不过,我在调用Python脚本时遇到了问题。我感觉这个脚本根本没有被调用,因为从一个页面跳转到下一个页面的时间不到几秒钟……

问题可能出在我调用Python脚本的方式上吧?我是在一个网页应用程序中运行这个脚本……

以下是我的一些代码:

    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....

    }

1 个回答

3

与其用一个字符串来表示命令,不如把它分成几个部分,放到一个字符串数组里。我觉得不需要写 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();

我没有处理输入/输出流,因为这个脚本/应用不需要输入,只在完成时输出一些内容,没什么重要的。对你来说可能情况会不同。

撰写回答