从Python运行Perl脚本并将输出写入文件时,为什么文件为空?

时间:2015-03-18 16:16:12

标签: python linux perl

我有以下Perl脚本,它将以太网接口名称和传输速率作为参数:

#!/usr/bin/perl -w

$prevRXpacks = 0;
$prevTXpacks = 0;
$prevRXbytes = 0;
$prevTXbytes = 0;
$recentRXpacks = 0;
$recentTXpacks = 0;
$recentRXbytes = 0;
$recentTXbytes = 0;
$time_wait_default = 2;
$time_run_default = 0;
$prev = 0;
$overflow = 4 * 1024 * 1024 * 1024;
$k = 1000;
$m = $k * $k;
$format = "";
$format_value = 1;
$hdr_format = "Bytes/s";

if ( defined ($ARGV[0]) && ($ARGV[0] eq "--help") ) {
    print "Usage: $0 <device> [-r runtime] [-d delaytime]\n";
    print " -r     time to run traffic monitor in seconds (default = 0 <- forever)\n";
    print " -d     delay between two records in seconds (default = $time_wait_default)\n";
    print " -k, -K    print transfer rate in kbits/s or KBytes/s\n";
    print " -m, -M    print transfer rate in mbits/s or MBytes/s\n";
    die "\n";
}

open (OUT, "/dev/null");
select (OUT);
if ( !defined($ARGV[0]) || !`/sbin/ifconfig $ARGV[0]` ) {
    close (OUT);
    select (STDOUT);
    die "Usage $0 <device> [-r runtime] [-d delaytime] [-kmKM].\nTry --help for more.\n";
}
close (OUT);
select (STDOUT);

$time_wait = $time_wait_default;
$time_run = $time_run_default;

$i = 1;

while ( defined ($ARGV[$i]) ) {
    if ($ARGV[$i] eq "-d") {
        $time_wait = $ARGV[++$i] || $time_wait_default;
    }
    if ($ARGV[$i] eq "-r") {
        $time_run = $ARGV[++$i] || $time_run_default;
    }
    if ($ARGV[$i] eq "-K") {
        $format = $hdr_format = "KBytes/s";
        $format_value = $k;
    }
    if ($ARGV[$i] eq "-k") {
        $format = $hdr_format = "Kbits/s";
        $format_value = $k/8;
    }
    if ($ARGV[$i] eq "-M")  {
        $format = $hdr_format = "MBytes/s";
        $format_value = $m;
    }
    if ($ARGV[$i] eq "-m") {
        $format = $hdr_format = "Mbits/s";
        $format_value = $m/8;
    }

    $i++;
}

print "Traffic monitoring...\n";

# main loop
$time_loop = $time_run + time();

while ( time() < $time_loop || !$time_run ) {
    $recent = time();
    foreach $_ (`/sbin/ifconfig $ARGV[0]`) {
        if (/RX.*packets/) {
            ($blabla1, $blabla2, $blabla3) = split(/\s+/);
            ($blabla1, $recentRXpacks, $blabla2) = split(/:/, $blabla3);
        }
        if (/TX.*packets/) {
            ($blabla1, $blabla2, $blabla3) = split(/\s+/);
            ($blabla1, $recentTXpacks, $blabla2) = split(/:/, $blabla3);
        }
        if (/RX.*bytes/) {
            ($blabla1, $blabla2, $blabla3) = split(/:/);
            ($recentRXbytes) = split(/ /, $blabla2);
            ($recentTXbytes) = split(/ /, $blabla3);
        }
    }

    if ( ($recent > $prev) && $prev) {
        $interval = $recent - $prev;
#       $interval = $time_wait;

        $RXpacks = round (rate ($prevRXpacks, $recentRXpacks, $interval));
        $TXpacks = round (rate ($prevTXpacks, $recentTXpacks, $interval));
        $RXbytes = round (rate ($prevRXbytes, $recentRXbytes, $interval)/$format_value);
        $TXbytes = round (rate ($prevTXbytes, $recentTXbytes, $interval)/$format_value);

        write;
    }

    $prev = $recent;
    $prevRXpacks = $recentRXpacks;
    $prevTXpacks = $recentTXpacks;
    $prevRXbytes = $recentRXbytes;
    $prevTXbytes = $recentTXbytes;

    $time_delay = $time_wait + time();
    while (time() < $time_delay) {}
}

format STDOUT_TOP =
RX [packets/s]    TX [packets/s]    RX [@<<<<<<<]        TX [@<<<<<<<]
                   $hdr_format,           $hdr_format
.

format STDOUT =
@<<<<<<<<<<<<<<    @<<<<<<<<<<<<<<    @<<<<<<<<<<<<<<<<<<<<<<    @<<<<<<<<<<<<<<<<<<<<<<
$RXpacks,    $TXpacks,    $RXbytes." ".$format,    $TXbytes." ".$format
.

sub rate {
    my ($prev, $recent);
    ($prev, $recent, $interval) = @_;
    if (($recent = $recent - $prev) <0) {
        $recent += $overflow;
    }
    return $recent/$interval;
}

sub round {
    my ($mod, $result);
    $result = int ($_[0]);
    $mod = ($_[0] - $result) ;
    if ( $mod >= 0.5) {
        $result++;
    }
    return $result;
}

我尝试从Python运行上面的脚本,并使用以下代码将输出写入文件:

#!/usr/bin/python

import sys
import subprocess
import datetime
import os
import time

command = ["perl", "/root/Desktop/myethtraffic.pl", "eth0", "M"]

dir_name = "/root/Desktop/"

logfile = open("/root/Desktop/aa1a.txt", 'w')

proc = subprocess.Popen(command)
for line in proc.stderr:
        logfile.write(line)

文件已创建但为空。我该如何解决这个问题?

3 个答案:

答案 0 :(得分:1)

参考文档https://docs.python.org/2/library/subprocess.html#popen-constructor我认为在调用stderr=subprocess.PIPE时需要明确指定POpen,否则子进程stderr将连接到主程序stderr。

试试这个:

proc=subprocess.Popen(command, stderr=subprocess.PIPE)

测试:

#!/usr/bin/python

import sys
import subprocess
import datetime
import os
import time

command = ["perl", "-e", "warn 'abc'"]

logfile = open("a.log", 'w')

proc=subprocess.Popen(command, stderr=subprocess.PIPE)
for line in proc.stderr:
        logfile.write(line)

编辑:您的perl进程是否实际写入stderr或stdout?

答案 1 :(得分:1)

您可以将文件描述符传递给Popen,程序将直接写入文件,您无需读取管道。我有点困惑,因为你试图阅读stderr而不是stdout,所以写了一个将管道写入一个文件的例子。

#!/usr/bin/python

import sys
import subprocess
import datetime
import os
import time

command = ["perl","/root/Desktop/myethtraffic.pl", "eth0", "M"]

dir_name = "/root/Desktop/"

logfile = open("/root/Desktop/aa1a.txt", 'w')

proc=subprocess.Popen(command, 
    stdout=open("/root/Desktop/aa1a.txt", 'w'), 
    stderr=subprocess.STDOUT)
proc.wait()

答案 2 :(得分:0)

perl可能不在您的路径中。 将完整路径传递给perl而不是字符串“perl”,例如

command = ["/usr/bin/perl", ...]

另一种选择是使用shell运行命令,以模拟直接从命令行执行时的运行方式。

subprocess.Popen("/root/Desktop/myethtraffic.pl eth0 M", ..., shell=True)