Interaction between Java App and Python App

前端 未结 6 1355
余生分开走
余生分开走 2021-01-20 11:33

I have a python application which I cant edit its a black box from my point of view. The python application knows how to process text and return processed text. I have anoth

6条回答
  •  青春惊慌失措
    2021-01-20 11:50

    Use ProcessBuilder to execute your Python code as a filter:

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    
    public class PBTest {
    
        public static void main(String[] args) {
            ProcessBuilder pb = new ProcessBuilder("python", "-c", "print 42");
            pb.redirectErrorStream(true);
            try {
                Process p = pb.start();
                String s;
                BufferedReader stdout = new BufferedReader (
                    new InputStreamReader(p.getInputStream()));
                while ((s = stdout.readLine()) != null) {
                    System.out.println(s);
                }
                System.out.println("Exit value: " + p.waitFor());
                p.getInputStream().close();
                p.getOutputStream().close();
                p.getErrorStream().close();
             } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    

提交回复
热议问题