Running Python scripts in Java
Question: I'm trying to run a python script during the execution of my java code,
because it will depend on the output received from the python script. So far
I've tried using jythonc, unfortunately to no success, and now im trying to
use the java
[Runtime](http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Runtime.html)
and java
[Process](http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Process.html)
to execute the python script.

Now I've run into a problem when trying to call the python script. I feel as
though it doesn't even call the script because it takes less than a couple
seconds to get to the next page....

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

Here is some of 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....
    
        }
    


Answer: Instead of String for the command, split it to chunks and make a String[]. No
need to state `cmd /c`, I think.

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 the Input/Output streams because the script/app doesn't require
input, and outputs only when finished, nothing important. Which might not be
the case for you.

