How to call Python function in Java -


this python code:

class mypythonclass:     def table(nb):         = 0         while < 10:              print(i + 1, "*", nb, "=", (i + 1) * nb)             += 1  

i need know how call using pythoninterpreter.

in java use processbuilder create child process , capture standard output. here's example:

import java.io.bufferedreader; import java.io.inputstreamreader; import java.io.ioexception;  class callpython {     public static void main(string[] args) throws ioexception, interruptedexception {         processbuilder pb = new processbuilder("python", "/path/to/your/script.py", "10");         process p = pb.start();          char[] readbuffer = new char[1000];         inputstreamreader isr = new inputstreamreader(p.getinputstream());         bufferedreader br = new bufferedreader(isr);          while (true) {             int n = br.read(readbuffer);             if (n <= 0)                 break;             system.out.print(new string(readbuffer, 0, n));         }     } } 

your python script need modifications can call function, should static method, method of class, or stand alone function. script needs value nb can passed function - use sys.argv that. e.g. static method:

import sys  class mypythonclass:     @staticmethod     def table(nb):         = 0         while < 10:              print(i + 1, "*", nb, "=", (i + 1) * nb)             += 1   if __name__ == '__main__':     mypythonclass.table(int(sys.argv[1])) 

Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -