Python的tarfile将tar写入管道

5
我希望创建一个tar文件并将其传输到http上传。然而,似乎Python tarfile模块执行了查找操作,这使得无法将其传输到下一个进程中。
以下是代码:
tar = tarfile.open('named_pipe', mode='w')
tar.add('file1')
p.close()

'named_pipe' 是由 mkfifo 命令创建的命名管道文件。当我在另一个终端运行 cat named_pipe 时,出现了错误。

tar = tarfile.open('named_pipe', mode='w')
  File "/usr/lib/python2.7/tarfile.py", line 1695, in open
    return cls.taropen(name, mode, fileobj, **kwargs)
  File "/usr/lib/python2.7/tarfile.py", line 1705, in taropen
    return cls(name, mode, fileobj, **kwargs)
  File "/usr/lib/python2.7/tarfile.py", line 1566, in __init__
    self.offset = self.fileobj.tell()
IOError: [Errno 29] Illegal seek

任何想法?
1个回答

5
我们做类似的事情,但是从另一方面来看。我们有一个Web应用程序,将tar文件传送到访问者的浏览器,这意味着我们通过HTTP会话流式传输。关键是将打开且可写的文件句柄传递给tarfile.open()调用,并设置模式为"w|"。代码大致如下:
# assume stream is set to your pipe

with tarfile.open(name="upload.tar", 
    mode = "w|", 
    fileobj = stream, 
    encoding = 'utf-8') as out:

    out.add(file_to_add_to_tar)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接