如何从python代码中获取.jar执行的输出? [英] How to get the output from .jar execution in python codes?

查看:556
本文介绍了如何从python代码中获取.jar执行的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写执行SQL到DBMS并检索数据的python模块。我正在尝试使用jdbc jar文件而不是本机DB驱动程序。我想知道如何在python中执行jar文件并从jar执行中获取输出。我想知道如何将SQL字符串传递给jar参数。
这是简化的代码。
非常感谢任何帮助。

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]

[ 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]

[ 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?


推荐答案

您可以通过管道读取输出:

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

关于将字符串传递给stdin,你可以通过这种方式实现:

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

这篇关于如何从python代码中获取.jar执行的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆