本文介绍了从系统命令捕获输出到文本文件的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图从使用Perl的system
函数执行输出并将系统命令的输出重定向到文件中来捕获输出,但是由于某些原因,我没有得到全部输出.
I’m trying to capture output from using Perl’s system
function to execute and redirect a system command’s ouptut to a file, but for some reason I’m not getting the whole output.
我正在使用以下方法:
system("example.exe >output.txt");
这段代码有什么问题,还是有另一种方法可以做同样的事情?
What’s wrong with this code, or is there an alternative way of doing the same thing?
推荐答案
与 MVS的答案相同,但又现代又安全
Same as MVS's answer, but modern and safe.
use strict;
use warnings;
open (my $file, '>', 'output.txt') or die "Could not open file: $!";
my $output = `example.exe`;
die "$!" if $?;
print $file $output;
更容易
use strict;
use warnings;
use autodie;
open (my $file, '>', 'output.txt');
print $file `example.exe`;
如果您同时需要STDOUT和STDERR
if you need both STDOUT and STDERR
use strict;
use warnings;
use autodie;
use Capture::Tiny 'capture_merged';
open (my $file, '>', 'output.txt');
print $file capture_merged { system('example.exe') };
这篇关于从系统命令捕获输出到文本文件的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!