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
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.
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:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.