なぜか Jython の情報が少ない。Python ってそんなに他言語と一線を画すような拘りがあるのだろうか?
Python は Pythonの良い所を利用して、Java はJavaの長所を活かして相互補助して使おうと考えないのだろうか?
Java → Python 実行で、パラメータ渡し、結果受け取りでハマったのが
・・・2バイト文字の結果を Java で受け取るケース
hello.py というテストの Python ソース・・・アホみたいなコードです
# -*- coding: UTF-8 -*- def helloFunc(m): str = "Hello Python : " + m print(str) sts = "あ" res = "helloFunc result = " + sts return res.decode("UTF-8") result = helloFunc(message)
1行目 # -*- coding: UTF-8 -*- を書いているから、Java からセットされた2バイト文字が
UTF-8 で扱われる?で正しいのか???
helloFunc() の戻り、return で返すものを unicode から UTF-8 にデコードする。
Java 呼び出し側
import org.python.core.PyObject; import org.python.util.PythonInterpreter;
Properties props = new Properties(); props.put("python.console.encoding", "UTF-8"); PythonInterpreter.initialize(System.getProperties(), props, new String[]{}); try(PythonInterpreter py = new PythonInterpreter()){ py.set("message", "あいう"); py.execfile("C:/hello.py"); PyObject pyResult = py.get("result"); System.out.println("hello.py の 結果:" + pyResult.toString() ); }catch(Exception e){ e.printStackTrace(); }
結果は、
Hello Python : あいう hello.py の 結果:helloFunc result = あ
new PythonInterpreter() の実行が、とにかく遅い!!
PythonInterpreter インスタンスは一度生成したら、そのまま使い回しはできるようである。
パラメータ渡し方は他にも、こんな方法ある。
java - Adding arguments in Jython PythonInterpreter to the "execfile" function - Stack Overflow