Browse Source

全部跑通

master
燕鹏 3 years ago
parent
commit
99a5ecbbe2
  1. 2
      src/main/java/JavaRunPythonFile.java
  2. 25
      src/main/java/JavaRunPythonFunc.java
  3. 32
      src/main/java/JavaRuntimePythonFile.java
  4. 2
      src/main/java/javaPythonFuncFile.py

2
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");
}
}

25
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);
}
}

32
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();
}
}
}

2
src/main/java/javaPythonFuncFile.py

@ -0,0 +1,2 @@
def add(a,b):
return a + b
Loading…
Cancel
Save