0

I want to call a python program with arguments from java. But my output is a blank. The code is here.

Python code is here:

import sys

print(sys.argv[1])

And the java code is here:

public class PrintNumber{
    public static void main(String[] args){
        Process proc;
        try {
            proc = Runtime.getRuntime().exec("python ../pythonProgram/pythonProgram/PrintN.py 30");
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
            proc.waitFor();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }   
}

I want to output 30, could somebody tell me where is the mistake?

3
  • duplicate of stackoverflow.com/questions/10097491/… ? Commented Nov 18, 2019 at 6:48
  • Maybe the Python script is not found. To investigate you might read from proc.getErrorStream instead to see any error. Commented Nov 18, 2019 at 8:51
  • @SubOptimal Yes, you are totally correct, Thank you. Commented Nov 27, 2019 at 4:05

1 Answer 1

0

You can try it out:

String command = "python /c start python ../pythonProgram/pythonProgram/PrintN.py";

int param = 30;

proc = Runtime.getRuntime().exec(command + param);

Reference: Run Python script by Java

Sign up to request clarification or add additional context in comments.

1 Comment

I kinda solve this problem, my issue is that I cannot run python code which imports a third-party library. So I need to find the full name of my python, which means I should code "which python" in terminal first, and then write down the full path. In this case, instead of "python ../pythonProgram/pythonProgram/PrintN.py 30", I should write down "/Users/archer/anaconda3/bin/python ../pythonProgram/pythonProgram/PrintN.py 30" and the first parameter is the outcome after "which python"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.