java中调用python脚本

在java中调用python脚本有三种方式java

【方式一】:python

直接执行Python脚本代码   引用 org.python包函数

1 PythonInterpreter interpreter = new PythonInterpreter();  
2 interpreter.exec("days=('mod','Tue','Wed','Thu','Fri','Sat','Sun'); ");   ///执行python脚本

【方式二】:命令行

执行python .py文件日志

1 PythonInterpreter interpreter = new PythonInterpreter();  
2 InputStream filepy = new FileInputStream("D:\\demo.py"); 
3 interpreter.execfile(filepy);  ///执行python py文件
4 filepy.close();

【方式三】:ip

对于前两种方式可能存在如下问题:get

当python调用第三方函数库的时候,不能调用。可是经过第三种方式能够解决。it

直接上代码:io

1.java代码部分test

public static void Test1() throws Exception {
        //TODO:执行python脚本  
        System.out.println("start python");  
        //需传入的参数  
        String a = "aaa", b = "bbb", c = "ccc", d = "中国";  
//        System.out.println("start;;;" + a);  
        //设置命令行传入参数  
        String[] argv = new String[] { "python", "data/pythonScrip/test1.py", a, b, c, d };  
        Process pr = Runtime.getRuntime().exec(argv);  
        System.err.println("pr:"+pr);
        BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream(),"GBK"));  
        System.err.println("in:"+in);
        String line;  
//        System.err.println(in.lines().count());
        while ((line = in.readLine()) != null) {  
            System.out.println("line:"+line);  
        }  
        in.close();  
        pr.waitFor();  
        System.out.println("end");  
    }

2.python代码部分(test1.py)

import sys  
print("======")
print(sys.argv[0])  
print(sys.argv[1])  
print(sys.argv[2])  
print(sys.argv[3]) 
print(sys.argv[4]) 
3.输出结果

调用第三方函数库案例

1.java代码部分

public static void Test1() throws Exception {
        //TODO:执行python脚本  
        System.out.println("start python");  
        //需传入的参数  
        String a = "F:/6-日志/20170822_主题相关进阶/Demo/w2v_java_call/bd/w2v_bd.model", b = "一带一路";  
//        System.out.println("start;;;" + a);  
        //设置命令行传入参数  
        String[] argv = new String[] { "python", "data/pythonScrip/w2v_java.py", a, b}; 
        Process pr = Runtime.getRuntime().exec(argv);  
        System.err.println("pr:"+pr);
     BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream(),"GBK")); 
        System.err.println("in:"+in);
        String line;  
//        System.err.println(in.lines().count());
        while ((line = in.readLine()) != null) {  
            System.out.println("line:"+line);  
        }  
        in.close();  
        pr.waitFor();  
        System.out.println("end");  
    }

2.Python代码部分

from gensim.models import word2vec   #调用第三方函数库
import sys  
# def get_vector(word,model):
print (sys.argv[0])       #读取动态参数,做为python脚本的输入
print (sys.argv[1])
print (sys.argv[2])
model = word2vec.Word2Vec.load(sys.argv[1])
vector=model[sys.argv[2]]
print(vector)

输出结果

相关文章
相关标签/搜索