我有一个 logText(String text)
函数,它基本上在文本区域中显示一些文本。我需要在运行外部 python 命令之前显示一些文本。但执行外部 python 命令后会显示文本。
这是我的代码。
logText("Please Wait Until The Testing Is Finished");
logText("Starting Testing...");
String command = "python3 python/Predict.py";
try {
String line;
Process process = Runtime.getRuntime().exec(command);
process.waitFor();
BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
error.close();
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
input.close();
OutputStream outputStream = process.getOutputStream();
PrintStream printStream = new PrintStream(outputStream);
printStream.println();
printStream.flush();
printStream.close();
logText("Images Created At Output Directory");
logText("Testing Completed");
} catch (IOException ex) {
Logger.getLogger(MasterFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (InterruptedException ex) {
Logger.getLogger(MasterFrame.class.getName()).log(Level.SEVERE, null, ex);
}
我的logText()
函数。
private void logText(String logText) {
if (logArea.getText().equals("")) {
logArea.setText(">>> " + logText);
} else {
logArea.append(System.lineSeparator() + ">>> " + logText);
}
}
如何在执行 python 命令之前显示文本区域中的文本?
最佳答案
您正在做的事情是在 GUI 线程上运行长时间运行的代码并因此卡住主线程的典型示例。解决方案与往常一样(无论什么语言或框架):在后台线程(例如 new Thread(...) 或 SwingWorker)中运行长时间运行的工作。
例如:
logText("Please Wait Until The Testing Is Finished");
logText("Starting Testing...");
String command = "python3 python/Predict.py";
new Thread(new Runnable() {
public void run() {
try {
String line;
Process process = Runtime.getRuntime().exec(command);
process.waitFor();
BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
error.close();
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
input.close();
OutputStream outputStream = process.getOutputStream();
PrintStream printStream = new PrintStream(outputStream);
printStream.println();
printStream.flush();
printStream.close();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Here, we can safely update the GUI
// because we'll be called from the
// event dispatch thread
logText("Images Created At Output Directory");
logText("Testing Completed");
}
});
} catch (IOException ex) {
Logger.getLogger(MasterFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (InterruptedException ex) {
Logger.getLogger(MasterFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}).start();
附:正如您在注释中看到的,新线程中的最后两个命令需要使用 SwingUtilities.invokeLater(...)
调用。
关于java - 在外部 python 命令在 java 中完成运行之前不会发生任何事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59804720/