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

it2022-05-05  130

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(); } } } }

最新回复(0)