python / cpython

The Python programming language
https://www.python.org
Other
62.34k stars 29.94k forks source link

Tarfile to stdout documentation example #86608

Open 8d94e94c-cc78-4121-a8cf-8c7d87bb7d8e opened 3 years ago

8d94e94c-cc78-4121-a8cf-8c7d87bb7d8e commented 3 years ago
BPO 42442

Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.

Show more details

GitHub fields: ```python assignee = None closed_at = None created_at = labels = ['3.7', '3.8', '3.9', 'docs'] title = 'Tarfile to stdout documentation example' updated_at = user = 'https://bugs.python.org/ilaughlin' ``` bugs.python.org fields: ```python activity = actor = 'ilaughlin' assignee = 'docs@python' closed = False closed_date = None closer = None components = ['Documentation'] creation = creator = 'ilaughlin' dependencies = [] files = [] hgrepos = [] issue_num = 42442 keywords = [] message_count = 1.0 messages = ['381665'] nosy_count = 2.0 nosy_names = ['docs@python', 'ilaughlin'] pr_nums = [] priority = 'normal' resolution = None stage = None status = 'open' superseder = None type = None url = 'https://bugs.python.org/issue42442' versions = ['Python 3.6', 'Python 3.7', 'Python 3.8', 'Python 3.9'] ```

Linked PRs

8d94e94c-cc78-4121-a8cf-8c7d87bb7d8e commented 3 years ago

Recommend adding example to tarfile documentation to provide example of writing a tarfile to stdout.

example:

files = [(file_1, filename_1), (file_2, filename_2)]

with tarfile.open(fileobj=sys.stdout.buffer, mode = 'w|gz') as tar:
    for file, filename in files:
        file_obj = io.BytesIO() #starts a BytesIO object
        file_obj.write(file.encode('utf-8')) #writes the file to the BytesIO object
        info = tarfile.TarInfo(filename) #creates the TarInfo
        file_obj.seek(0) #goes to the beginning of the BytesIO object else it won't write
        info.size = len(file) #sets the length of the file
        tar.addfile(info, fileobj=file_obj) #writes the tar to stdout.