【问题标题】:Python how to direct subprocess to output filePython如何将子进程定向到输出文件
【发布时间】:2014-04-22 19:12:15
【问题描述】:

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

为了让事情更有趣,bunzip2 在我运行脚本时报告了这个错误:


处理 /opt/syslog/app/applog-20140314.bz2。 bunzip2:无法打开输入文件>:没有这样的文件或目录。 bunzip2:压缩文件意外结束;也许它已损坏? *可能的原因如下。 bunzip2: No such file or directory 输入文件 = /var/tmp/parsed_applog-20140314.decompressed, 输出文件 = (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

【问题讨论】:

    标签: python unix subprocess logfiles


    【解决方案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)
    

    【讨论】:

    • 误读错误信息,确实是这个问题。干杯!
    猜你喜欢
    • 2017-06-25
    • 2015-04-04
    • 1970-01-01
    • 2018-01-07
    • 1970-01-01
    • 2021-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多