Jython:Java如何傳值給Python
阿新 • • 發佈:2019-02-12
想在Java工程中呼叫Python指令碼,最關鍵的是python指令碼需要使用Java實時傳遞過來的變數。因此麻煩了,到處找教程。
中文教程為零,還好有Stack Over Flow,輸入關鍵字:jython java passing variable topython,果真找到一個案例。以下是翻譯內容:
我用的是jython2.7.0,想要把java命令列的引數通過jython傳遞給Python指令碼,結果完全不符合預期,程式碼如下:
String[] arguments ={"arg1", "arg2", "arg3"}; PythonInterpreter.initialize(props,System.getProperties(), arguments); org.python.util.PythonInterpreterpython = new org.python.util.PythonInterpreter(); StringWriter out = newStringWriter(); python.setOut(out); python.execfile("myscript.py"); String outputStr =out.toString(); System.out.println(outputStr);
程式碼執行出現的問題是:傳值失敗。也就是說沒有正確呼叫介面。
下面是兩個回答(未測試):
作者補充回覆:
String[] arguments ={"myscript.py", "arg1", "arg2","arg3"}; PythonInterpreter.initialize(System.getProperties(),System.getProperties(), arguments); org.python.util.PythonInterpreterpython = new org.python.util.PythonInterpreter(); StringWriter out = newStringWriter(); python.setOut(out); python.execfile("myscript.py"); String outputStr =out.toString(); System.out.println(outputStr);
注意第一行,作者是通過arg[0]把指令碼傳入的。
其他人回覆:
import org.python.core.Py; import org.python.core.PyException; import org.python.core.PyObject; import org.python.core.PyString; importorg.python.core.__builtin__; importorg.python.util.PythonInterpreter; public class JythonTest { public static void main(String[] args) { PythonInterpreter interpreter = newPythonInterpreter(); String fileUrlPath ="/path/to/script"; String scriptName ="myscript"; interpreter.exec("importsys\n" + "import os \n" + "sys.path.append('" +fileUrlPath + "')\n"+ "from "+scriptName+" import *\n"); String funcName ="myFunction"; PyObject someFunc =interpreter.get(funcName); if (someFunc == null) { throw new Exception("Could notfind Python function: " + funcName); } try { someFunc.__call__(newPyString(arg1), new PyString(arg2), new PyString(arg3)); } catch (PyException e) { e.printStackTrace(); } } }
注意對方在directory /path/to/script 目錄下建立一個叫做myscript.py 的python指令碼:
def myscript(arg1,arg2,arg3):
print "calling python function withparamters:"
print arg1
print arg2
print arg3
親測:
importjava.io.IOException;
importorg.python.util.PythonInterpreter;
public class test {
public static void main(String[] args) throws IOException {
int[] arg = {3,6};
PythonInterpreter.initialize(System.getProperties(),System.getProperties(), new String[0]);
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("a="+ arg[0]+ "\n");
interpreter.exec("b="+arg[1] + "\n");
interpreter.exec("print b/a");
// pass the address
String txt_path = "\\python\\sample.txt";
interpreter.exec("txt_path = \"" + txt_path + "\"");
interpreter.exec("print txt_path");
}//main
}