【问题标题】:using java to call and run python but no result. processbuilder runtime使用java调用并运行python但没有结果。进程构建器运行时
【发布时间】:2016-12-23 03:17:11
【问题描述】:

我尝试了runtime和processbuilder都在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?

【问题讨论】:

    标签: java python runtime processbuilder


    【解决方案1】:

    您的代码绝对正确。以下是在标准 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);
        }
       }
       }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-17
      • 1970-01-01
      • 2013-04-21
      • 1970-01-01
      相关资源
      最近更新 更多