17

I am trying to execute a .py file from java code. I move the .py file in the default dir of my java project and I call it using the following code:

    String cmd = "python/";
    String py = "file";
    String run = "python  " +cmd+ py + ".py";
    System.out.println(run);
    //Runtime.getRuntime().exec(run);

    Process p = Runtime.getRuntime().exec("python  file.py");

Either using variable run, or the whole path or "python file.py" my code is running showing the message build successful total time 0 seconds without execute the file.py. What is my problem here?

DavidPostill
  • 7,734
  • 9
  • 41
  • 60
Jose Ramon
  • 5,572
  • 25
  • 76
  • 152
  • ‘Build successful’ sounds like the result of a *compilation*. How are you running this? – Biffen Dec 03 '14 at 09:02
  • 2
    possible duplicate of [How to Run a Python file from Java using an Absolute Path?](http://stackoverflow.com/questions/21081898/how-to-run-a-python-file-from-java-using-an-absolute-path) – bud-e Dec 03 '14 at 09:04
  • I run it either with the play button or right click and run file. – Jose Ramon Dec 03 '14 at 09:21

5 Answers5

22

You can use like this also:

String command = "python /c start python path\to\script\script.py";
Process p = Runtime.getRuntime().exec(command + param );

or

String prg = "import sys";
BufferedWriter out = new BufferedWriter(new FileWriter("path/a.py"));
out.write(prg);
out.close();
Process p = Runtime.getRuntime().exec("python path/a.py");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String ret = in.readLine();
System.out.println("value is : "+ret);

Run Python script from Java

Prateek
  • 6,785
  • 2
  • 24
  • 37
  • What is param variable? I run this one String c = "python c start python influencersDataset_edgelist.py"; Process p = Runtime.getRuntime().exec(c); but the same it just build in 0 seconds. – Jose Ramon Dec 03 '14 at 09:40
  • @FereRes param means if you want to send a parameter in script so this is the way... – Prateek Dec 03 '14 at 09:43
  • Weird if I copy python path\to\script\script.py to console it works fine, however here with pb it doesn't react. – Jose Ramon Dec 03 '14 at 09:45
  • Yes indeed. Finally I have checked that link and I found the solution. – Jose Ramon Dec 03 '14 at 09:55
10

I believe we can use ProcessBuilder

Runtime.getRuntime().exec("python "+cmd + py + ".py");
.....
//since exec has its own process we can use that
ProcessBuilder builder = new ProcessBuilder("python", py + ".py");
builder.directory(new File(cmd));
builder.redirectError();
....
Process newProcess = builder.start();
Maddy
  • 2,025
  • 5
  • 26
  • 59
  • Exception in thread "main" java.io.IOException: Cannot run program "python" (in directory "python python\file.py"): CreateProcess error=267, The directory name is invalid. I tested the whole path but I got the same. – Jose Ramon Dec 03 '14 at 09:07
  • try changing the string to an array. I believe that will work. `String[] cmd = new String[] {"python,"...",".."}` – Maddy Dec 03 '14 at 09:10
  • Cannot run program "python " (in directory "python C:\Users\path\file.py"): CreateProcess error=267, The directory name is invalid. I use String[] command = new String[]{"python ", cmd+py+".py"}; – Jose Ramon Dec 03 '14 at 09:16
6
String command = "cmd /c python <command to execute or script to run>";
    Process p = Runtime.getRuntime().exec(command);
    p.waitFor();
    BufferedReader bri = new BufferedReader(new InputStreamReader(p.getInputStream()));
    BufferedReader bre = new BufferedReader(new InputStreamReader(p.getErrorStream()));
          String line;
        while ((line = bri.readLine()) != null) {
            System.out.println(line);
          }
          bri.close();
          while ((line = bre.readLine()) != null) {
            System.out.println(line);
          }
          bre.close();
          p.waitFor();
          System.out.println("Done.");

    p.destroy();
Anshul Gupta
  • 465
  • 5
  • 4
4

You can run the python script

Process p = Runtime.getRuntime().exec(PYTHON_ABSOLUTE_PATH, script_path)

To get the PYTHON_ABSOLUTE_PATH just type

which python2.7

in terminal

2

Though the OP has got the answer, I'm posting my solution which might help someone else like me..

        File file = new File(("C:/.../file.py"));

        List<String> list = new ArrayList<String>();
        list.add("python.exe");
        String absPath = file.getAbsolutePath();

        System.out.println("absPath>>"+absPath);

        list.add(absPath);
        ProcessBuilder pb = new ProcessBuilder(list);
        Process process = pb.start();

        InputStream inputStream = process.getInputStream();
        byte[] b = new byte[1024 * 1024];// {(byte) 1024};
        while (inputStream.read(b) > 0) {
            System.out.println("b.length>>"+new String(b));
        }

        process.waitFor();
        System.out.println("exitValue()>>"+process.exitValue());    //Should return 0 on successful execution
Suresh
  • 1,491
  • 2
  • 22
  • 27