我尝试了运行时和流程构建器在java中运行python,但java无法显示python结果。
python代码:
def cal():
a=4
b=90
c=a+b
return c
if __name__ == "__main__":
c=cal()
print c
print "hello"
print "hello..................."
java代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class qqqqqqqqqqqqqqqq {
public static void main (String args[]) throws IOException {
try
{
// ProcessBuilder pb = new ProcessBuilder("C:/Python27/python","C://Users//admin//Destop//dsf.py" );
// Process p = pb.start();
Runtime r=Runtime.getRuntime();
Process p=r.exec("cmd /c C:/Python27/python C://Users//admin//Destop//dsf.py");
BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream()));
System.out.println(".........start process.........");
String line = "";
while ((line = bfr.readLine()) != null)
{
System.out.println("Python Output: " + line);
}
System.out.println("........end process.......");
} catch (Exception e)
{
System.out.println(e);
}
}
}
java输出结果:
.........start process.........
........end process.......
路径和代码没有错误,为什么java无法运行python?
答案 0 :(得分:0)
您的代码绝对正确。下面是在标准java程序中运行python代码所需的一些更正。
在提供python exe时使用双斜杠
Process p=r.exec("cmd /c C:/Python27/python C://Users//admin//Destop//dsf.py");
public class Test {
public static void main (String args[]) throws IOException {
try
{
Runtime r=Runtime.getRuntime();
Process p=r.exec("cmd /c C:\\Python34\\python.exe D:\\PythonScripts\\HelloWorld.py");
BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream()));
System.out.println(".........start process.........");
String line = "";
while ((line = bfr.readLine()) != null)
{
System.out.println("Python Output: " + line);
}
System.out.println("........end process.......");
} catch (Exception e)
{
System.out.println(e);
}
}
}