1

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
flipchart
  • 6,548
  • 4
  • 28
  • 53

2 Answers2

2

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.

Evan
  • 2,217
  • 15
  • 18
1

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:

Community
  • 1
  • 1
Robᵩ
  • 163,533
  • 20
  • 239
  • 308