0

I try to test my Java class using python, i use suproccess in a "for loop"

>>> import subprocess
>>> for x in range(1, 6):
...     subprocess.call(["java", "Watermelon"])
... 

so when the Watermelon is executing waiting for input...

public class Watermelon{
    public static void main(String[]args){
    Scanner sc = new Scanner(System.in);

    int w = sc.nextInt();

and i have to input the "value" and press ENTER to Watermelon get the "value" and the loop from python continues and input the "value" again and ... to the end.

Can you help me to use "x" in python loop like the "value" to java class...

Thanks for your help and excuse me by my English.

  • Take a look at [`Popen`](https://docs.python.org/2/library/subprocess.html#popen-constructor). You can use pipes to connect `stdin` and `stdout` of the child process. – Pablo Sep 24 '16 at 18:34

2 Answers2

0

You can use PyJnius to access Java classes as Python classes.

>>> from jnius import autoclass
>>> system = autoclass('java.lang.System')
>>> con = system.console() 
>>> con.readLine()
12
'12'
>>>

Test with a compiled Watermelon class:

import java.io.Console;

public class Watermelon
{
    public String read()
    {   
        Console con = System.console();
        String line = con.readLine();
        return line;
    }
}

Python code:

>>> from jnius import autoclass
>>> w = autoclass('Watermelon')
>>> wi = w()
>>> line = wi.read()
12
>>> type(line)
<type 'str'>
>>> 
Kenly
  • 16,220
  • 5
  • 36
  • 52
-2

You can do this very easily

>>> import subprocess
>>> for x in range(1, 6):
...     subprocess.call(["java", "Watermelon "+x])
... 

You just need to append x to complete the string.

Just like java ProgramName int1 int2 ...

Also, Scanner is halting the program and program waits for user input. Instead, you can do the following

int w =Integer.parseInt(args[0]);
swapyonubuntu
  • 1,356
  • 2
  • 21
  • 31