2012-02-21 17 views
8

Sto usando Jython all'interno di un progetto Java.Come chiamare un metodo python da una classe java?

Ho una classe Java: myJavaClass.java e uno Python classe: myPythonClass.py

public class myJavaClass{ 
    public String myMethod() { 
     PythonInterpreter interpreter = new PythonInterpreter(); 
     //Code to write 
    } 
} 

Il file di Python è la seguente:

class myPythonClass: 
    def abc(self): 
     print "calling abc" 
     tmpb = {} 
     tmpb = {'status' : 'SUCCESS'} 
     return tmpb 

Ora il problema è che voglio chiamare il metodo di abc() il mio file Python dal metodo myMethod del mio file Java e stampare il risultato.

+1

Cos'hai provato? Hai guardato questo: http://www.jython.org/archive/21/docs/embedding.html? – grifaton

risposta

12

Se leggo the docs destra, si può semplicemente utilizzare la funzione eval:

interpreter.execfile("/path/to/python_file.py"); 
PyDictionary result = interpreter.eval("myPythonClass().abc()"); 

Oppure, se volete per ottenere una stringa:

PyObject str = interpreter.eval("repr(myPythonClass().abc())"); 
System.out.println(str.toString()); 

Se si vuole fornire con qualche input da variabili Java, è possibile utilizzare set beforeh e e di usare quel nome variabile all'interno del codice Python:

interpreter.set("myvariable", Integer(21)); 
PyObject answer = interpreter.eval("'the answer is: %s' % (2*myvariable)"); 
System.out.println(answer.toString()); 
+0

così ho bisogno di avere una riga di codice come: interpreter.eval ("myPythonClass(). Abc (myvariable)"); – Hasti

+0

@ashti: Sì, questo fornirebbe 'myvariable' come argomento al metodo' abc' della tua classe. Ho aggiunto un altro esempio per dimostrare come utilizzare quella variabile appena creata. –

+0

Grazie mille per le tue informazioni utili. Problema risolto! – Hasti

1

Non c'è alcun modo per fare esattamente questo (che io sappia).

Dovete comunque alcune opzioni:

1) Eseguire il pitone all'interno di Java in questo modo:

try { 
    String line; 
    Process p = Runtime.getRuntime().exec("cmd /c dir"); 
    BufferedReader bri = new BufferedReader(new InputStreamReader(p.getInputStream())); 
    BufferedReader bre = new BufferedReader(new InputStreamReader(p.getErrorStream())); 
    while ((line = bri.readLine()) != null) { 
     System.out.println(line); 
    } 
    bri.close(); 
    while ((line = bre.readLine()) != null) { 
     System.out.println(line); 
    } 
    bre.close(); 
    p.waitFor(); 
    System.out.println("Done."); 
} 
catch (Exception err) { 
    err.printStackTrace(); 
} 

2) È possibile magari utilizzare Jython che è "un'implementazione della programmazione Python linguaggio scritto in Java ", da lì potresti avere più fortuna a fare quello che vuoi.

3) È possibile effettuare le due applicazioni di comunicare in qualche modo, con una presa o file condiviso

+0

Sta già usando 'PythonInterpreter', che è una [classe Jython] (http://www.jython.org/javadoc/org/python/util/PythonInterpreter.html). –

+0

Oh, il tag * Python * è confuso quindi. –

+0

Perché è così? Jython * è * un'implementazione di Python. Tuttavia, ho aggiunto il tag [jython] alla domanda. –

3

Se abbiamo bisogno di eseguire una funzione Python che dispone di parametri e restituire i risultati, abbiamo solo bisogno di stampare questo:

import org.python.core.PyObject; 
import org.python.core.PyString; 
import org.python.util.PythonInterpreter; 

public class method { 

public static void main(String[] args) { 

    PythonInterpreter interpreter = new PythonInterpreter(); 
    interpreter.execfile("/pathtoyourmodule/somme_x_y.py"); 
    PyObject str = interpreter.eval("repr(somme(4,5))"); 
    System.out.println(str.toString()); 

} 

somme è la funzione nel modulo python somme_x_y.py

def somme(x,y): 
    return x+y 
0

Puoi download here Jython 2.7.0 - Jar Standalone.

Poi ...

  1. aggiungere questo al percorso java in Eclipse ......
  2. In Esplora Package (a sinistra), fare clic destro sul vostro progetto Java e selezionare Proprietà .
  3. Nella vista ad albero sulla sinistra, selezionare Percorso build Java.
  4. Selezionare la scheda Librerie.
  5. Selezionare Aggiungi JAR esterni ...
  6. Individuare l'installazione Jython (C: \ jython2.5.2 per me) e selezionare jython.jar.
  7. Fare clic su Applica e chiudi.

Poi ...

Java class (main) //use your won package name and python class dir 
----------------- 
package javaToPy; 
import org.python.core.PyObject; 
import org.python.util.PythonInterpreter; 

public class JPmain { 

    @SuppressWarnings("resource") 
    public static void main(String[] args) { 

    PythonInterpreter interpreter = new PythonInterpreter(); 

    //set your python program/class dir here 
    interpreter.execfile 
    ("C:\\Users\\aman0\\Desktop\\ME\\Python\\venv\\PYsum.py"); 

    PyObject str1 = interpreter.eval("repr(sum(10,50))"); 
    System.out.println(str1.toString()); 

    PyObject str2 = interpreter.eval("repr(multi(10,50))"); 
    System.out.println(str2.toString()); 


    interpreter.eval("repr(say())"); 


    interpreter.eval("repr(saySomething('Hello brother'))"); 

} 

} 

--------------------------- 
Python class 
------------ 

def sum(x,y): 
    return x+y 

def multi(a,b): 
    return a*b 

def say(): 
    print("Hello from python") 

def saySomething(word): 
    print(word)`enter code here` 
Problemi correlati