what is the Java equivalent of Pythons's subprocess shell=True property?

大憨熊 提交于 2021-02-16 15:02:21

问题


I've been using python for a long time. python's system and subprocess methods can take shell=True attibute to spawn an intermediate process setting up env vars. before the command runs. I've be using Java back and forth and using Runtime.exec() to execute shell command.

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

I find difficulty to run some commands in java with success like "cp -al". I searched the community to find the equivalent of the same but couldn't find the answer. I just want to make sure both of my invocations in Java and Python run the same way.

refer


回答1:


Two possible ways:

  1. Runtime

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

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

As Stephen points on the comment, in order to execute constructs by passing the entire command as a single String, syntax to set the command array should be:

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

Bash doc

If the -c option is present, then commands are read from string.

Examples:

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

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

And the always useful*

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

*may not be useful



来源:https://stackoverflow.com/questions/65447595/what-is-the-java-equivalent-of-pythonss-subprocess-shell-true-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!