2016-07-06 171 views
-3

這是我的Python代碼:如何調用Python函數在Java中

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

我需要知道如何使用PythonInterpreter調用它。

+4

查看jython – syntonym

+0

只需搜索「java systemcall」;並認真:我猜上面的python代碼只是打印出一些字符。你爲什麼要爲此調用一個python解釋器?什麼阻止你將這幾行轉換成java代碼? – GhostCat

+0

請查看http://stackoverflow.com/help/how-to-ask。你的「問題」不清楚。你到目前爲止嘗試了什麼? –

回答

0

在Java中使用ProcessBuilder來創建子進程並捕獲其標準輸出。這裏有一個例子:

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)); 
     } 
    } 
} 

你的Python腳本也需要修改,以便它可以調用的函數,這實際上應該是一個靜態方法,類的方法,或者僅僅是一個獨立的功能。該腳本還需要nb的值,以便它可以傳遞給該函數 - 對此使用sys.argv。所以例如作爲一種靜態方法:

import sys 

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

if __name__ == '__main__': 
    myPythonClass.table(int(sys.argv[1]))