java调用Python

JPython

本文 Python 版本 2.7
JPython pom

	<dependency>
            <groupId>org.python</groupId>
            <artifactId>jython-standalone</artifactId>
            <version>2.7.0</version>
   </dependency>

执行py脚本文件

在py脚本中直接定义的方法是OK的,但是调用 定义在类中的方法为nullPoint,后续继续研究……

import org.junit.Test;
import org.python.core.*;
import org.python.util.PythonInterpreter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Properties;

	@Test
    public void test3(){
        PythonInterpreter pythonInterpreter = new PythonInterpreter();
        pythonInterpreter.execfile("xxx.py");
        PyFunction func = (PyFunction) pythonInterpreter.get("add",PyFunction.class);
        PyObject pyObject = func.__call__(new PyInteger(998),new PyInteger(1));
        System.out.println(pyObject.toString());

    }
def add(c, b):
    return c+b


print(add(2, 3))

idea控制台输出print() 中内容

999
5
常见问题
  1. TypeError: object of type ‘NoneType’ has no len()
    更新pom文件解决
<dependency>
            <groupId>org.python</groupId>
            <artifactId>jython-standalone</artifactId>
            <version>2.7.0</version>
   </dependency>

java直接运行python代码

print注意Python 2.x 和 3.x 区别

 @Test
    public void test2(){
        PythonInterpreter interpreter = new PythonInterpreter();
        PySystemState sys = Py.getSystemState();
        //指定python
        sys.path.add("D:\\Program Files (x86)\\python32\\Lib");
        interpreter.exec("print('hello')");
        interpreter.exec("import sys");
        interpreter.exec("print(sys.path)");
    }

Runtime

  @Test
    public void testReadFromLocal() {
        Process proc;
        try {
            proc = Runtime.getRuntime().exec("python D:\\ReturnTest.py");
            //用输入输出流来截取结果
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String line ;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
            proc.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

打开记事本 计算器

		Runtime.getRuntime().exec("notepad.exe");
        Runtime.getRuntime().exec("calc");

常见问题

Runtime.exec相当于在windows + R 中执行命令,确保python已经加入环境变量,否则请手动指定python环境

        Runtime.getRuntime().exec("D:\\Program Files (x86)\\python32\\python.exe D:\\ReturnTest.py");

使用RunTime exec的风险请参考:
https://www.jianshu.com/p/af4b3264bc5d

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值