Java運行腳本優化
1.直接執行Python腳本代碼
引用 org.python包
1 PythonInterpreter interpreter = new PythonInterpreter();
2 interpreter.exec("days=('mod','Tue','Wed','Thu','Fri','Sat','Sun'); "); ///執行python腳本
2. 執行python .py文件
1 PythonInterpreter interpreter = new PythonInterpreter();
2 InputStream filepy = new FileInputStream("D:\\demo.py");
3 interpreter.execfile(filepy); ///執行python py文件
4 filepy.close();
3. 使用Runtime.getRuntime()執行腳本文件
這種方式和.net下面調用cmd執行命令的方式類似。如果執行的python腳本有引用第三方包的,建議使用此種方式。使用上面兩種方式會報錯java ImportError: No mole named arcpy。
1 Process proc = Runtime.getRuntime().exec("python D:\\demo.py");
2 proc.waitFor();
2. 如何在java工程里運行一個python腳本
可以使用jython
方法參考如下
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("uar/local/xxx.py");
//pyFunction :py中方法名
PyFunction func = (PyFunction)interpreter.get("pyFunction",PyFunction.class);
Integer a = 1
Integer b = 2
// py中方法傳參
PyObject pyobj = func.__call__(new PyInteger(a), new PyInteger(b));
System.out.println("anwser = " + pyobj.toString());