Java での Python メソッドの呼び出しとピットレコードのステップの概要

序文

最近、プロジェクト内で Java を介して Python スクリプトを呼び出す必要があり、インターネットで多くのブログを検索したところ、操作プロセス全体で多くの落とし穴を踏んだため、この記事では Java での Python の呼び出しと問題点をまとめます。遭遇した。

呼び出しメソッド

ランタイムを介したコール

例は次のとおりです。

public class InvokeByRuntime {
    
    
	/**
	 * @param args
	 * @throws IOException 
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws IOExceptionInterruptedException {
    
    
		String exe = "python";
		String command = "D:\\calculator_simple.py";
		String num1 = "1";
		String num2 = "2";
		String[] cmdArr = new String[] {
    
    exe, command, num1, num2};
		Process process = Runtime.getRuntime().exec(cmdArr);
		InputStream is = process.getInputStream();
		DataInputStream dis = new DataInputStream(is);
		String str = dis.readLine();
		process.waitFor();
		System.out.println(str);
	}
}

caculator_simple.py:

# coding=utf-8
from sys import argv

num1 = argv[1]
num2 = argv[2]
sum = int(num1) + int(num2)
print sum

出力:

3

この方法は、Python プログラムを直接実行するのと同じ効果があります。Python は Java から渡されたパラメータを読み取ることができますが、欠点は、Python の return ステートメントを介して結果を返すことができず、戻り値を標準プログラムに書き込むことしかできないことです。出力ストリームを使用し、Java が Python の出力値を読み取ります。

ジソンに呼ばれた

Maven プロジェクトに依存関係を導入します。ここでは最新バージョンが使用されます

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

パラメータなし戻り値なし

例:

package com.poas.utils;
import org.python.util.PythonInterpreter;

public class PythonTest {
    
    
    public static void main(String[] args) {
    
    
        PythonInterpreter interpreter = new PythonInterpreter();
        //这里用的是相对路径,注意区分
        interpreter.execfile("core/src/main/java/com/poas/utils/plus.py");
      
      	interpreter.cleanup();
        interpreter.close();
    }
}

プラス.py:

a = 1
b = 2
print(a + b)

出力

3

パラメータと戻り値があります

例:

package com.poas.utils;

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

public class PythonTest {
    
    
    public static void main(String[] args) {
    
    
        PythonInterpreter interpreter = new PythonInterpreter();
        //我在这里使用相对路径,注意区分
        interpreter.execfile("core/src/main/java/com/poas/utils/plus.py");

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

プラス.py:

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

実行後の結果は15です

トランプルレコード

インターネット上のほとんどのブログは上記の部分まで到達していますが、実際には次のような問題にも遭遇しました。

报错: ファイル xxx に非 ASCII 文字がありますが、エンコーディングが宣言されていません

理由は、Python ファイル内に中国語が含まれており、コメントであっても認識できないためです。

Pythonファイル内で最初の行以下の内容を追加すると問題は解決します

# -*- coding: utf-8 -*-

报错:バイト値以外の PyString は作成できません

最初に使用した jython のバージョンは 2.7.0 で、Java で文字列を渡すときに次のエラーが報告されました: Cannot create PyString with non-byte value; インターネットで調べたところ、バージョンの問題だったので、バージョンを 2.7.2 にすると問題は解決します

エラー: ImportError: xxx という名前のモジュールがありません

Python ファイルでサードパーティのライブラリを参照したため、このエラーが発生しました

Java ファイル:

public class PythonTest {
    
    
    public static void main(String[] args) {
    
    
        PythonInterpreter interpreter = new PythonInterpreter();       
        interpreter.execfile("core/src/main/java/com/poas/utils/hello.py");        
        PyFunction pyFunction = interpreter.get("hello", PyFunction.class);        
        PyString str = Py.newString("hello world!");
        PyObject pyobj = pyFunction.__call__(str);
        System.out.println(pyobj);
      
      	interpreter.cleanup();
        interpreter.close();
    }
}

Pythonファイル:

import requests #此处这个包没有实际作用,只是为了复现报错
def hello(str) :
    print(str)
    return str

エラー:

ImportError: No module named requests

まず、対応するサードパーティ製ライブラリがインストールされているかどうかを確認し、Python 環境で成功すると、対応するモジュールがインストールされていることがわかり、インターネットで検索すると、設定が必要であることがわかりますPythonのシステムパス、コードは以下のように表示されます:

public class PythonTest {
    
    
    public static void main(String[] args) {
    
    
		// 配置python的系统路径
        System.setProperty("python.home", "/usr/bin/python2.7");

        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.execfile("core/src/main/java/com/poas/utils/hello.py");        
        PyFunction pyFunction = interpreter.get("hello", PyFunction.class);        
        PyString str = Py.newString("hello world!");
        PyObject pyobj = pyFunction.__call__(str);
        System.out.println(pyobj);
      
      	interpreter.cleanup();
        interpreter.close();
    }
}

構成が完了した後もエラーが報告される

上記の設定に加えて、引き続き情報を確認します。参照されるサードパーティ ライブラリのパスシステム環境変数に追加すると、コードは次のようになります。

public class PythonTest {
    
    
    public static void main(String[] args) {
    
    
        // 配置python的系统路径
        System.setProperty("python.home", "/usr/bin/python2.7");

        PythonInterpreter interpreter = new PythonInterpreter();
        // 添加第三方库的路径
        PySystemState sys = interpreter.getSystemState();
        sys.path.add("/Users/xxx/Library/Python/2.7/lib/python/site-packages");

        interpreter.execfile("core/src/main/java/com/poas/utils/hello.py");
        PyFunction pyFunction = interpreter.get("hello", PyFunction.class);
        PyString str = Py.newString("hello world!");
        PyObject pyobj = pyFunction.__call__(str);
        System.out.println(pyobj);
        interpreter.cleanup();
        interpreter.close();
    }
}

問題が解決しました

参考文献:

Java で Python を呼び出す
[Java] Java を使用して Python を呼び出す 4 つの方法

おすすめ

転載: blog.csdn.net/wzc3614/article/details/128666187
おすすめ