【问题标题】:How can I get the command-line output of a DOS tool using Perl?如何使用 Perl 获取 DOS 工具的命令行输出?
【发布时间】:2009-02-21 03:12:27
【问题描述】:

我想在 Perl 脚本中使用 Windows 内置 FTP 工具来测量链接的吞吐量。因此该脚本会创建以下命令脚本:

open <ip>
<username>
<password>
hash
get 500k.txt
quit

之后我使用以下 Perl 代码运行命令脚本:

system(@args);
@args = ("ftp", "-s:c:\\ftp_dl.txt");
system(@args);

如果我在 DOS 框内运行命令,输出如下所示:

ftp> open <ip>
Connected to <ip>
220 "Welcome to the fast and fabulous DUFTP005 ftp-server :-) "
User (<ip>:(none)):
331 Please specify the password.

230 Login successful.
ftp> hash
Hash mark printing On  ftp: (2048 bytes/hash mark) .
ftp> get 500k.txt
200 PORT command successful. Consider using PASV.
150 Opening BINARY mode data connection for 500k.txt (14336 bytes).
#######
226 File send OK.
ftp: 14336 bytes received in 0.00Seconds 14336000.00Kbytes/sec.
ftp> quit
221 Goodbye.

为了能够获得吞吐量,我需要提取该行:

 ftp: 14336 bytes received in 0.00Seconds 14336000.00Kbytes/sec.

我对 Perl 不是很熟悉。有人知道如何获得那条线吗?

【问题讨论】:

    标签: perl command-line ftp stdout


    【解决方案1】:

    在管道模式下使用open

    open($filehandle, "$command|") or die "did not work: $! $?";
    while(<$filehandle>)
    {
    #do something with $_
    }
    

    或使用反引号:

    my  @programoutput=`$command`
    

    【讨论】:

    • 但是请注意,这两个都只捕获命令的标准输出。您必须做一些额外的工作才能获得标准错误。我不知道 DOS ftp 命令使用了哪些。
    【解决方案2】:

    can't get the output with system()

    改为使用反踢:

    my $throughput = 0;
    my $output = `ftp -s:c:\\ftp_dl.txt`;
    if (($? == 0) && ($output =~ /([\d+\.]+)\s*K?bytes\/sec/m)) {
        $throughput = $1;
    }
    

    $output 将包含执行ftp 命令的所有行(但不包含发送到STDERR 的任何错误消息)。
    然后我们检查 ftp 是否返回成功 (0) 以及我们是否在输出中的某处获得了吞吐量。
    如果是这样,我们将$throughput 设置为它。

    这是 Perl,有很多方法可以做到这一点:

    您还可以使用支持 Windows 的 Net::FTP 模块来处理文件传输,并使用像 Time::HiRes 这样的计时模块来计时并计算您的吞吐量。

    这样您就不会依赖 ftp 程序(例如,您的脚本将无法在本地化版本的 Windows 上运行而无需大量返工,并且您需要依赖安装在同一位置的 ftp 程序)。

    【讨论】:

      【解决方案3】:

      请参阅perlfaq8,其中有几个与此主题相关的答案。这个问题你可能需要的是:

      另外,您可能对标准库中的一些 IPC(进程间通信)Perl 模块感兴趣:

      • IPC::Open2
      • IPC::Open3

      一些 Perl 文档可能也有帮助:

      如果您不熟悉 Perl 文档,可以查看我的 Perl documentation documentation

      祝你好运,

      【讨论】:

        【解决方案4】:

        您应该尝试使用更适合该任务的libcurl

        有一个easy to use API

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-08-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-05-17
          • 2015-11-01
          • 1970-01-01
          相关资源
          最近更新 更多