Python如何将子进程直接输出到输出文件

时间:2014-03-17 14:19:07

标签: python unix subprocess logfiles

我创建了一个脚本,它接收一堆日志文件作为输入,以便进行一些模式匹配。 但是,我的" processFiles"方法无法正常工作。 它应该将所有数据写入" fileDest"。但是创建的文件仍然是空的。 如果我放一个" print processFiles"函数本身下的语句我可以在终端上看到作为吞吐量的行。

为了使问题更有趣,bunzip2在我运行脚本时会报告此错误:


处理/opt/syslog/app/applog-20140314.bz2。 bunzip2:无法打开输入文件> : 没有相应的文件和目录。 bunzip2:压缩文件意外结束;也许它已经腐败了? *可能的原因如下。 bunzip2:没有这样的文件或目录输入文件= /var/tmp/parsed_applog-20140314.decompressed,输出文件=(stdout)


我的代码中的某些内容似乎将输出发送到stdout。而不是文件。

def parse_log_files(self):
    sub_dir = os.listdir(self.base_path)
    for directory in sub_dir:
        if re.search('app\d+', directory):
            fileInput = self.base_path + '/' + directory + '/applog-' + str(self.date.strftime('%Y%m%d')) + '.bz2'
            fileDest = '/var/tmp/parsed_log_files-'  + str(self.date.strftime('%Y%m%d')) + '.decompressed'
            if not os.path.isfile(fileDest):
                subprocess.Popen(['touch',fileDest]).communicate()[0]
            proccessFiles = subprocess.Popen(['/bin/bunzip2','-cd',fileInput,' > ',fileDest],stdout=subprocess.PIPE).communicate()[0]
            accessFileHandle =  open(self.file_out, 'r')
            readFileHandle = accessFileHandle.readlines()
            print "Proccessing %s." % fileInput

1 个答案:

答案 0 :(得分:1)

' > '是一个shell重定向语法。除非你问(你不应该),否则Popen不会产生shell。如果要将子进程的输出重定向到文件,请使用stdout=file_object参数,例如:

from subprocess import check_call

with open('/path/to/output', 'wb', 0) as output_file:
    check_call(['command', 'arg1', 'arg2'], stdout=output_file)