简体   繁体   English

如何从 Java 执行 Python 脚本(通过命令行)?

[英]How to execute Python script from Java (via command line)?

I can execute Linux commands like ls or pwd from Java without problems but couldn't get a Python script executed.我可以毫无问题地从 Java 执行lspwd等 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.我正在尝试执行一个需要 root 权限的脚本,因为它使用串行端口。 Also, I have to pass a string with some parameters (packet).另外,我必须传递一个带有一些参数(数据包)的字符串。

You cannot use the PIPE inside the Runtime.getRuntime().exec() as you do in your example.您不能像在示例中那样在Runtime.getRuntime().exec()使用 PIPE。 PIPE is part of the shell. PIPE 是外壳的一部分。

You could do either你可以这样做

  • Put your command to a shell script and execute that shell script with .exec() or将您的命令放入 shell 脚本并使用.exec()
  • You can do something similar to the following您可以执行类似于以下操作

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

@Alper's answer should work. @Alper 的回答应该有效。 Better yet, though, don't use a shell script and redirection at all.不过,更好的是,根本不要使用 shell 脚本和重定向。 You can write the password directly to the process' stdin using the (confusingly named) Process.getOutputStream() .您可以使用(名称混淆) 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();

You would do worse than to try embedding jython and executing your script.你会比尝试嵌入 jython并执行你的脚本更糟糕。 A simple example should help:一个简单的例子应该会有所帮助:

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.这不会创建额外的过程。

First, open terminal and type "which python3".首先,打开终端并输入“which python3”。 You will get the complete path of python3.您将获得python3的完整路径。 For example "/usr/local/bin/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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM