-1

String command:

python FileName.py <ServerName> userName pswd<b>

Process p = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
    System.out.println(line + "\n");
}

Code is neither terminating nor giving the actual results. ...

Fenio
  • 3,528
  • 1
  • 13
  • 27
Shakir
  • 123
  • 1
  • 4
  • 14
  • 1
    Have a look here [3 ways to run python script from java](https://bytes.com/topic/python/insights/949995-three-ways-run-python-programs-java) – LenglBoy Mar 19 '18 at 09:29
  • See also [When Runtime.exec() won't](http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html) for many good tips on creating and handling a process correctly. Then ignore it refers to `exec` and use a `ProcessBuilder` to create the process. Also break a `String arg` into `String[] args` to account for things like paths containing space characters. – Andrew Thompson Mar 19 '18 at 10:10

1 Answers1

5

This May Be Helpful !

You can use Java Runtime.exec() to run python script, As an example first create a python script file using shebang and then set it executable.

#!/usr/bin/python
import sys
print 'Number of Arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.arv)
print('This is Python Code')
print('Executing Python')
print('From Java')

if you save the above file as script_python and then set the execution permissions using

chmod 777 script_python

Then you can call this script from Java Runtime.exec() like below

import java.io.*;
import java.nio.charset.StandardCharsets;

public class ScriptPython {
       Process mProcess;

public void runScript(){
       Process process;
       try{
             process = Runtime.getRuntime().exec(new String[]{"script_python","arg1","arg2"});
             mProcess = process;
       }catch(Exception e) {
          System.out.println("Exception Raised" + e.toString());
       }
       InputStream stdout = mProcess.getInputStream();
       BufferedReader reader = new BufferedReader(new InputStreamReader(stdout,StandardCharsets.UTF_8));
       String line;
       try{
          while((line = reader.readLine()) != null){
               System.out.println("stdout: "+ line);
          }
       }catch(IOException e){
             System.out.println("Exception in reading output"+ e.toString());
       }
}
}

class Solution {
      public static void main(String[] args){
          ScriptPython scriptPython = new ScriptPython();
          scriptPython.runScript();
      }

}
Shahbaz Ali
  • 1,262
  • 1
  • 12
  • 13