上一篇博客讲了不需要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 {import java.io.BufferedReader;
import java.io.InputStreamReader;
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();
}
}
}