How to get out of .jar execution in python codes?

I am programming a python module that executes SQL in a DBMS and retrieves data. I am trying to use jdbc jar files instead of native DB drivers. I am wondering how to execute jar file in python and get output from jar execution. And I would like to know how to pass SQL string to jar argument. Here is the simplified code. Any help is 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?
+4
source share
3 answers

You can read the output through the channel:

>>> 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 for passing the string to stdin, you can achieve it like this:

>>> p = Popen(['cat'], stdin=PIPE, stdout=PIPE, stderr=STDOUT)
>>> stdout, stderr = p.communicate(input='passed_string')
>>> print stdout
passed_string
+8
source

Linux, os.system:

os.system("your_java_file > out_put_file")

out_out_file .

+2

You can 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 fileoutput_of_jar.txt

Then you just need to read the contents of the file with:

with open('output_of_jar.txt') as f :
    output = f.read()
print output
+1
source

Source: https://habr.com/ru/post/1524926/


All Articles