How to get the output from .jar execution in python codes?
Solution 1
You can read the output through pipe:
>>> from subprocess import Popen, PIPE, STDOUT
>>> p = Popen(['java', '-jar', './GET_DB_DATA.jar'], stdout=PIPE, stderr=STDOUT)
>>> for line in p.stdout:
print line
As regards passing string to stdin, you can achieve it this way:
>>> p = Popen(['cat'], stdin=PIPE, stdout=PIPE, stderr=STDOUT)
>>> stdout, stderr = p.communicate(input='passed_string')
>>> print stdout
passed_string
Solution 2
If you are using Linux you can use the os.system command:
os.system("your_java_file > out_put_file")
This command will execute the file and print the output to the out_out_file Then you can read the output file.
Solution 3
You could do :
with open('output_of_jar.txt','w') as fp :
subprocess.Popen('java -jar ./GET_DB_DATA.jar',stdout=fp).wait()
with open('output_of_jar.txt') as f :
output = f.read()
print output
Edit :
stdout=fp means that the output of the command will be written to the file output_of_jar.txt
Then you just have to read the contents of the file with :
with open('output_of_jar.txt') as f :
output = f.read()
print output
Related videos on Youtube
Comments
-
Bruce Jung almost 2 years
I'm programming the python module that executes SQL to DBMS and retrieves data. I'm trying to use jdbc jar files instead of native DB drivers. I'm wondering how to executes jar file in python and get output from jar execution. And I'd like to know how to pass SQL string to jar argument. Here is the simplified code. Any help is greatly appreciated.
[ java code ]
public class GetDBResults { public static void main(String[] args) { // return sql results for(int i=0; i<=100; i++){ // Is this the proper way to generate the output? System.out.println(i+"/t"+i*100+1); } } }
[ python code ]
subprocess.call( [ 'java','-jar','./GET_DB_DATA.jar' ) # how to get results from jar execution? # how to pass SQL string to jar execution?
-
Bruce Jung about 10 yearsThank you. You answered within only one minute. I'll try your solution.
-
Bruce Jung about 10 yearsThank you for your fast answer.
-
Bruce Jung about 10 yearsI added the option "shell=True" then your solution worked nicely.
-
Bruce Jung about 10 yearsWow. Your simple code works as well in mac mountain lion as well.
-
ifryed about 10 yearsIt just uses the shell commands, and mac OS is based on Unix as well as Linux, so thats why the same commands work.
-
Bruce Jung about 10 yearsThank your perfect answer. It works like a charm. I think there are many people who are trying to executing jar files in Python. This will help their trials and errors to reduce.
-
Crista23 over 8 years@ovgolovin How can one make two consecutive calls without reloading the jar once it has been loaded? Thanks!
-
ovgolovin over 8 years@Crista23 I would do it through pipe communication. But then it will require to implement reading from pipe on java side.