在java中调用/执行python方法

来源:互联网 发布:js皮肤哪个好 编辑:程序博客网 时间:2024/05/21 08:47

http://sourceforge.net/projects/jython/下载jython包,把其中的jython.jar添加到工程目录。

或者使用maven:

<!-- https://mvnrepository.com/artifact/org.python/jython --><dependency>    <groupId>org.python</groupId>    <artifactId>jython</artifactId>    <version>2.7.0</version></dependency>

1、在java类中直接执行python语句

import javax.script.*;    import org.python.util.PythonInterpreter;    import java.io.*;  import static java.lang.System.*;  public class FirstJavaScript  {   public static void main(String args[])   {        PythonInterpreter interpreter = new PythonInterpreter();    interpreter.exec("days=('mod','Tue','Wed','Thu','Fri','Sat','Sun'); ");    interpreter.exec("print days[1];");           }//main  } 

2、在java中调用本机python脚本中的函数:

1)首先建立一个python脚本,名字为:my_utils.py

def adder(a, b):      return a + b
2)然后建立一个java类,用来测试:

import javax.script.*;    import org.python.core.PyFunction;  import org.python.core.PyInteger;  import org.python.core.PyObject;  import org.python.util.PythonInterpreter;    import java.io.*;  import static java.lang.System.*;  public class FirstJavaScript  {      public static void main(String args[])      {                    PythonInterpreter interpreter = new PythonInterpreter();          interpreter.execfile("C:\\Python27\\programs\\my_utils.py");          PyFunction func = (PyFunction)interpreter.get("adder",PyFunction.class);            int a = 2010, b = 2 ;          PyObject pyobj = func.__call__(new PyInteger(a), new PyInteger(b));          System.out.println("anwser = " + pyobj.toString());          }//main  }  

得到的结果是:anwser = 2012

3、使用java直接执行python脚本:

1)建立脚本input.py:

#open files    print 'hello'  number=[3,5,2,0,6]  print number  number.sort()  print number  number.append(0)  print number  print number.count(0)  print number.index(5)

2)建立java类,调用这个脚本:

import javax.script.*;    import org.python.core.PyFunction;  import org.python.core.PyInteger;  import org.python.core.PyObject;  import org.python.util.PythonInterpreter;    import java.io.*;  import static java.lang.System.*;  public class FirstJavaScript  {   public static void main(String args[])   {        PythonInterpreter interpreter = new PythonInterpreter();    interpreter.execfile("C:\\Python27\\programs\\input.py");   }//main  }  

得到的结果是:

hello  [3, 5, 2, 0, 6]  [0, 2, 3, 5, 6]  [0, 2, 3, 5, 6, 0]  2  3  


问题1:jython在eclipse控制台出现Failed to install '': java.nio.charset.UnsupportedCharsetException: cp0解决方法

在用jython在eclipse中开发的时候,控制台的输出可能会出现 console: Failed to install ”: java.nio.charset.UnsupportedCharsetException: cp0. 
这样一个错误,此时如果控制台的错误堆栈中有中文的时候,中文就会显示为乱码,解决办法为在要执行的代码上右键, Run As>Run Configurations,选择第二个页签Arguments,在VM arguments中添加:

-Dpython.console.encoding=UTF-8



问题2:

console: Failed to install '': java.nio.charset.UnsupportedCharsetException: cp0.Exception in thread "main" ImportError: Cannot import site module and its dependencies: No module named siteDetermine if the following attributes are correct:  * sys.path: ['...python\\jython\\2.7.0\\Lib', '__classpath__', '__pyclasspath__/']    This attribute might be including the wrong directories, such as from CPython  * sys.prefix:***\jython\2.7.0    This attribute is set by the system property python.home, although it can    be often automatically determined by the location of the Jython jar fileYou can use the -S option or python.import.site=false to not import the site module
解决:

import java.util.Properties;import org.python.util.PythonInterpreter;public class JpythonScript {    public static void main(String args[]) {        Properties props = new Properties();        props.put("python.home", "path to the Lib folder");        props.put("python.console.encoding", "UTF-8");                props.put("python.security.respectJavaAccessibility", "false");                props.put("python.import.site", "false");        Properties preprops = System.getProperties();        PythonInterpreter.initialize(preprops, props, new String[0]);        PythonInterpreter interpreter = new PythonInterpreter();        interpreter.exec("days=('mod','Tue','Wed','Thu','Fri','Sat','Sun'); ");        interpreter.exec("print days[1];");    }}




0 0
原创粉丝点击