Java: is there a way to run a system command and print the output during execution?

后端 未结 4 2039
醉酒成梦
醉酒成梦 2020-12-06 21:17

I have a python script and it takes a long time to finish. I would like to run it from Java, but also output the script\'s output while it is executing, so that I can tell i

4条回答
  •  难免孤独
    2020-12-06 21:54

    i managed to get it working like this (Note it requires java7):

    package test;
    import java.lang.ProcessBuilder.Redirect;
    
    public class Test {
    
        public static void main(String... args) throws Exception {
            ProcessBuilder pb = new ProcessBuilder("python","/home/foobar/Programming/test/src/test/test.py");
            pb.redirectOutput(Redirect.INHERIT);
            Process p = pb.start();
            p.waitFor();
        }
    
    }
    

    python (note i flush on python to make it work using sys.stdout.flush())

    import time,sys
    c =0
    while c<=50:
        time.sleep(1)
        print("----")
        c = c +1
        sys.stdout.flush()
    

    Note if you don't want to flush in a loop you can use this:

    ProcessBuilder pb = new ProcessBuilder("python","-u","/home/foobar/Programming/NetBeansProjects/test/src/test/test.py");
    

    Redirect.INHERIT

    Indicates that subprocess I/O source or destination will be the same as those of the current process. This is the normal behavior of most operating system command interpreters (shells).

提交回复
热议问题