【问题标题】:Running python with command line in java在java中使用命令行运行python
【发布时间】:2021-04-12 06:58:50
【问题描述】:

程序卡在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();
    }
    
    
}

simulation.py

import os

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

simulation.py 自己运行良好。当我在java中将命令放入simulation.py时,我遇到了同样的问题。

System.out.println(line); 打印出“Success”,然后什么也没有 我遗漏了simulation.py 中的代码,该代码保存了java 在p2.wait() 之后立即读取的文件,并且没有p2.wait(),该文件永远不会改变。

【问题讨论】:

  • 线程是否陷入了死循环?当BufferedReader 达到EOF 时,line 只是null
  • 这真的有意义吗? new InputStreamReader(p.getInputStream())。在我看来p 已经完成了。

标签: java python process sumo


【解决方案1】:

你有

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

但你需要

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

由于 p 已经完成,bufferedreader 将等待但永远不会收到任何东西。

【讨论】:

    猜你喜欢
    • 2018-12-28
    • 2019-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-15
    • 1970-01-01
    • 2021-07-16
    • 1970-01-01
    相关资源
    最近更新 更多