0

I'm trying to compile a python file from a java program. When I pass the file name directly it works fine. But when i try to pass a string containing the file name in the function I get an error. I need to pass a string containing the file name because I get the path from another function. And I split the path to get the file name. Can anyone help me in achieving this?

Have a look at what I have tried so far:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

public class Python_Compiler {
    static String newName = null;
    static String r2;
    static String result;
    public static void main(String args[]) throws IOException{
        InputStream inStream = null;
        OutputStream outStream = null;

        String filepath = "C:\\Hello.py";

          String p = filepath;
          System.out.println(p);
          int pos1 = p.lastIndexOf("\\");
          int pos2 = p.lastIndexOf(".py");
          result = p.substring(pos1+1, pos2);
          r2 = p.substring(0,pos1);
          System.out.println("PartialPath: "+r2+"\\");
          System.out.println("The file name only: "+result+".py");

        newName = filepath.replaceAll("(\\.\\S+?$)","1$1");
        File originalcopy =new File(newName);

        inStream = new FileInputStream(filepath);
        outStream = new FileOutputStream(originalcopy);

        byte[] buffer = new byte[1024];

        int length;
        //copy the file content in bytes 
        while ((length = inStream.read(buffer)) > 0){

            outStream.write(buffer, 0, length);

        }

        inStream.close();
        outStream.close();
        System.out.println("File is copied successful!");



        String ret = compile();
        System.out.println("Returned String from Inside Log: "+ret);

        int counter = 0;

        while(!ret.equals("Compilation Successful !!!") && counter!=50)
        {

            System.out.println("Your file contains errors");
            String myReturnedErrorDetails = Reggex_Capture.Extracter(ret);
            System.out.println("My Returned Error Details: "+myReturnedErrorDetails);
            String[] splitted = myReturnedErrorDetails.split(" ");

            int lineNumber = Integer.parseInt(splitted[0]);
            System.out.println("Line number: "+lineNumber);
            System.out.println("Error:  "+splitted[1]);
            String theError = splitted[1];
            String myWholeSolution;
            myWholeSolution = Fixer.PythonFix(theError);
            String[] secondSplitted = myWholeSolution.split(" ");
            String mySolution = secondSplitted[1];
            int myPercentage = Integer.parseInt(secondSplitted[0]);
            System.out.println("The solution proposed by the fixer is: "+ mySolution);
            System.out.println("The best percentage returned by the fixer is: "+myPercentage);
            //Python_Replacer.fix(lineNumber,theError, filepath, mySolution);
            Python_Replacer.fix(lineNumber,theError, newName, mySolution);

            counter++;
            ret = compile();


        }



    }
        public static String compile()
        {
            String log="";


            String myDirectory = r2;

             try {
                 String s= null;
               //change this string to your compilers location
                // String fileName = "Hello1.py";
                 Process p = Runtime.getRuntime().exec("cmd /C python result", null, new java.io.File(myDirectory));

             BufferedReader stdError = new BufferedReader(new 
                  InputStreamReader(p.getErrorStream()));
             boolean error=false; 

             log+="";
             while ((s = stdError.readLine()) != null) {
                 log+=s;
                 error=true;
                 //log+="";

             }if(error==false) log+="Compilation Successful !!!";


         } catch (IOException e) {
             e.printStackTrace();
         }
             /*String log2 = log;
             System.out.println("LOG2: "+log2);
             Reggex_Capture.Extracter(log2);*/

            return log;
        }


      public int runProgram() 
        {
            int ret = -1;
           try
             {            
                 Runtime rt = Runtime.getRuntime();
                 Process proc = rt.exec("cmd.exe /c start a.exe");
                 proc.waitFor();
                 ret = proc.exitValue();
             } catch (Throwable t)
               {
                 t.printStackTrace();
                 return ret;
               }
           return ret;                      
        }}

Have a look at the errors:

C:\Hello.py
PartialPath: C:\
The file name only: Hello.py
File is copied successful!
Returned String from Inside Log: python: can't open file 'result': [Errno 2] No such file or directory
Your file contains errors
Received String: python:#can't#open#file#'result':#[Errno#2]#No#such#file#or#directory
Line Number: null
Z atfer while: null
Keywords: null
Error details: null null
My Returned Error Details: null null
    Exception in thread "main" java.lang.NumberFormatException: For input string: "null"
        at java.lang.NumberFormatException.forInputString(Unknown Source)
        at java.lang.Integer.parseInt(Unknown Source)
        at java.lang.Integer.parseInt(Unknown Source)
        at Python_Compiler.main(Python_Compiler.java:66)
Christopher Creutzig
  • 8,656
  • 35
  • 45
  • 1
    can you show what error it throws? I mean the stack trace – asifsid88 Mar 09 '13 at 09:12
  • Exception in thread "main" java.lang.NumberFormatException: For input string: "null" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at Python_Compiler.main(Python_Compiler.java:66) – user2026254 Mar 09 '13 at 09:13
  • So it means that you are not getting any file name? Look it is throwing null pointer exception. As it's not getting any file name then how do you expect it to run that python file – asifsid88 Mar 09 '13 at 09:14
  • But have a look at the string result...The path is split and then I store only the file name that is Hello.py in it. It is the same string that is fed to function Process p = Runtime.getRuntime().exec("cmd /C python result", null, new java.io.File(myDirectory)); – user2026254 Mar 09 '13 at 09:16
  • I think you meant to pass in the variable result to you python command not the string 'result'? – Byron Mar 09 '13 at 09:27
  • The string result holds the file name of the file to be compiled. – user2026254 Mar 09 '13 at 09:35

1 Answers1

2

Process p = Runtime.getRuntime().exec("cmd /C python result", null, new java.io.File(myDirectory));
Should be:
Process p = Runtime.getRuntime().exec("cmd /C python " + result + ".py", null, new java.io.File(myDirectory));

You want to pass in the value of your String called result not the literal 'result'.

Furthermore your myDirectory variable must contain a valid directory like 'C:\' and not just 'C:'. So you may need to modify that variable as so: myDirectory = myDirectory + "\\";

Byron
  • 1,313
  • 10
  • 22