在java中调用python程序

问题描述:前段时间在项目中需要计算语义相似度,项目是java工程,但是计算语义相似度是基于python写的,因为这其中又涉及到tensorflow,numpy等,所有又不能直接转成java的,所以如果要实时计算的话必须在java中调用python的程序,在网上搜了搜,找到了解决方案,这里我写了例子大概展示一下。

python程序如下:

#encoding=utf-8
from sys import argv

s = argv[1]
print("hello "+s)

java程序如下:

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;

public class Java2Python {
    public static void main(String[] args) throws IOException, InterruptedException {
        String exe = "python";
        String command = "E:\hello.py";
        String num1 = "world";
        String[] cmdArr = new String[] {exe, command, num1};
        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);
    }
}

执行结果如下:hello world

原文地址:https://www.cnblogs.com/earthhouge/p/10165606.html