Running Python scripts in Java

I am trying to run a python script while my java code is running, because it will depend on the output from the python script. So far I have tried using jythonc unfortunately with no success and now I am trying to use java Runtime and java Process to run python script.

Now I am facing a problem when trying to call a python script. It seems to me that it doesn't even call the script because it takes less than a couple of seconds to go to the next page ...

Could the problem be with how I am calling the python script ?? I am trying to run this through a web app ...

Here is my code:

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

    }

      

+2


source to share


1 answer


Instead of a command line, split it into chunks and create a [] line. I don't need to specify cmd /c

.

This is a sample code from my application:



//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();

      

I don't handle I / O streams because the script / application doesn't require input, and only outputs when finished, nothing important. What might be wrong for you.

+3


source







All Articles