【问题标题】:Run Python script from Java从 Java 运行 Python 脚本
【发布时间】:2016-04-16 05:27:05
【问题描述】:

我正在尝试在 Java 中运行 .py 脚本,但是当我运行 java 代码时它没有显示任何输出。我做错了什么?我试过了:

ArrayList<String> command = new ArrayList<String>();
    //xterm will be launched, if platform is Linux.
    command.add("xterm");
    command.add("-c");
    command.add("python");
    command.add("/home/clef/Escritorio/use_archive.py");
    command.add("/home/clef/classification/STOP_WORDS.tar.gz");
    command.add("/home/clef/Escritorio/Prueba_linea/000006/6.jpg");
    command.add(" > ~/Escritorio/mike.txt");
    //command.add("--revert");    // switch to revert the patch

    ProcessBuilder pb = new ProcessBuilder(command);

    Process p = null;

    if (pb != null) {

        try {
            p = pb.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (p != null) {
            try {
                p.waitFor();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

    String line = "";
    ArrayList<String> allOut = new ArrayList<>();
    System.out.println("salida");
    try
    {
        System.out.println("SALIDA-----------:");
        while ((line = reader.readLine())!= null)
        {
            System.out.println(line);
            allOut.add(line);
        }
    } catch (IOException ex)
    {
        //allOut = "0";
        //Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        //System.out.println("erro3");        }
        System.out.println("error");
    }

脚本来自 NVIDIA DIGITS 框架,但我无法从 Java 运行任何 python 脚本。如果我在终端中运行 .py 脚本,我会得到输出:

Unknown file: solver.prototxt
    Unknown file: train_val.prototxt
    Processed 1/1 images in 0.076470 seconds ...
    -------- Prediction for /home/clef/Escritorio/Prueba_linea/000006/6.jpg --------
     51.4607% - "0"
      7.7899% - "1"
      5.7782% - "2"
      5.6086% - "3"
      5.2513% - "4"

    Script took 0.523756 seconds.

【问题讨论】:

  • 你为什么使用 xterm?
  • 我也试过 /bin/bash 但效果不佳
  • 你不需要使用其中任何一个,python 会自己运行...
  • 我是这么认为的,但是如果我从 java 运行它,脚本就不起作用,我尝试像 'ls' 'cd ..' 这样的命令,但我不能从 java 运行 python 脚本。跨度>
  • “不起作用”是什么意思

标签: java python digits pycaffe


【解决方案1】:

试试这个:

Process p = Runtime.getRuntime().exec("python yourapp.py");

Exec 运行系统命令,如果您安装了 python,它将像在操作系统的命令终端中一样运行 python 文件。

【讨论】:

    猜你喜欢
    • 2018-01-08
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    相关资源
    最近更新 更多