Linux 如何从 Java 执行 Python 脚本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16447410/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:53:45  来源:igfitidea点击:

How to execute Python script from Java?

javapythonlinux

提问by Biribu

I can execute Linux commands like lsor pwdfrom Java without problems but couldn't get a Python script executed.

我可以毫无问题地执行类似Javalspwd从 Java执行 Linux 命令,但无法执行 Python 脚本。

This is my code:

这是我的代码:

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) {}

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

什么都没有发生。它到达了 SEND 但它只是在它之后停止了......

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).

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

采纳答案by Alper

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

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

You could do either

你可以这样做

  • 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);
    
  • 将您的命令放入 shell 脚本并使用.exec()或执行该 shell 脚本
  • 您可以执行类似于以下操作

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

回答by jtahlborn

@Alper's answer should work. Better yet, though, don't use a shell script and redirection at all. You can write the password directly to the process' stdin using the (confusingly named) Process.getOutputStream().

@Alper 的回答应该有效。不过,更好的是,根本不要使用 shell 脚本和重定向。您可以使用 (混淆命名) 将密码直接写入进程的标准输入Process.getOutputStream()

Process p = Runtime.exec(
    new String[]{"python", "script.py", packet.toString()});

BufferedWriter writer = new BufferedWriter(
    new OutputStreamWriter(p.getOutputStream()));

writer.write("password");
writer.newLine();
writer.close();

回答by hd1

You would do worse than to try embedding jythonand executing your script. A simple example should help:

你会比尝试嵌入 jython并执行你的脚本更糟糕。一个简单的例子应该会有所帮助:

ScriptEngine engine = new ScriptEngineManager().getEngineByName("python");

// Using the eval() method on the engine causes a direct
// interpretataion and execution of the code string passed into it
engine.eval("import sys");
engine.eval("print sys");

If you need further help, leave a comment. This does not create an additional process.

如果您需要进一步的帮助,请发表评论。这不会创建额外的过程。

回答by Chandu Arya

First, open terminal and type "which python3". You will get the complete path of python3. For example "/usr/local/bin/python3"

首先,打开终端并输入“which python3”。您将获得python3的完整路径。例如“/usr/local/bin/python3”

String[] cmd = {"/usr/local/bin/python3", "arg1", "arg2"};
Process p = Runtime.getRuntime().exec(cmd);
p.waitFor();

String line = "", output = "";
StringBuilder sb = new StringBuilder();

BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = br.readLine())!= null) {sb = sb.append(line).append("\n"); }

output = sb.toString();
System.out.println(output);