首页>代码>java调用python代码>/javatopython/src/main/java/javatopython/testPython.java
package javatopython;

import org.python.core.PyFunction;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class testPython {
    public static void main(String[] args) {
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.execfile("D:\\add.py");

        // 第一个参数为期望获得的函数(变量)的名字,第二个参数为期望返回的对象类型
        PyFunction pyFunction = interpreter.get("add", PyFunction.class);
        int a1 = 5, b1 = 10;
        //调用函数,如果函数需要参数,在Java中必须先将参数转化为对应的“Python类型”
        PyObject pyobj = pyFunction.__call__(new PyInteger(a1), new PyInteger(b1));
        System.out.println("the anwser is: " + pyobj);



        int a = 18;
        int b = 23;
        try {
            String[] args1 = new String[] { "python", "D:\\dome.py", String.valueOf(a), String.valueOf(b) };
            Process proc = Runtime.getRuntime().exec(args1);// 执行py文件

            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
            proc.waitFor();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
最近下载更多
lironggang  LV38 2023年4月20日
w123456w  LV3 2021年5月18日
aihui523  LV34 2021年3月30日
最代码官方  LV167 2021年3月14日
最近浏览更多
sunlea  LV17 2023年9月2日
stonemachen  LV3 2023年8月8日
Xbfm0329 2023年3月29日
暂无贡献等级
mrrrrr  LV1 2023年1月31日
heqian  LV16 2023年1月10日
新工艺  LV7 2022年11月28日
好的好的  LV8 2021年6月17日
kong.yee  LV40 2021年5月31日
Magic丶M  LV6 2021年5月26日
anheimushi  LV6 2021年5月25日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友