4 changed files with 60 additions and 1 deletions
@ -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); |
||||
|
} |
||||
|
} |
@ -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(); |
||||
|
} |
||||
|
} |
||||
|
} |
@ -0,0 +1,2 @@ |
|||||
|
def add(a,b): |
||||
|
return a + b |
Loading…
Reference in new issue