【问题标题】:print tar.gz to stdout in python在 python 中将 tar.gz 打印到标准输出
【发布时间】:2013-11-13 16:28:40
【问题描述】:

我可以创建一个 .tar.gz 文件使用

with tarfile.open(archive, 'w:gz') as archive_fd:
    add_files_to_tar('.', archive_fd)

这很好用。但有时我想将这些文件打印到stdout(如果我通过 SSH 执行命令)

有人知道怎么做吗?我的旧 bash 代码是这样的

tar -czf - $files >&1

tar -czf - $files >/filename

【问题讨论】:

  • 什么是add_files_to_tar
  • 一种将文件添加到存档的方法。您可以将其替换为 archive_fd.add('filename')

标签: python gzip tar


【解决方案1】:

认为您可以在流模式下打开 tar 文件并将其传递给 sys.stdout:

import sys
with tarfile.open(fileobj=sys.stdout, mode='w|gz') as archive_fd:
    add_files_to_tar('.', archive_fd)

tarfile 文档说这在完成时不会关闭标准输出。

【讨论】:

    【解决方案2】:

    在模式字符串中使用fileobj=sys.stdout 和管道符号(表示流模式)。

    这类似于tar czf - .:

    with tarfile.open(archive, 'w|gz', fileobj=sys.stdout) as archive_fd:
        archive_fd.add('.')
    

    这是在 Linux 上测试的;我认为它会在 Windows 上失败。有关该问题的解决方案,请参阅 this question

    参考资料:

    【讨论】:

    • 谢谢,它对我来说很好用(在 linux 上):) 感谢参考链接
    • 不客气。请记住为您认为有用的答案投票,并接受解决您问题的答案。
    最近更新 更多