Search code examples
python-3.xtartarfile

how to mimic `--numeric-owner` in tarfile?


with tar command we can use tar --numeric-owner -cf - test | tee to make sure in tar data it use number to represent owner:group. How can we do this in python3's tarfile? It seems only extract mentioned numeric owner.


Solution

  • I've faced a similar problem. After some investigation the only solution I was able to come up with was to pass a TarInfo filter when adding the files to the tarball. Something like:

    def tar_filter(tarinfo: TarInfo) -> TarInfo:
        # tar filter to mimic --numeric-owner argument
        tarinfo.uname = ''
        tarinfo.gname = ''
        return tarinfo
    
    with tarfile.open(<tar_file_name>, w:gz) as tar:
        tar.add(<file_to_add>, filter=tar_filter)