java調用python方法總結

來源:互聯網
上載者:User

java調用python方法總結

一、在java類中直接執行python語句

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}

調用的結果是Tue,在控制台顯示出來,這是直接進行調用的。

二、在java中調用本機python指令碼中的函數

首先建立一個python指令碼,名字為:my_utils.py

def adder(a, b):      return a + b  

然後建立一個java類,用來測試,

java類代碼 FirstJavaScript:

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}

得到的結果是:anwser = 2012

三、使用java直接執行python指令碼

建立指令碼inputpy

 #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類,調用這個指令碼:

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}

得到的結果是:
view plain

hello  [3, 5, 2, 0, 6]  [0, 2, 3, 5, 6]  [0, 2, 3, 5, 6, 0]  2  3  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.