Reputation: 61
(new to python so bear with me...)
I have a simple java jar file that when executed, it asks the user for some basic data in a command prompt and then executes an operation based on this data. I want to write a simple python script that will automate the execution of this jar file without the need for the user to supply the data, meaning writing the data inside the script and basically interact with the java application when asked by the command prompt.
Think of a java file that is executed by running Java -jar someJavaApp.jar Then a command prompt is asking for you name. you enter it and press enter, then it asks for your last name, you enter it and press enter and then the java app executes an arbitrary operation based on the input.
I want to have a python script that I can execute the java app several times, each time with different inputs taken from a file or something similar. Any help will be appreciated.
Thanks.
Upvotes: 1
Views: 3887
Reputation: 3245
You can use Popen
from the subprocess module.
Here's a simple example, first script to prompt for input and return some output, test_input.py
:
first = input("Enter your first name: ")
second = input("Enter your second name: ")
print(first+second)
Then the script to call the first script:
import subprocess
values = (("A", "B"), ("C", "D"), ("E", "F"))
command = "python test_input.py"
for first, second in values:
# lazy use of universal_newlines to prevent the need for encoding/decoding
p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True, universal_newlines=True)
output, err = p.communicate(input="{}\n{}\n".format(first, second))
# stderr is not connected to a pipe, so err is None
print(first, second, "->", end="")
# we just want the result of the command
print(output[output.rfind(" "):-1]) # -1 to strip the final newline
This will print:
A B -> AB
C D -> CD
E F -> EF
If you have problems getting it working with your java program, a quick solution may be to specify shell=True
in the Popen
function call. But you'll want to be aware of the security considerations.
Upvotes: 2