Python tarfile 将 tar 写入管道
我想创建一个tar文件,然后把它直接上传到HTTP。
不过,似乎Python的tarfile模块在处理文件时会进行寻址,这样就没法直接把它传给下一个处理步骤。
下面是代码
tar = tarfile.open('named_pipe', mode='w')
tar.add('file1')
p.close()
‘named_pipe’是通过mkfifo命令创建的一个命名管道文件。当我运行这个程序,并在另一个终端中使用cat命令读取这个命名管道时,我遇到了一个错误
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
我们做的事情有点类似,但方向正好相反。我们有一个网页应用,它会把一个压缩文件(tarfile)传送到访问者的浏览器,这意味着我们是通过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)