Java から Python を call するのに、Process 作ってシェル実行でなく、Jython を使うこと検討する。
シェル実行だと結果が欲しい時に実行結果の標準出力や標準エラー出力ハンドリングをしなきゃならないからだ。
Maven で、以下より jython-standalone JAR を取得
<dependency> <groupId>org.python</groupId> <artifactId>jython-standalone</artifactId> <version>2.7.1</version> </dependency>
PythonInterpreter インスタンスを単純に、new PythonInterpreter() で生成して
execfile(String filename) で、実行する Python ソースファイルパスを
指定実行するが、動きはするが以下の警告メッセージが出た。
console: Failed to install '': java.nio.charset.UnsupportedCharsetException: cp0.
Jython のバグである。
http://bugs.jython.org/issue2222
http://8thstring.blogspot.com/2014/11/console-failed-to-install.html
JVM起動オプションに、-Dpython.console.encoding=UTF-8 付けるなんて
書いてあるけど、
そんな事するんじゃなくて!PythonInterpreter 生成前に、python.console.encoding 属性が UTF-8 であることを教えてやる。
Properties prop = new Properties(); prop.put("python.console.encoding", "UTF-8"); PythonInterpreter.initialize(System.getProperties(), prop, new String[]{}); try(PythonInterpreter py = new PythonInterpreter()){ py.execfile("c:/var/test.py"); }