AviusX
AviusX

Reputation: 489

How can I use subprocess to provide multiple inputs to my Java program?

I wrote a Java program for random number generation that first asks the user for a minimum number and then the maximum number and finally outputs a random number in that range.

Now I want to write a python script that automatically runs the java program and gives it the minimum number and then the maximum number. I cannot however, figure out a way to do so after multiple hours of reading documentation and Stack Overflow answers. Here's my python script up until now-

import subprocess

p1 = subprocess.run(['javac', 'RandomNumInt.java'])
p2 = subprocess.run(['java', 'RandomNumInt'])

Now once RandomNumInt runs, here's how it goes-

Enter the minimum number
1
Enter the maximum number
100
The generated random number is: 71

Except here, '1' and '100' are entered by the user from the keyboard.

I want the script to automatically do it. I have read about Popen and communicate() but I can't figure out how to use them to do what I want. (The java program takes input using a scanner.)

Even if I modify the Java program to make it easy to write a script for it, I want to learn.. is there no way to automatically enter multiple inputs at different points in the program execution?

My main objective is to learn how to use Python scripts like this and for now, use this knowledge to run this Java program hundreds of times so that I can see how random my Java program is.

Upvotes: 0

Views: 258

Answers (1)

Mike Br
Mike Br

Reputation: 918

You could pass the parameters in an array, i.e.:

p2 = subprocess.run(['java', 'RandomNumInt', '--min', 1, '--max', 100])

Provided that your second code can read it.

EDIT

Also you can try something like that:

p2 = subprocess.Popen(['java','RandomNumInt'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p2.stdin.write(b'1\n')
p2.stdin.flush()
p2.stdin.write(b'100\n')
p2.stdin.flush()
print(p2.stdout.readline())

Upvotes: 1

Related Questions