Java中的python脚本子进程在Windows中运行时不会被破坏

2024-09-30 10:34:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个控制台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脚本本身在一个无限循环中运行,从一个目录(在参数中传递)读取文件,处理它们并将它们写入另一个目录。你知道吗


Tags: the方法脚本newstringif进程args

热门问题