溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何在Java中調(diào)用Python程序

發(fā)布時間:2021-06-25 09:12:00 來源:億速云 閱讀:143 作者:chen 欄目:開發(fā)技術

這篇文章主要介紹“如何在Java中調(diào)用Python程序”,在日常操作中,相信很多人在如何在Java中調(diào)用Python程序問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”如何在Java中調(diào)用Python程序”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!

Java中調(diào)用Python程序

1.新建一個Maven工程,導入如下依賴

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

2.在java中直接執(zhí)行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");
    }
}

通過上面這種方式執(zhí)行python代碼片段,實際上是通過Jpython來實現(xiàn)的,這種方式能執(zhí)行的python代碼片段比較有限,都是一些最原始的python命令,很多包不能用,例如執(zhí)行pythonInterpreter.exec("import pandas as pd"); 都會報錯。所以這種方式一般不推薦

3.通過PythonInterpreter類中的execfile()方法來執(zhí)行一個python腳本文件。

import org.python.util.PythonInterpreter;

public class InvokePython {

    public static void main(String[] args) {
        PythonInterpreter pythonInterpreter = new PythonInterpreter();
        pythonInterpreter.execfile("F:\\大學\\大三\\大三下\\工程創(chuàng)新和企業(yè)開發(fā)\\大作業(yè)\\圖靈API.py");
    }
}

這種方式和上面的那種方式的本質(zhì)是一樣的,能執(zhí)行的命令也是很原始的,一般不推薦。

4.通過Runtime.getRuntime().exec()方法來執(zhí)行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] ##這個是用來接收外部傳進來的參數(shù)
chat_by_Turing(question)

Runtime.getRuntime().exec()調(diào)用

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:\\大學\\大三\\大三下\\工程創(chuàng)新和企業(yè)開發(fā)\\大作業(yè)\\圖靈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()需要傳入一個字符串類型的參數(shù)command ,完整語句Runtime.getRuntime().exec(command)。這條語句是通過自己電腦上的cmd來執(zhí)行的python程序文件的,因此command的構成如下:
python解釋器+" “+python程序文件的絕對路徑+” "+需要給python程序文件傳入的參數(shù)
注意command中的空格比不可少,python腳本里面需要通過sys.argv來接收參數(shù)的

通過這種方式來執(zhí)行python程序,完全取決于你前面使用的python編譯器,編譯器環(huán)境里面有的,就一定能夠通過這種方式調(diào)用。這種方式比較強大,推薦使用這種方式來執(zhí)行python程序。

到此,關于“如何在Java中調(diào)用Python程序”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續(xù)學習更多相關知識,請繼續(xù)關注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI