温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在Java中调用Python程序

发布时间:2021-06-25 09:12:00 来源:亿速云 阅读:134 作者:chen 栏目:开发技术

这篇文章主要介绍“如何在Java中调用Python程序”,在日常操作中,相信很多人在如何在Java中调用Python程序问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”如何在Java中调用Python程序”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

Java中调用Python程序

1.新建一个Maven工程,导入如下依赖

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

2.在java中直接执行python代码片段

import org.python.util.PythonInterpreter;

public class InvokePython {

    public static void main(String[] args) {
        PythonInterpreter pythonInterpreter = new PythonInterpreter();
        pythonInterpreter.exec("a='aaa'");
        pythonInterpreter.exec("print(a)");
//        pythonInterpreter.exec("import pandas as pd");
    }
}

通过上面这种方式执行python代码片段,实际上是通过Jpython来实现的,这种方式能执行的python代码片段比较有限,都是一些最原始的python命令,很多包不能用,例如执行pythonInterpreter.exec("import pandas as pd"); 都会报错。所以这种方式一般不推荐

3.通过PythonInterpreter类中的execfile()方法来执行一个python脚本文件。

import org.python.util.PythonInterpreter;

public class InvokePython {

    public static void main(String[] args) {
        PythonInterpreter pythonInterpreter = new PythonInterpreter();
        pythonInterpreter.execfile("F:\\大学\\大三\\大三下\\工程创新和企业开发\\大作业\\图灵API.py");
    }
}

这种方式和上面的那种方式的本质是一样的,能执行的命令也是很原始的,一般不推荐。

4.通过Runtime.getRuntime().exec()方法来执行python脚本

原python脚本

import requests
import json
import sys

def chat_by_Turing(question):
    url = "http://www.tuling123.com/openapi/api?key=49de46c409c047d19b2ed2285e8775a6&info="
    response = requests.get(url+question)
    result = json.loads(response.text)
    answer = result['text']
    print("小安:",answer)

question = sys.argv[1] ##这个是用来接收外部传进来的参数
chat_by_Turing(question)

Runtime.getRuntime().exec()调用

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

public class RuntimeFunction {
    public static void main(String[] args) {
        Process proc;
        String compiler = "E:\\Anaconda\\Anaconda_install\\python.exe";
//        String program = "F:\\大学\\大三\\大三下\\工程创新和企业开发\\大作业\\图灵API.py";
        String rootPath = "F:\\大学\\大三\\大三下\\机器学习\\课设\\Python\\src\\main\\resources\\";
        String program = "图灵API.py";
        try {
            Scanner in = new Scanner(System.in);
            System.out.print("我:");
            String question = in.nextLine();
            String commond = compiler+" "+rootPath+program+" "+question;
            proc = Runtime.getRuntime().exec(commond);
            BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream(),"GBK"));
            String line = null;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
            proc.waitFor();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Runtime.getRuntime().exec()需要传入一个字符串类型的参数command ,完整语句Runtime.getRuntime().exec(command)。这条语句是通过自己电脑上的cmd来执行的python程序文件的,因此command的构成如下:
python解释器+" “+python程序文件的绝对路径+” "+需要给python程序文件传入的参数
注意command中的空格比不可少,python脚本里面需要通过sys.argv来接收参数的

通过这种方式来执行python程序,完全取决于你前面使用的python编译器,编译器环境里面有的,就一定能够通过这种方式调用。这种方式比较强大,推荐使用这种方式来执行python程序。

到此,关于“如何在Java中调用Python程序”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI