gpt4 book ai didi

java - 无法从 Apache Commons Exec 获取输出

转载 作者:行者123 更新时间:2023-12-02 12:05:27 25 4
gpt4 key购买 nike

虽然标题非常相似,但这个问题Process output from apache-commons exec 重复。 .

我正在尝试使用 apache-commons exec 获取命令的输出。这就是我正在做的事情

import org.apache.commons.exec.*;
import java.io.ByteArrayOutputStream;

public class Sample {


private static void runCommand(String cmd) throws Exception {
ByteArrayOutputStream stdout = new ByteArrayOutputStream();
PumpStreamHandler psh = new PumpStreamHandler(stdout);
CommandLine cl = CommandLine.parse(cmd);
DefaultExecutor exec = new DefaultExecutor();
exec.setStreamHandler(psh);
exec.execute(cl);
System.out.println(stdout.toString());
}

public static void main(String... args) throws Exception {

String cmd1 = "python -c \"print(10)\"";
String cmd2 = "python -c \"import datetime; print(datetime.datetime.now())\"";

runCommand(cmd1); // prints 10
runCommand(cmd2); // should print the current datetime, but does not!
}
}

问题是 runCommand(cmd2) 不会在输出中打印任何内容。当我尝试在终端上运行该命令时,它工作正常。

我已经在使用和不使用 IDE 的情况下尝试过该程序,因此我确信这与 IDE 控制台无关。

这是屏幕截图

enter image description here

这是终端的屏幕截图

enter image description here

在终端上运行Python命令

enter image description here

最佳答案

它在我的 IDEA PC 上运行良好。尝试重新创建项目。添加有关您的环境的更多信息。尝试将您的Python代码放入.py文件中并像“python test.py”一样运行它。

screen

关于java - 无法从 Apache Commons Exec 获取输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46937202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com