简体   繁体   English

Python如何将子流程定向到输出文件

[英]Python how to direct subprocess to output file

I have created a script that receives a bunch of log files as input in order to do some pattern matching. 我创建了一个脚本,该脚本接收一堆日志文件作为输入,以便进行某些模式匹配。 However, my "processFiles" method is not working properly. 但是,我的“ processFiles”方法无法正常工作。 It should write all data to "fileDest". 它应该将所有数据写入“ fileDest”。 But the created file remains empty. 但是创建的文件仍然为空。 If I put a "print processFiles" statement under the function itself I can see lines as throughput on my terminal. 如果在函数本身下放置“ print processFiles”语句,则可以在终端上看到行作为吞吐量。

To make matters more interesting, bunzip2 reports this error while I run the script: 为了使事情更有趣,当我运行脚本时,bunzip2报告此错误:


Proccessing /opt/syslog/app/applog-20140314.bz2. 处理/opt/syslog/app/applog-20140314.bz2。 bunzip2: Can't open input file > : No such file or directory. bunzip2:无法打开输入文件>:没有此类文件或目录。 bunzip2: Compressed file ends unexpectedly; bunzip2:压缩文件意外结束; perhaps it is corrupted? 也许它已损坏? *Possible reason follows. *可能的原因如下。 bunzip2: No such file or directory Input file = /var/tmp/parsed_applog-20140314.decompressed, output file = (stdout) bunzip2:无此类文件或目录输入文件= /var/tmp/parsed_applog-20140314.decompressed,输出文件=(stdout)


It seems something in my code sends the output to stdout. 似乎我的代码中的某些内容将输出发送到stdout。 And not to the file. 而不是文件。

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

' > ' is a shell redirection syntax. ' > '是shell重定向语法。 Popen doesn't spawn the shell unless you ask (you shouldn't). 除非您提出要求,否则Popen不会生成外壳程序(您不应该这样做)。 If you want to redirect the output of a subprocess to a file then use stdout=file_object parameter eg: 如果要将子流程的输出重定向到文件,请使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM