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?

1 Answers1

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

  • 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" – シュクゴチ Nov 27 '19 at 04:03