如何从 Java 执行 Python 脚本(通过命令行)? [英] How to execute Python script from Java (via command line)?

查看:56
本文介绍了如何从 Java 执行 Python 脚本(通过命令行)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以毫无问题地从 Java 执行 lspwd 等 Linux 命令,但无法执行 Python 脚本.

I can execute Linux commands like ls or pwd from Java without problems but couldn't get a Python script executed.

这是我的代码:

Process p;
try{
    System.out.println("SEND");
    String cmd = "/bash/bin -c echo password| python script.py '" + packet.toString() + "'";
    //System.out.println(cmd);
    p = Runtime.getRuntime().exec(cmd); 
    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String s = br.readLine(); 
    System.out.println(s);
    System.out.println("Sent");
    p.waitFor();
    p.destroy();
} catch (Exception e) {}

什么都没发生.它到达了 SEND 但它在它之后就停止了......

Nothing happened. It reached SEND but it just stopped after it...

我正在尝试执行一个需要 root 权限的脚本,因为它使用串行端口.另外,我必须传递一个带有一些参数的字符串(数据包).

I am trying to execute a script which needs root permissions because it uses serial port. Also, I have to pass a string with some parameters (packet).

推荐答案

您不能像在示例中那样在 Runtime.getRuntime().exec() 中使用 PIPE.PIPE 是外壳的一部分.

You cannot use the PIPE inside the Runtime.getRuntime().exec() as you do in your example. PIPE is part of the shell.

你可以这样做

  • 将您的命令放入 shell 脚本并使用 .exec()
  • 执行该 shell 脚本
  • 你可以做类似下面的事情

  • Put your command to a shell script and execute that shell script with .exec() or
  • You can do something similar to the following

String[] cmd = {
        "/bin/bash",
        "-c",
        "echo password | python script.py '" + packet.toString() + "'"
    };
Runtime.getRuntime().exec(cmd);

这篇关于如何从 Java 执行 Python 脚本(通过命令行)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆