简体   繁体   English

在python中将tar.gz打印到stdout

[英]print tar.gz to stdout in python

I can create a .tar.gz file using 我可以使用创建一个.tar.gz文件

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

and this works fine. 而且效果很好。 But sometimes I want to print these files to stdout (if I execute the command via SSH) 但是有时候我想将这些文件打印到stdout (如果我通过SSH执行命令)

Does anyone have an idea how to do this? 有谁知道如何做到这一点? My old bash code is something like this 我以前的bash代码是这样的

tar -czf - $files >&1

or 要么

tar -czf - $files >/filename

I think you can just open the tar file in streaming mode and pass it sys.stdout: 认为您可以在流模式下打开tar文件并将其传递给sys.stdout:

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

The tarfile documentation says that this doesn't close stdout when it finishes. tarfile文档说完成后不会关闭stdout。

Use fileobj=sys.stdout and the pipe symbol (to indicate streaming mode) in the mode string. 在模式字符串中使用fileobj=sys.stdout和管道符号(指示流模式)。

This is similar to tar czf - . 这类似于tar czf - . :

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

This is tested on Linux; 这已在Linux上进行了测试; I assume it will fail on Windows. 我认为它将在Windows上失败。 See this question for a solution to that problem. 有关此问题的解决方案,请参见此问题。

References: 参考文献:

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

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