java中如何调用python呢?

java问题王 Java每日一问 发布时间:2021-10-23 11:50:07 阅读数:8286 1
下文讲述java中调用python中方法的示例分享,如下所示:

java类中直接运行python语句

import org.python.util.PythonInterpreter;
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[3];");

  }
}
-----运行以上代码,将输出以下信息-----
Thu

java中调用本机python脚本中的函数

//1.建立一个python脚本,名字为: pythonTest.py

def adder(a, b): 
  return a + b 

//建立java代码
import org.python.core.PyFunction;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;

public class TestPython {
  public static void main(String args[]) {

    PythonInterpreter interpreter = new PythonInterpreter();
    interpreter.execfile("D:\\Test\\pythonTest.py");
    PyFunction func = (PyFunction) interpreter.get("adder",
        PyFunction.class);

    int a = 999, b =10;
    PyObject pyobj = func.__call__(new PyInteger(a), new PyInteger(b));
    System.out.println("结果:" + pyobj.toString());
  } 
}
---------------运行以上代码,将输出以下信息------
结果:1009

使用java直接运行python脚本

 //建立脚本 testPython.py

 #open files 
 print 'welcome java265.com' 
 number=[11,22,88] 
 print number 
 number.sort() 
 print number 
 number.append(0) 
 print number 
 print number.count(0) 
 print number.index(5)

//建立java文件
import org.python.util.PythonInterpreter;

public class TestPython {
  public static void main(String args[]) {

    PythonInterpreter interpreter = new PythonInterpreter();
    interpreter.execfile("D:\\test\testPython.py");
  }
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaProblem/202110/1547.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者