让Python将多个值返回给Java

时间:2015-12-09 23:09:19

标签: java python

我使用this link中的信息编写下面的代码来运行Python脚本并让它返回一个返回的字符串:

public static void Option_2_Output()
    {
        Scanner Option2_Input = new Scanner(System.in);

        System.out.println("");
        System.out.println("===============================================");
        System.out.println("          Testing Means of Two Groups          ");
        System.out.println("===============================================");
        System.out.println("");

        String Option2_program = "python";
        String Option2_path = "C:\\PathtoScript\\Python_Test.py";

        try{

            String Option2_datapath;
            System.out.print("Please type the location of your Data : ");
            Option2_datapath = Option2_Input.next();

            ProcessBuilder Option2_process = new ProcessBuilder(Option2_program,Option2_path,"" + Option2_datapath);
            Process Option2_Output = Option2_process.start();

            BufferedReader in = new BufferedReader(new InputStreamReader(Option2_Output.getInputStream()));
            String Option2_Final = new String(in.readLine());
            System.out.println(Option2_Final);
            }catch(Exception e){
                System.out.println(e);
            }

    }

对象Option2_Final将Python脚本中的最后一个打印输出作为字符串传回。如何获得多个值?

1 个答案:

答案 0 :(得分:0)

只有一行正在流式传输,因为只使用了一个readLine()功能。可以编写for循环来搜索每个额外的行,或者可以为您想要传回的每一行创建对象:

BufferedReader in = new BufferedReader(new InputStreamReader(Option2_Output.getInputStream()));
            String Option2_Final_1 = new String(in.readLine()); //Line 1
            String Option2_Final_2 = new String(in.readLine()); //Line 2
            System.out.println(Option2_Final_1); //Print Line 1
            System.out.println(Option2_Final); //Print Line 2