简体   繁体   中英

Perl - capture system() error

I am converting some jpg images to png w/ imagemagick & have the following in perl:

system("convert $jpg $png");
print "$?\n";

Is there a way to capture the actual errors from imagemagick (rather than just whether or not it executed successfully as I have in the code above)?

note: I use imagemagick solely as an example....this is more a general question on how to capture errors from whatever program that system() executes.

thx!

cribbed from the IPC::Run manpage:

use IPC::Run qw{run timeout};
my ($in, $out, $err);

run [convert => ($jpg, $png)], \$in, \$out, \$err, timeout( 10 ) or die "$err (error $?)"

You could also use PerlMagick like this:

use Image::Magick;

my $p = new Image::Magick;
$p->Read($jpg);
$p->Write($png);

As noted by MkV, IPC::Run is the best solution. Use that if possible.

If you are in a broken environment that does not allow you to install CPAN modules, a grotty workaround is to do a pipe hack with shell redirection:

open my $fh, '-|', "convert \Q$jpg\E \Q$png\E 2>&1"
    or die "Can't launch 'convert'";

...and then read and parse $fh as appropriate. The \\Q ... \\E escapes the filenames, and is necessary to avoid problems with filenames that contain spaces or other shell metacharacters. You should also use them with system() to avoid the same problems.

For best results see: How-can-I-capture-STDERR-from-an-external-command?

Also read the previous one:

Why can't I get the output of a command with system()?

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