能否用ProcessBuilder从一个.py脚本启动一个进程?

编程语言 2026-07-10

作为我正在做的某些课程作业的一部分,我需要使用ProcessBuilder来模拟操作系统的进程调度器——将Python脚本作为进程。问题在于,我无法让ProcessBuilder将 .py识别为一个有效的应用程序文件。

  • 当我独立尝试该文件路径时,即 ... = new ProcessBuilder(processPath);,我会收到一个IOException,提示该文件不是一个有效的Win32应用程序。
  • 当我在文件路径后跟随一个 "python" 参数时,即 new ProcessBuilder(processPath, "python");new ProcessBuilder(List.of(processPath, "python"));,同样会发生。
  • 当我在文件路径前面加上 "python"(这是在其他关于这个主题的Stack Overflow问题中最常见的格式),程序反而会尝试并未能找到名为 "python" 的应用程序文件而失败!

我没有足够的经验来进一步诊断这个问题——除了确认传入函数的参数中的文件路径确实是正确的(确实如此;我找到了在运行时创建相关.py的预写代码,它把文件放在一个 @tempdir目录中并传递该文件路径)。


编辑: 以下是相关代码:

@Override
public void run() {
    System.out.println("Working Directory = " + PCB.getProcessPath()); // debug print;
    running = true;
    PCB.callState("running");

    ProcessBuilder Build = new ProcessBuilder("python", PCB.getProcessPath());
    Process prcss = null;

    try {
        prcss = Build.start();
        prcss.waitFor();
    }
    catch (InterruptedException | IOException e) {
        PCB.callState("interrupted!"); // debug print;
        e.printStackTrace();
    }

    String output = prcss.getInputStream().toString();

    PCB.setPCBResult(output);
    System.out.println("Output: " + output);

    running = false;
    PCB.callState("finished");
}

请注意以下几点:

  • PCB是我们期望使用的自定义预先编写的ProcessControlBlock类的一个实例。
  • CallState() 是我自己写的一个自定义便利方法,它只是设置并打印PCB的状态。
  • 建议使用ProcessBuilder而不是RunTime.exec(); 我认为这不是强制性的,但我对这部分不太在行,因此正在努力遵循这些准则。

解决方案

请参见furas的评论。这只是为了我能关闭这个问题。

它需要 python.exe 作为第一参数,processPath 作为该 python.exe 的参数 - ProcessBuilder("/full/path/to/python.exe", processPath)

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章