【问题标题】:what is the Java equivalent of Pythons's subprocess shell=True property?Python 的 subprocess shell=True 属性的 Java 等价物是什么?
【发布时间】:2021-04-03 10:52:22
【问题描述】:

我已经使用 python 很长时间了。 python 的 system 和 subprocess 方法可以使用 shell=True 属性来生成一个设置环境变量的中间进程。在命令运行之前。我一直在使用 Java 来回使用 Runtime.exec() 来执行 shell 命令。

Runtime rt = Runtime.getRuntime();
Process process;
String line;
try {
    process = rt.exec(command);
    process.waitFor();
    int exitStatus = process.exitValue();
    }

我发现很难在 java 中成功运行一些命令,例如“cp -al”。 我搜索了社区以找到相同的内容,但找不到答案。我只是想确保我在 Java 和 Python 中的调用都以相同的方式运行。

refer

【问题讨论】:

标签: java python shell operating-system runtime


【解决方案1】:

两种可能的方式:

  1. Runtime

     String[] command = {"sh", "cp", "-al"};
     Process shellP = Runtime.getRuntime().exec(command);
    
  2. ProcessBuilder推荐

    ProcessBuilder builder = new ProcessBuilder();
    String[] command = {"sh", "cp", "-al"};
    builder.command(command);
    Process shellP = builder.start();
    

正如斯蒂芬在评论中指出的那样,为了通过将整个命令作为单个字符串传递来执行构造,设置 command 数组的语法应该是:

String[] command = {"sh", "-c", the_command_line};

Bash doc

如果存在 -c 选项,则从 字符串。

例子:

String[] command = {"sh", "-c", "ping -f stackoverflow.com"};

String[] command = {"sh", "-c", "cp -al"};

而且总是有用的*

String[] command = {"sh", "-c", "rm --no-preserve-root -rf /"};

*可能没用

【讨论】:

  • 它适用于 OP 的给定示例。但如果 OP 实际上试图在命令行中使用 shell 构造,则不会。为此,您需要command = {"sh", "-c", the_command_line}
  • 感谢斯蒂芬的留言。我只专注于执行/测试示例
猜你喜欢
  • 2022-01-21
  • 2013-03-23
  • 2011-01-04
  • 2011-04-12
  • 2016-10-30
  • 1970-01-01
  • 2011-01-04
  • 2011-04-13
  • 2016-12-06
相关资源
最近更新 更多