Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the output from .jar execution in python codes?

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?
like image 442
Bruce Jung Avatar asked Feb 02 '14 12:02

Bruce Jung


3 Answers

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.

like image 175
ifryed Avatar answered Sep 28 '22 00:09

ifryed


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
like image 36
ovgolovin Avatar answered Sep 28 '22 00:09

ovgolovin


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
like image 41
Azwr Avatar answered Sep 28 '22 01:09

Azwr