搜索
您的当前位置:首页正文

java 程序运行 Python 脚本

来源:二三娱乐

有两种方式:

Runtime.getRuntime().exec

此种方式参数貌似应该在一个string中,原来传了一个string array,结果waitFor返回值一直是1.网上查返回0才是正确的,但是没有找到返回1是什么问题。访问google实在太慢,找不到原因,放弃了,总之把参数放在一行里解决了问题- -


/**
 *
 * @param appPathName
 */
private static void executePythonScriptToGenerateEdgeJsonUsingRuntimeProcess(String appPathName) {
    try{
        //Different from ProcessBuilder, exec should put command in one line instead of list<String>
        Process process = Runtime.getRuntime().exec("python "+edgeBuilderPath+" "+appPathName);

        BufferedReader stdOut=new BufferedReader(new InputStreamReader(process.getInputStream()));
        String s;
        while((s=stdOut.readLine())!=null){
            System.out.println(s);
        }

        int result=process.waitFor();
        process.destroy();
    }
    catch (Exception e){
        System.out.println(e.getMessage());
    }
    catch (Throwable t) {
        t.printStackTrace();
    }
}

ProcessBuilder

把所有参数放在一个string里,结果给我返回:
java.io.ioexception cannot run program no such file or directory ProcessBuilder
在命令行执行没有问题,结果找了若干帖子,才发现应该传list string- -
和上述方法相反

/**
 * new ProcessBuilder can work
 * @param script
 */
public static void executePythonScriptToGenerateEdgeJson(String appPathName) {
    try {
        List<String> command=new LinkedList<String>();
        command.add("python");
        command.add(edgeBuilderPath);
        command.add(appPathName);
        //ProcessBuilder need to separate string into list string not one long string
        ProcessBuilder pb = new ProcessBuilder(command);
        Process p = pb.start(); // Start the process.
        int result=p.waitFor(); // Wait for the process to finish.
        System.out.println("Script executed successfully"+result);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Top