How to execute a python file with few arguments in java

+5 votes

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 not terminating nor giving the results

Mar 27, 2018 in Java by DareDev
• 6,890 points
69,262 views

4 answers to this question.

+2 votes
Best answer

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.argv))
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();
      }

}

Hope this helps and if not then its recommended to join our Java training class and learn about Java in detail.

answered Mar 27, 2018 by DragonLord999
• 8,450 points

edited Nov 7, 2018 by Omkar
0 votes

There are three ways to get this done:

  • runtime approach
  • process approach
  • jython approach

Have a look at this blog for detailed explanation with example.

answered Oct 12, 2018 by Hannah
• 18,570 points
Sorry None of those approaches are usefull
Hey there! Share the code you have used and the error you are getting..

This is the code that worked for me:

yes this solution is working fine

 Omkar, This code run in command prompt but it cant work on netbeans 

Thankyou bro, it works
its working but  not showing output?

Hey, @There,

Are you getting any error or getting just blank space as output? Can you please confirm in brief!

0 votes
how to read pandas dataframe in java
answered Jan 3, 2019 by anonymous
Hey! It would be better if you post this as a new question. Because your question is irrelevant to this thread. And also, by posting this as a new question, more people will be able to help you.
0 votes

In short one solution could be:

public void runPython() 
{ //need to call myscript.py and also pass arg1 as its arguments.
  //and also myscript.py path is in C:\Demo\myscript.py

    String[] cmd = {
      "python",
      "C:/Demo/myscript.py",
      this.arg1,
    };
    Runtime.getRuntime().exec(cmd);
}

edit: just make sure you change the variable name from str to something else, as noted by cdarke

Your python code (change str to something else, e.g. arg and specify a path for file):

def returnvalue(arg) :
    if arg == "hi" :
        return "yes"
    return "no"
print("calling python function with parameters:")
print(sys.argv[1])
arg = sys.argv[1]
res = returnvalue(arg)
print(res)
with open("C:/path/to/where/you/want/file.txt", 'w') as target:  # specify path or else it will be created where you run your java code
    target.write(res)
answered Dec 15, 2020 by Roshni
• 10,520 points

Related Questions In Java

0 votes
1 answer

How to run a .java file from command line passing arguments in Maven?

Hello @kartik, You could run: mvn exec:exec -Dexec.args="arg1". This will ...READ MORE

answered Jun 3, 2020 in Java by Niroj
• 82,820 points
13,866 views
0 votes
3 answers

How to read a Text File in Java?

You can use readAllLines and the join method to ...READ MORE

answered Jul 28, 2018 in Java by samarth295
• 2,220 points
1,337 views
0 votes
3 answers

How to check whether a file exists or not in Java?

Using nio we can check whether file ...READ MORE

answered Aug 14, 2018 in Java by Sushmita
• 6,900 points
2,649 views
0 votes
2 answers

How to read a text file in Java?

You can use Scanner class to read ...READ MORE

answered Aug 9, 2018 in Java by Parth
• 4,630 points
448 views
0 votes
1 answer

How to run a JAR file in Java?

The command given below will help you ...READ MORE

answered Jun 1, 2018 in Java by Parth
• 4,630 points
6,339 views
0 votes
2 answers

How to left pad a string with zero in java?

String paddedString = org.apache.commons.lang.StringUtils.leftPad("129018", 10, "0") the second ...READ MORE

answered Aug 31, 2018 in Java by Sushmita
• 6,900 points
2,362 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 3,270 views
0 votes
1 answer
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP