Python如何将子进程定向到输出fi

2024-09-30 06:28:40 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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


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

Tags: 文件pathself脚本appstdoutdirectorysubprocess
1条回答
网友
1楼 · 发布于 2024-09-30 06:28:40

' > '是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)

相关问题 更多 >

    热门问题