我正在编写一个控制台Java应用程序,它生成一个包含长时间运行的Python脚本的子进程。当Java应用程序终止时,我调用process.destroy()
方法终止这个python进程。但是,即使父Java进程终止,该进程仍然可以在任务管理器中看到。你知道吗
另一件需要注意的事情是,当相同的代码在Linux中运行时,python进程会成功地销毁。你知道吗
我也试过给process.destroyForcibly()
打电话,但也没用。我在javadoc中看到,destroyForcibly()
默认情况下调用destroy()
。你知道吗
通过在main()中调用以下方法生成进程:
public static Process executeNonBlockingPython(List<String> args, String workingDirectory) throws IOException, InterruptedException {
if(taggerProperties== null || taggerProperties.isEmpty()) init();
List<String> command = new ArrayList<>();
ProcessBuilder processBuilder = new ProcessBuilder();
if(workingDirectory != null && !workingDirectory.isEmpty())
processBuilder.directory(new File(workingDirectory));
// Prepare the command to be executed based on the base operating system.
if(System.getProperty("os.name").toLowerCase().startsWith("win")) {
command.addAll(
Arrays.asList(
new String[] {
"cmd.exe",
"/c",
taggerProperties.getProperty("PYTHON_EXECUTABLE")
}
)
);
command.addAll(args);
}
else {
command.add(taggerProperties.getProperty("PYTHON_EXECUTABLE"));
command.addAll(args);
}
logger.debug("Executing python command: "+command.toString());
// Spawn the process
processBuilder.command(command);
processBuilder.redirectErrorStream(true);
Process process = null;
process = processBuilder.start();
return process;
}
这里args
是要传递给python脚本的参数列表。然后,此方法将准备用于执行进程的参数列表,并将其传递给processBuilder.command()
方法。最后,在方法结束后,它将返回处理流程的流程对象。属性PYTHON_EXECUTABLE
是指向Python.exe文件。这里有什么我不知道的吗?你知道吗
python脚本本身在一个无限循环中运行,从一个目录(在参数中传递)读取文件,处理它们并将它们写入另一个目录。你知道吗
目前没有回答
相关问题 更多 >
编程相关推荐