diff --git a/src/main/java/JavaRunPythonFile.java b/src/main/java/JavaRunPythonFile.java index a3e85ff..8857d17 100644 --- a/src/main/java/JavaRunPythonFile.java +++ b/src/main/java/JavaRunPythonFile.java @@ -10,6 +10,6 @@ import org.python.util.PythonInterpreter; public class JavaRunPythonFile { public static void main(String[] args) { PythonInterpreter interpreter = new PythonInterpreter(); - interpreter.execfile("classpath:/javaPythonFile.py"); + interpreter.execfile("F:\\javaPythonFile.py"); } } diff --git a/src/main/java/JavaRunPythonFunc.java b/src/main/java/JavaRunPythonFunc.java new file mode 100644 index 0000000..c0a8906 --- /dev/null +++ b/src/main/java/JavaRunPythonFunc.java @@ -0,0 +1,25 @@ +import org.python.core.PyFunction; +import org.python.core.PyInteger; +import org.python.core.PyObject; +import org.python.util.PythonInterpreter; + +/** + * @author yanpeng + * @version 1.0 + * @desc TODO + * @company 北京中经网软件有限公司 + * @date 2021/7/16 17:43 + */ +public class JavaRunPythonFunc { + public static void main(String[] args) { + PythonInterpreter interpreter = new PythonInterpreter(); + interpreter.execfile("F:\\javaPythonFuncFile.py"); + + // 第一个参数为期望获得的函数(变量)的名字,第二个参数为期望返回的对象类型 + PyFunction pyFunction = interpreter.get("add", PyFunction.class); + int a = 5, b = 10; + //调用函数,如果函数需要参数,在Java中必须先将参数转化为对应的“Python类型” + PyObject pyobj = pyFunction.__call__(new PyInteger(a), new PyInteger(b)); + System.out.println("the anwser is: " + pyobj); + } +} diff --git a/src/main/java/JavaRuntimePythonFile.java b/src/main/java/JavaRuntimePythonFile.java new file mode 100644 index 0000000..3ee9ba7 --- /dev/null +++ b/src/main/java/JavaRuntimePythonFile.java @@ -0,0 +1,32 @@ +import org.python.util.PythonInterpreter; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +/** + * @author yanpeng + * @version 1.0 + * @desc TODO + * @company 北京中经网软件有限公司 + * @date 2021/7/16 17:43 + */ +public class JavaRuntimePythonFile { + public static void main(String[] args) { + Process proc; + try { + proc = Runtime.getRuntime().exec("python F:\\javaPythonFile.py"); + BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream())); + String line = null; + while ((line = in.readLine()) != null) { + System.out.println("java"+line); + } + in.close(); + proc.waitFor(); + } catch (IOException e) { + e.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/javaPythonFuncFile.py b/src/main/java/javaPythonFuncFile.py new file mode 100644 index 0000000..edd4422 --- /dev/null +++ b/src/main/java/javaPythonFuncFile.py @@ -0,0 +1,2 @@ +def add(a,b): + return a + b \ No newline at end of file