Python 3 fileinput:压缩和endcoded文件挂钩?

时间:2016-11-22 00:06:33

标签: python python-3.x

我需要解压缩和解码一组gzip压缩文件,并且filehook模块(https://docs.python.org/3/library/fileinput.html)有两个挂钩,但我无法同时应用这两个:

是否存在将这两个挂钩应用于同一个FileInput实例的语法?

fi = fileinput.FileInput(openhook=fileinput.hook_compressed)
fi = fileinput.FileInput(openhook=fileinput.hook_encoded("iso-8859-1"))

2 个答案:

答案 0 :(得分:2)

查看the source并注意到gzip.openbz2.open支持编码参数,打印自己不应该太难:

def hook_compressed_encoded(encoding):
    def hook_compressed(filename, mode):
        ext = os.path.splitext(filename)[1]
        if ext == '.gz':
            import gzip
            return gzip.open(filename, mode, encoding=encoding)
        elif ext == '.bz2':
            import bz2
            return bz2.open(filename, mode, encoding=encoding)
        else:
            return open(filename, mode, encoding=encoding)
    return hook_compressed

fi = fileinput.FileInput(openhook=hook_compressed_encoded('iso-8859-1'))

答案 1 :(得分:0)

不,没有办法将这些结合起来。您甚至无法通过传递文字模式将pipeline { agent none stages { stage('create hosts') { steps { echo "Hello! , This build for create VMs " build job: 'createhosts', parameters: [ ********* ********* some parameters ] } } stage ('CD job ') { steps { echo "This build for configure VMs " build job: 'CD' } } stage ('Delete VMs') { steps { echo "This job is required a host file as input for approval to Delete VMs" input "approve for deletion" build job: 'delete_vms' } } } } 与默认hook_compressed一起使用,因为utf8假设FileInput始终表示文字。rt拒绝接受r。 / p>

唯一的解决方案是自己编写。

def hook_compressed_encoded(encoding):
    def hook(filename, mode):
        ext = os.path.splitext(filename)[1]
        if ext == '.gz':
            import gzip
            return gzip.open(filename, 'rt', encoding=encoding)
        elif ext == '.bz2':
            import bz2
            return bz2.open(filename, 'rt', encoding=encoding)
        else:
            return open(filename, 'rt', encoding=encoding)
    return hook

fi = fileinput.FileInput(openhook=hook_compressed_encoded('iso-8859-1'))