zoukankan      html  css  js  c++  java
  • Java利用Runtime调用Python脚本

    使用Runtime.getRuntime()执行python脚本文件

    在本地的D盘创建一个python脚本,文件名字为Runtime.py,文件内容如下:

    print('RuntimeDemo')

    注意:如果Python脚本里面有文件路径,则要进行转换,比如 ./ 指的是javaweb项目的当前项目路径,而不是Python脚本的当前路径。

    创建RuntimeFunction.java类,内容如下:

     1 package com.test;
     2 
     3 import java.io.BufferedReader;
     4 import java.io.IOException;
     5 import java.io.InputStreamReader;
     6 
     7 public class RuntimeFunction {
     8     public static void main(String[] args) {
     9         Process proc;
    10         try {
    11             proc = Runtime.getRuntime().exec("python D:\Runtime.py");
    12             BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    13             String line = null;
    14             while ((line = in.readLine()) != null) {
    15                 System.out.println(line);
    16             }
    17             in.close();
    18             proc.waitFor();
    19         } catch (IOException e) {
    20             e.printStackTrace();
    21         } catch (InterruptedException e) {
    22             e.printStackTrace();
    23         } 
    24     }
    25 }

    运行结果如下:

    调用python脚本中的函数

    在本地的D盘创建一个python脚本,文件名字为add.py,文件内容如下:

    def add(a,b):
        return a + b

    创建Function.java类,内容如下:

     1 package com.test;
     2 
     3 import org.python.core.PyFunction;
     4 import org.python.core.PyInteger;
     5 import org.python.core.PyObject;
     6 import org.python.util.PythonInterpreter;
     7 
     8 public class Function {
     9     
    10     public static void main(String[] args) {
    11         PythonInterpreter interpreter = new PythonInterpreter();
    12         interpreter.execfile("D:\add.py");
    13                 
    14         // 第一个参数为期望获得的函数(变量)的名字,第二个参数为期望返回的对象类型
    15         PyFunction pyFunction = interpreter.get("add", PyFunction.class);
    16         int a = 5, b = 10;
    17         //调用函数,如果函数需要参数,在Java中必须先将参数转化为对应的“Python类型”
    18         PyObject pyobj = pyFunction.__call__(new PyInteger(a), new PyInteger(b)); 
    19         System.out.println("the anwser is: " + pyobj);
    20     }
    21 
    22 }

    运行结果如下:

    中文乱码问题解决

    用Runtime.getRuntime.exec()调用Python脚本时,Java端捕获脚本有中文输出时,输出的中文可能会是乱码,因为Python安装在Windows环境下的默认编码格式是GBK。

    解决方法:

    在被调用的脚本的开头增加如下代码,一定要添加到其他依赖模块import之前:

    import io
    import sys
     
    sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

    参考文章:

    java调用python的几种用法(看这篇就够了)

    Java利用Runtime调用Python脚本时的中文乱码问题

  • 相关阅读:
    Oracle误删除数据和表的恢复办法包括truncate
    SQL中简单函数介绍
    SQL中的null
    oracle数据库实例后台进程
    常用查询视图
    AIX 常用命令积累(未完待续)
    查询当前用户下的表/查询某一个用户的表
    查询统计运行和采控库里所有用户下的记录数大于5000万条的表
    使用orace数据库自带的sqldeveloper
    PL/SQL Developer
  • 原文地址:https://www.cnblogs.com/FengZeng666/p/14366138.html
Copyright © 2011-2022 走看看