您的位置:首页 > 编程语言 > Python开发

Java调用Python脚本(需要传参)

2017-11-01 09:07 417 查看
      上一篇博客讲了不需要Java调用Python脚本不需要传参的解决办法,这篇博客主要讲一下需要传参数时如何解决。

1、将写好的py脚本最好放置在Java工程Resource的根目录下,方便管理和引用,当然也可以存放在本地;
2、编写python脚本,名称为pythontest.py,假设需要传递的参数位于sql语句:
     sql = "select * from 表名称  where 列名称 between  '%s' and '%s'" % (sys.argv[1],sys.argv[2]); #查询列值位于第一个参数                和第二个参数之间的值;
3、编写class文件,代码如下:
       package python;

        import java.io.BufferedReader;    

        import java.io.InputStreamReader;

        
        public class test {
        public static void main(String[] args){  

        try{  

                System.out.println("open");              

                Process pr = Runtime.getRuntime().exec("python pythontest.py 参数1的值 参数2的值"); 

                BufferedReader in = new BufferedReader(new  

                        InputStreamReader(pr.getInputStream()));  

                String line;  

                while ((line = in.readLine()) != null) {  

                    System.out.println(line);  

                }  

                in.close();   

                pr.waitFor(); 

                System.out.println(pr.exitValue());  

        } catch (Exception e){  

                    e.printStackTrace();  

                }  

        }  

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: