Java直接调用Python
转载 2015Java直接调用Python
转载 2015年04月07日 16:38:27 3173
使用Runtime.getRuntime()执行脚本文件,这种方式和.net下面调用cmd执行命令的方式类似。如果执行的python脚本有引用第三方包的,建议使用此种方式。
[java] view plain copy
Process proc = Runtime.getRuntime().exec(“python D:\demo.py”);
proc.waitFor();
Java调用代码:
[java] view plain copy
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Test5 {
public static void main(String[] args){
try{
System.out.println(“start”);
Process pr = Runtime.getRuntime().exec(“d:\python27\python.exe test.py”);
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("end");
} catch (Exception e){
e.printStackTrace();
}
}
}
test.py的文件内容为:
[python] view plain copy
import sys
import urllib
print “hello”
print sys.path
java程序运行的结果为:
start
hello
[‘D:\eclipse_jee_workspace\ZLabTest’, ‘C:\Windows\system32\python27.zip’, ‘D:\Python27\DLLs’, ‘D:\Python27\lib’, ‘D:\Python27\lib\plat-win’, ‘D:\Python27\lib\lib-tk’, ‘D:\Python27’, ‘D:\Python27\lib\site-packages’]
end年04月07日 16:38:27 3173
使用Runtime.getRuntime()执行脚本文件,这种方式和.net下面调用cmd执行命令的方式类似。如果执行的python脚本有引用第三方包的,建议使用此种方式。
[java] view plain copy
Process proc = Runtime.getRuntime().exec(“python D:\demo.py”);
proc.waitFor();
Java调用代码:
[java] view plain copy
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Test5 {
public static void main(String[] args){
try{
System.out.println(“start”);
Process pr = Runtime.getRuntime().exec(“d:\python27\python.exe test.py”);
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("end");
} catch (Exception e){
e.printStackTrace();
}
}
}
test.py的文件内容为:
[python] view plain copy
import sys
import urllib
print “hello”
print sys.path
java程序运行的结果为:
start
hello
[‘D:\eclipse_jee_workspace\ZLabTest’, ‘C:\Windows\system32\python27.zip’, ‘D:\Python27\DLLs’, ‘D:\Python27\lib’, ‘D:\Python27\lib\plat-win’, ‘D:\Python27\lib\lib-tk’, ‘D:\Python27’, ‘D:\Python27\lib\site-packages’]
end