Java Runtime.getRuntime().exec调用python程序问题总结

Java Runtime.getRuntime().exec调用python程序的问题总结

1、python程序中,打开外部文件时,找不到文件的问题

在Java中使用Runtime.getRuntime().exec()调用程序时,如果java程序和python程序不在一个文件夹下,而且python中还会打开外部文件,这时会出现找不到文件的异常

解决:
使用 Runtime.getRuntime().exec(cmd,null,new File(path));方法
cmd为输入的指令(包括命令行参数也可以) , path为python文件的路径
这样就可以使python程序找到外部文件

2、调用python程序时,python控制台输出信息过多,导致程序卡死

解决:
开两个独立的线程来处理python程序的正常输出和错误输出
例程:

public static void exePython(String cmd,String path){
        System.out.println("正在执行python程序");
        Process proc = null;
        try {
            proc = Runtime.getRuntime().exec(cmd,null,new File(path));// 执行py文件
            Thread thread1 = new Thread(new StreamReaderThread(proc.getInputStream(),"normal.txt"));
            Thread thread2 = new Thread(new StreamReaderThread(proc.getErrorStream(),"error.txt"));
            thread2.start();
            thread1.start();//必须后执行,否则正确消息容易接收不到
            proc.waitFor();
            Thread.sleep(1000);//等待后台线程读写完毕
            System.out.println("python program done!!!");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                proc.getErrorStream().close();
                proc.getInputStream().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            proc.destroy();
        }
    }

线程代码

public class StreamReaderThread implements Runnable {
    /*
     * python的输出流
     */
    private InputStream inputStream;
    /*
     * 输出信息保存的文件名称
     */
    private String logName;

    public StreamReaderThread(InputStream inputStream,String logName){
        this.inputStream = inputStream;
        this.logName = logName;
    }
    public void run()
    {
        BufferedReader in = null;
        FileWriter fwriter = null;
        try
        {
             in = new BufferedReader(new InputStreamReader(this.inputStream));
             fwriter = new FileWriter(logName, true);
            String line = null;
            while ( (line = in.readLine()) != null)
            {
                fwriter.write(line);
                System.out.println(line);
            }

        } catch (IOException e){
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
                fwriter.flush();
                fwriter.close();
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
  • 7
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值