首页 > 技术文章 > Java调用Python的两种方式

kikyoqiang 2020-12-26 16:00 原文

1、前言

在与第三方程序或语言进行交互时,需要Java调用

2、使用Runtimeexec函数

在使用时需注意img = sys.argv[1]取下标为1的参数

package com;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Java通过Runtime.exec()调用python
 */
public class CallPythonExec {
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static void main(String[] args) {
        run();
    }

    public static void run() {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                String exe = "python";
                // String command = "/usr/local/python/videoRec.py";
                String command = "D:\\VideoRec\\Python\\videoRec.py";
                String param = sdf.format(new Date());
                String[] args1 = new String[]{exe, command, param};
                System.out.println("result=" + callPython(args1));
            }
        }, 0, 1000);
    }

    private static String callPython(String... param) {
        String result = "";
        Process process = null;
        BufferedReader reader = null;
        try {
            process = Runtime.getRuntime().exec(param);
            reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                if (!"".equals(line)) {
                    result = line;
                }
            }
            // System.out.println("waitFor=" + process.waitFor());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (process != null) process.destroyForcibly();
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return result;
        }
    }

    /* python 代码
    img = sys.argv[1] 参数需下标为1


import sys

def fun(img):
    #print("python print="+img)
    #print(img)
    return img

if __name__ == '__main__':
    img = sys.argv[1]
    result=fun(img)
    print(result)


    */
}

3、使用Jython调用python

在使用时需注意img = sys.argv[0]取下标为0的参数

package com;

import org.python.core.PyFunction;
import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.util.PythonInterpreter;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Java通过Jython调用python
 */
public class CallPythonJython {
    private static PyFunction pyFunction = null;
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static void main(String[] args) {
        run();
    }

    public static void run() {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                String result = callPython(new PyString(sdf.format(new Date())));
                System.out.println(result);
            }
        }, 0, 1000);
    }

    public static String callPython(PyObject... params) {
        if (pyFunction == null) {
            PythonInterpreter interpreter = new PythonInterpreter();
            // interpreter.execfile("/usr/local/python/videoRec.py");
            interpreter.execfile("D:\\VideoRec\\Python\\videoRec.py");
            // 第一个参数为期望获得的函数(变量)的名字,第二个参数为期望返回的对象类型
            pyFunction = interpreter.get("fun", PyFunction.class);
        }
        PyObject pyobj = pyFunction.__call__(params);
        return pyobj.asString();
    }

    /* python 代码
    img = sys.argv[0] Jython调用参数需下标为0


import sys

def fun(img):
    #print("python print="+img)
    #print(img)
    return img

if __name__ == '__main__':
    img = sys.argv[0]
    result=fun(img)
    print(result)


    */
}

推荐阅读