最近做項目時需要用Java調用python的文件,本篇博客介紹用java調用python的代碼。
一、使用Jpython來實現用java調用python的代碼
1.下載JPython的包
我下載的是jython-2.7-b1.jar,下載好后在項目classpath中添加這個jar包。
2.編寫簡易python代碼
import org.python.util.PythonInterpreter; import java.util.Properties; /** *@author chenmeiqi *@version 2020年2月26日 下午7:08:24 */ public class test { public static void main(String[] args) { // TODO Auto-generated method stub PythonInterpreter interpreter = new PythonInterpreter(); // 運行python語句 interpreter.exec("a = \"hello, Jython\""); interpreter.exec("print a"); } }
運行結果:
二、使用Runtime.getRuntime()執行腳本文件
Runtime.getRuntime()可以取得當前JVM的運行時環境,這也是在java中唯一一個得到運行時環境的方法。
注:如果執行的Python腳本有引用第三方包的,建議使用此種方式。
代碼示例:
import org.python.util.PythonInterpreter; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Properties; /** *@author chenmeiqi *@version 2020年2月26日 下午7:08:24 */ public class test { public static void main(String[] args) throws IOException, InterruptedException { // TODO Auto-generated method stub Process proc = Runtime.getRuntime().exec("D:\\Anaconda3\\envs\\py36\\python.exe D:/spider/ItemCF.py"); BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream())); String line; while ((line = in.readLine()) != null) { System.out.println(line); } in.close(); proc.waitFor(); System.out.println("end"); } }
python腳本代碼:
print("使用java調用python代碼!")
運行結果: