什么是Java的Pythons子进程shell = True属性的等效项? [英] what is the Java equivalent of Pythons's subprocess shell=True property?

查看:50
本文介绍了什么是Java的Pythons子进程shell = True属性的等效项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用python很长时间了.python的system和subprocess方法可以使用shell = True样式来产生一个设置env vars的中间过程.在命令运行之前.我一直在来回使用Java,并使用Runtime.exec()执行shell命令.

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();
    }

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

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.

推荐答案

两种可能的方式:

  1. 运行时

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

  • ProcessBuilder (推荐)

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


  • 正如Stephen指出的那样,为了通过将整个命令作为单个String传递来执行构造,设置 command 数组的语法应为:

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

    Bash文档

    如果存在-c选项,则从中读取命令字符串.

    示例:

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

    永远有用的*

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


    * 可能没有用

    这篇关于什么是Java的Pythons子进程shell = True属性的等效项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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