I'm trying to retrieve the version of python form java using ProcessBuilder.

The command i'm using is:

{process = new ProcessBuilder("C:\\Python27\\python.exe", "-V")}

This command does not return anything.

I'm almost sure this is the correct syntax to retrieve the python version,

{process = new ProcessBuilder("C:\\Python27\\python.exe", "-h")} 

returns the python help as expected, but python -V does not return the python version.

package com.x.x.precheck.python;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;

public class Test {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub

    Process process = null;
    try {
        process = new ProcessBuilder("C:\\Python27\\python.exe", "-V")
                .start();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    InputStream is = process.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line;

    System.out.printf("Output of running %s is:", Arrays.toString(args));

    try {
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
}
有帮助吗?

解决方案

It's because, strangely enough, the python2.7 version is displayed in stderr. in python version 3.4 this behaviour will change see http://bugs.python.org/issue18338

so instead of

InputStream is = process.getInputStream();

you should call

InputStream stderr = process.getErrorStream ();

其他提示

I tested your code with other programs.It all works fine.for example i gave octave instead of the python and It printed out.Its weird.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top