user2988599
user2988599

Reputation: 11

print tar.gz to stdout in python

I can create a .tar.gz file using

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)

Does anyone have an idea how to do this? My old bash code is something like this

tar -czf - $files >&1

or

tar -czf - $files >/filename

Upvotes: 1

Views: 2210

Answers (2)

Evan
Evan

Reputation: 2357

I think you can just open the tar file in streaming mode and pass it 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.

Upvotes: 2

Robᵩ
Robᵩ

Reputation: 168876

Use fileobj=sys.stdout and the pipe symbol (to indicate streaming mode) in the mode string.

This is similar to tar czf - .:

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

This is tested on Linux; I assume it will fail on Windows. See this question for a solution to that problem.

References:

Upvotes: 1

Related Questions