How to Run a Python file from Java using an Absolute Path?

后端 未结 2 580
终归单人心
终归单人心 2021-01-15 01:19

I want to run a python script called, for example foo. And I have the absoulute path, lets say: /Users/me/pythonscripts/

I have tried running:

St         


        
2条回答
  •  终归单人心
    2021-01-15 01:59

    Try using something more like...

    Runtime.getRuntime().exec("python "+cmd + py + ".py");
    

    Instead. Each exec is it's own process and multiple exec has no relationship to each other...

    You should also consider using ProcessBuilder instead, as this provides you with a great level of configurability, for example, you can change the execution path context...

    ProcessBuilder pb = new ProcessBuilder("python", py + ".py");
    pb.directory(new File(cmd));
    pb.redirectError();
    //...
    Process p = pb.start();
    

    Also, beware, that Python has an issue with it's output stream, which may prevent Java from reading it until it's completely finished if at all...

    For more details, take a look at Java: is there a way to run a system command and print the output during execution?

    Also, make sure python is within the shell's search path, otherwise you will need to specify the full path to the command as well

提交回复
热议问题