本文為大家分享了java調(diào)用python方法,供大家參考,具體內(nèi)容如下
一、在java類中直接執(zhí)行python語(yǔ)句
1
2
3
4
5
6
7
8
9
10
11
|
import org.python.util.PythonInterpreter; public class FirstJavaScript { public static void main(String args[]) { PythonInterpreter interpreter = new PythonInterpreter(); interpreter.exec( "days=('mod','Tue','Wed','Thu','Fri','Sat','Sun'); " ); interpreter.exec( "print days[1];" ); } // main } |
調(diào)用的結(jié)果是Tue,在控制臺(tái)顯示出來,這是直接進(jìn)行調(diào)用的。
二、在java中調(diào)用本機(jī)python腳本中的函數(shù)
首先建立一個(gè)python腳本,名字為:my_utils.py
1
2
|
def adder(a, b): return a + b |
然后建立一個(gè)java類,用來測(cè)試,
java類代碼 FirstJavaScript:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
import org.python.core.PyFunction; import org.python.core.PyInteger; import org.python.core.PyObject; import org.python.util.PythonInterpreter; public class FirstJavaScript { public static void main(String args[]) { PythonInterpreter interpreter = new PythonInterpreter(); interpreter.execfile( "C:\\Python27\\programs\\my_utils.py" ); PyFunction func = (PyFunction) interpreter.get( "adder" , PyFunction. class ); int a = 2010 , b = 2 ; PyObject pyobj = func.__call__( new PyInteger(a), new PyInteger(b)); System.out.println( "anwser = " + pyobj.toString()); } // main } |
得到的結(jié)果是:anwser = 2012
三、使用java直接執(zhí)行python腳本
建立腳本inputpy
1
2
3
4
5
6
7
8
9
10
11
|
#open files print 'hello' number=[ 3 , 5 , 2 , 0 , 6 ] print number number.sort() print number number.append( 0 ) print number print number.count( 0 ) print number.index( 5 ) |
建立java類,調(diào)用這個(gè)腳本:
1
2
3
4
5
6
7
8
9
|
import org.python.util.PythonInterpreter; public class FirstJavaScript { public static void main(String args[]) { PythonInterpreter interpreter = new PythonInterpreter(); interpreter.execfile( "C:\\Python27\\programs\\input.py" ); } // main } |
得到的結(jié)果是:
1
2
3
4
5
6
|
hello [ 3 , 5 , 2 , 0 , 6 ] [ 0 , 2 , 3 , 5 , 6 ] [ 0 , 2 , 3 , 5 , 6 , 0 ] 2 3 |
以上就是三種java調(diào)用python方法,希望對(duì)大家的學(xué)習(xí)有所幫助。