java调用Python
在java里面调用Python可以采用process类的方法来调用,具体方法如下:
将调用Python的方法封装成为一个类OpenPython,run()方法为调用Python代码执行,并获得返回值,getResult()为获得返回值。
public class OpenPython {
private String path;//路径
private List<String> args=new ArrayList<String>();//参数
private List<String> result=new ArrayList<String>();//返回值
OpenPython(String path,List<String> args){
this.path=path;
this.args=args;
}
//参数组装
private String[] parameterCombine(){
String[] argg=new String[2+args.size()];
argg[0]="python";
argg[1]=path;
for(int i=0;i<args.size();i++){
argg[2+i]=args.get(i);
}
return argg;
}
public void run(){
try{
Process pr=Runtime.getRuntime().exec(parameterCombine());
pr.waitFor();
BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result.add(line);
}
pr.waitFor();
}catch(Exception e){
e.printStackTrace();
}
}
public List<String> getResult(){
return this.result;
}
}
Python代码如下,文件名为my_utils.py
print( "script name:", sys.argv[0])
for i in range(1, len(sys.argv)):
print ("Parameter:", i, sys.argv[i])
print( "script name:", int(sys.argv[1])+int(sys.argv[2]))
客户端调用
public static void main(String args[]){
String path="H:\\my_utils.py";
List<String> argg=new ArrayList<String>();
argg.add("1");
argg.add("2");
OpenPython open=new OpenPython(path,argg);
open.run();
List<String> result=open.getResult();
for(int i=0;i<result.size();i++){
System.out.println(result.get(i));
}
}