java里面嵌套执行python脚本

2021-01-29 05:13

阅读:414

标签:col   word   span   nbsp   bsp   text   comm   current   keyword   

方法一:通过RunTime.getRuntime().exec(shellScript)

    //方式1 不带参数
       String classpath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        String shellScript = null;
        if (System.getProperties().getProperty("os.name").toLowerCase().indexOf("windows") != -1){
            shellScript = String.format("python template.py", classpath.substring(1));
        }else {
            shellScript = String.format("python3 template.py", classpath.substring(1),classpath);
        }
        Runtime rt = Runtime.getRuntime();
        

      

    //方式2 带参数

        String command = "D:\\calculator_simple.py"; 
        String num1 = "1"; 
        String num2 = "2"; 
        String[] cmdArr = new String[] {exe, command, num1, num2}; 
        Process process = Runtime.getRuntime().exec(cmdArr); 
        InputStream is = process.getInputStream(); 
        DataInputStream dis = new DataInputStream(is); 
        String str = dis.readLine(); 
        process.waitFor(); 
        System.out.println(str); //此处输出3

        #calculator_simple.py脚本
        # coding=utf-8
        from sys import argv
        num1 = argv[1]
        num2 = argv[2]
        sum = int(num1) + int(num2)
        print sum        

方法2:通过Jython调用,这种方式不太推荐,记得调用selenium的库会报No module found,可是明明引用了,而且java社区不太喜欢这种强耦合的方式调用Python,所以官网也不怎么更新了,在微服务架构大行其道的今天,这种程序间嵌套调用的方式将会逐渐被淘汰

    String python = "D:\\simple_python.py";
    PythonInterpreter interp = new PythonInterpreter();
    interp.execfile(python);

 

 

//方式1 不带参数
String command = "D:\\calculator_simple.py"; 
String num1 = "1";
String num2 = "2";
String[] cmdArr = new String[] {exe, command, num1, num2};
Process process = Runtime.getRuntime().exec(cmdArr);
InputStream is = process.getInputStream();
DataInputStream dis = new DataInputStream(is);
String str = dis.readLine();
process.waitFor();
System.out.println(str);

java里面嵌套执行python脚本

标签:col   word   span   nbsp   bsp   text   comm   current   keyword   

原文地址:https://www.cnblogs.com/feibazhf/p/14337603.html


评论


亲,登录后才可以留言!