如何在Java项目中执行python代码

  最近在做一个项目,需要在java里调用python代码,网上找了一些资料,想简单总结一下。可是我对java运行机制并不是很了解,所以只能说说怎么做。


1. 安装Jython (什么是Jython)


下载安装jython_installer-2.5.0.jar, 安装完毕后需要把其中的jython.jar复制到项目中的lib中(引入jar包);


2. 编写简易python代码


import java.io.IOException;    
import org.python.util.PythonInterpreter;      
public class test {      
    public static void main(String args[]) throws IOException {      
        PythonInterpreter interpreter = new PythonInterpreter();     
        // 运行python语句     
        interpreter.exec("a = \"hello, Jython\"");      
        interpreter.exec("print a");      
           
    }     
}     
结果报错:console: Failed to install '': java.nio.charset.UnsupportedCharsetException: cp0.


把上述代码改成下面形式即可

import java.io.IOException;    
import org.python.util.PythonInterpreter;      
public class test {      
    public static void main(String args[]) throws IOException {  
<span class="space" style="white-space:pre;display:inline-block;text-indent:2em;line-height:inherit"> </span><span class="space" style="white-space:pre;display:inline-block;text-indent:2em;line-height:inherit"> </span><span class="space" style="white-space:pre;display:inline-block;text-indent:2em;line-height:inherit"> </span><span class="space" style="white-space:pre;display:inline-block;text-indent:2em;line-height:inherit"> </span>Properties props = new Properties();  
            props.put("python.console.encoding", "UTF-8"); // Used to prevent: console: Failed to install '': java.nio.charset.UnsupportedCharsetException: cp0.  
            props.put("python.security.respectJavaAccessibility", "false"); //don't respect java accessibility, so that we can access protected members on subclasses  
            props.put("python.import.site","false");  
            Properties preprops = System.getProperties();  
            PythonInterpreter.initialize(preprops, props, args);      
        PythonInterpreter interpreter = new PythonInterpreter();     
        // 运行python语句     
        interpreter.exec("a = \"hello, Jython\"");      
        interpreter.exec("print a");      
           
    }     
}     
3. 执行python文件


把上述执行python语句的代码改为

interpreter.execfile("C:/Users/JingYi/Desktop/hello.py");  ///执行python py文件  

4. 执行python文件并传参


package jp;  
import java.util.Properties;  
import org.python.core.Py;    
import org.python.core.PyException;  
import org.python.core.PyObject;  
import org.python.core.PyString;  
import org.python.util.PythonInterpreter;  
  
public class main {  
  
        public static void main(String args[]) {  
          
            Properties props = new Properties();  
            props.put("python.console.encoding", "UTF-8"); // Used to prevent: console: Failed to install '': java.nio.charset.UnsupportedCharsetException: cp0.  
            props.put("python.security.respectJavaAccessibility", "false"); //don't respect java accessibility, so that we can access protected members on subclasses  
            props.put("python.import.site","false");  
            Properties preprops = System.getProperties();  
            String[] arguments ={ "string1", "string2","string3"};  
            PythonInterpreter.initialize(preprops, props, arguments);  
            PythonInterpreter interpreter = new PythonInterpreter();  
            interpreter.exec("import sys");  
            interpreter.exec("sys.path.append('E:/Python27/Lib')"); // 加载第三方包的路径  
            interpreter.exec("sys.path.append('E:/Python27/Lib/site-packages')"); // 加载第三方包的路径  
            interpreter.exec("sys.path.append('E:/Python27/Lib/site-packages/numpy/lib')"); // 加载第三方包的路径  
              
            interpreter.execfile("C:/Users/JingYi/Desktop/hello.py"); //执行python文件  
            String funcName ="myFunction";  
            PyObject someFunc =interpreter.get(funcName); // 调用python的猴哥函数  
             
            if (someFunc == null) {  
                //throw new Exception("Could notfind Python function: " + funcName);  
            }  
            else   
            {  
                someFunc.__call__(new PyString(arguments[0]), new PyString(arguments[1]), new PyString(arguments[2])); // 把参数传过去  
            }     
  
        }// main  
      
      
    }  
其中hello.py文件内容如下:


def myFunction(str1, str2, str3):  
    print 'print parameters from java'  
    print str1  
    print str2  
    print str3  

5. 引入第三方库


根据上述方法,暂时不清楚如何在jython中引用类似numpy pandas这样的第三方库,这里给出一种实现方法(与jython无关)。

package jp;  
  
import java.io.BufferedReader;    
import java.io.InputStreamReader;    
    
public class test {    
       public static void main(String[] args){    
                try{    
                        System.out.println("start");    
                        Process pr = Runtime.getRuntime().exec("E:\\Python27\\python.exe C:/Users/JingYi/Desktop/hello.py");  // 本机的python运行环境 & 即将要调用的py文件  
                            
                        BufferedReader in = new BufferedReader(new    
                                InputStreamReader(pr.getInputStream()));    
                        String line;    
                        while ((line = in.readLine()) != null) {    
                            System.out.println(line);    
                        }    
                        in.close();    
                        pr.waitFor();    
                        System.out.println("end");    
                } catch (Exception e){    
                            e.printStackTrace();    
                        }    
                }    
}   

参考:

1.  Jython:java调用python文件之第三方包路径问题 java调用python总出现python第三方库没有定义

2.  java调用python总出现python第三方库没有定义






  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值