在java中使用命令行运行python

2024-05-14 21:34:11 发布

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

程序在p2.waitFor()时卡住了(我在前后用打印字符串进行了测试)

public void score() {
    this.toXML();
    try {
        Process p = Runtime
                    .getRuntime()
                    .exec("python sumocfg_maker.py Carrefour.net.xml Detectors.det.xml edgedata.csv -ef");
        p.waitFor();
        Process p2 = Runtime.getRuntime().exec("python simulation.py");

        new Thread(new Runnable() {
            public void run() {
                BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
                String line = null;

                try {
                    while ((line = input.readLine()) != null)
                        System.out.println(line);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        p2.waitFor();
    } catch (Exception e) {
        e.printStackTrace();
    }
    
    
}

而且{}是

import os

os.system('cmd /c "sumo -c Simulation.sumocfg --duration-log.statistics --log duration.txt)

{}本身运行良好。当我在java中把命令放在simulation.py中时,我遇到了同样的问题

System.out.println(line);打印出“Success”,然后一无所获 我省略了simulation.py中的代码,该代码保存了一个文件,java在p2.wait()之后读取该文件,如果没有p2.wait(),该文件永远不会更改


Tags: 文件pynewlinepublicprocessruntimesimulation
1条回答
网友
1楼 · 发布于 2024-05-14 21:34:11

你有

BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));

但是你需要

BufferedReader input = new BufferedReader(new InputStreamReader(p2.getInputStream()));

由于p已经完成,bufferedreader将等待,但不会接收任何内容

相关问题 更多 >

    热门问题