3 回答

TA貢獻1906條經(jīng)驗 獲得超10個贊
一種骯臟的 hacky 方法是調(diào)用Runtime.exec("python command here")一個偵聽器并將其附加到由此創(chuàng)建的進程。本文解釋了與此技術(shù)相關(guān)的方法:https://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html。一個粗略的例子如下:
button.setOnAction(event -> {
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("python command");
process.getOutputStream() // add handling code here
});
但是,請考慮這是否是您真正想要做的事情。為什么不用 Python 創(chuàng)建用戶界面。流行的 GTK GUI 庫具有 Python 綁定(文檔位于https://python-gtk-3-tutorial.readthedocs.io/en/latest/)。
或者考慮用 Java 編寫人臉識別組件。如果您完全從頭開始編寫它,這可能會很困難,但如果使用像 OpenCV 這樣的庫,則可能有可用的 Java 綁定。
一般來說,如果不特別小心,跨語言交流是很困難的,而且很容易出錯,所以請仔細考慮您是否需要這個確切的設(shè)置。

TA貢獻1895條經(jīng)驗 獲得超3個贊
我想你可以使用
????Runtime?rt?=?Runtime.getRuntime(); ????????Process?pr?=?rt.exec(path?+?"XXX.py");
并等待py完成輸出JSON格式,最后使用java rading你要做的JSON數(shù)據(jù)處理。

TA貢獻1860條經(jīng)驗 獲得超8個贊
老實說,我猜上面給出的答案是正確的。只需在按鈕事件中使用另一個線程,這樣您的 Java 程序主線程就不必等到事情完成,并且可以防止 UI 凍結(jié)。
創(chuàng)建線程
public class MyRunnable implements Runnable {
private String commandParameters = "";
// Just Creating a Constructor
public MyRunnable(String cmd)
{
this.commandParameters = cmd;
}
public void run()
{
try
{
Runtime runtime = Runtime.getRuntime();
// Custom command parameters can be passed through the constructor.
Process process = runtime.exec("python " + commandParameters);
process.getOutputStream();
}
catch(Exception e)
{
// Some exception to be caught..
}
}
}
在您的按鈕事件中執(zhí)行此操作
yourBtn.setOnAction(event -> {
try{
Thread thread = new Thread(new MyRunnable("command parameter string"));
thread.start();
}
catch(Exception e)
{
// Some Expection..
}
});
現(xiàn)在您的主線程不會凍結(jié)或等待命令執(zhí)行完成。希望這能解決問題。如果你想將一些變量值傳遞給“python 命令”,只需在創(chuàng)建MyRunnable 類時讓你成為一個構(gòu)造函數(shù),并將它作為參數(shù)傳遞給 MyRunnable 類的構(gòu)造函數(shù)。
現(xiàn)在,當(dāng)您單擊該按鈕時,這將運行一個新線程。這不會干擾您的主 UI 線程。
添加回答
舉報