想在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 }
参考问答:how to passarguments to python script in java using jython