【问题标题】:Calling command from Perl, need to see output从 Perl 调用命令,需要查看输出
【发布时间】:2010-12-14 20:08:23
【问题描述】:

我需要从 perl 中调用一些 shell 命令。这些命令需要相当长的时间才能完成,所以我想在等待完成时查看它们的输出。

system 函数在完成之前不会给我任何输出。

exec 函数给出输出;但是,它从那时起退出了 perl 脚本,这不是我想要的。

我在 Windows 上。有没有办法做到这一点?

【问题讨论】:

    标签: perl shellexecute


    【解决方案1】:

    Backticks,或qx 命令,在单独的进程中运行命令并返回输出:

    print `$command`;
    print qx($command);
    

    如果您希望查看中间输出,请使用open 创建命令输出流的句柄并从中读取。

    open my $cmd_fh, "$command |";   # <---  | at end means to make command 
                                     #         output available to the handle
    while (<$cmd_fh>) {
        print "A line of output from the command is: $_";
    }
    close $cmd_fh;
    

    【讨论】:

    • @Nathan - 可能,但对于外部命令来说,具有良好的缓冲行为更为重要——要么不缓冲其输出,要么以足够快的速度产生输出,以至于缓冲无关紧要。
    • ++ 用于反引号和管道打开 - 我唯一的挑剔是没有提到该技术的 3+ args 版本,这应该更安全:打开我的 $cmd_fh, '-| ',$命令;另外,链接:perldoc.perl.org/perlopentut.html#Pipe-Opens
    猜你喜欢
    • 2011-01-10
    • 1970-01-01
    • 2011-05-23
    • 1970-01-01
    • 2014-08-10
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    相关资源
    最近更新 更多