开发者

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 开发者_如何学JAVAas 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);


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()?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜