简体   繁体   中英

Handling Java stdout and stderr in Perl

I am trying to run a Java program from my Perl script. I would like to avoid using System.exit(1) and System.exit(-1) commands in Java. I am however printing to STDOUT and STDERR from Java. In my Perl script, I am reading from Java's stdout and using that line by line output. How do I print stderr and fail if I ever see stderr? This is what I have so far:

my $java_command = ...;
open(DATA, ">$java_command"); 
while (<DATA>) {
    chomp($_);
    ....
    ....
}

This has been discussed here: How can I capture STDERR from an external command?

So you can do something like:

open (DATA, "($java_command_with_args | sed 's/^/STDOUT:/') 2>&1 |");
while (<DATA>) {
    if (s/^STDOUT://)  {
        print "line from stdout: ", $_;
    } else {

        print "line from stderr: ", $_;
        die("Saw something on stderr");
    }
}

Look at the perl documentation for FAQ How-can-I-capture-STDERR-from-an-external-command . This will brief you all the details about capturing and discarding STDOUT and STDERR.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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