0

我正在尝试从 java 程序编译 python 文件。当我直接传递文件名时,它工作正常。但是当我尝试在函数中传递一个包含文件名的字符串时,我得到一个错误。我需要传递一个包含文件名的字符串,因为我从另一个函数获取路径。我拆分路径以获取文件名。谁能帮助我实现这一目标?

看看我到目前为止所做的尝试:

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;                      
        }}

看看错误:

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)
4

1 回答 1

2

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

你想传入你的 String 的值,result而不是字面的“结果”。

此外,您的myDirectory变量必须包含有效目录,例如“C:\”,而不仅仅是“C:”。因此,您可能需要像这样修改该变量: myDirectory = myDirectory + "\\";

于 2013-03-09T09:42:06.787 回答