如何在不访问磁盘的情况下从命令的标准输出中读取单个文件的内容?
我想出了这样的事情:
def get_files_from(sha, files):
from subprocess import Popen, PIPE
import tarfile
p = Popen(["git", "archive", sha], bufsize=10240, stdin=PIPE, stdout=PIPE, stderr=PIPE)
tar = tarfile.open(fileobj=p.stdout, mode='r|')
p.communicate()
members = tar.getmembers()
names = tar.getnames()
contents = {}
for fname in files:
if fname not in names:
contents[fname] = None
continue
else:
idx = names.index(fname)
contents[fname] = members[idx].tobuf()
contents[fname] = tar.extractfile(members[idx]) #<--- HERE
tar.close()
return contents
问题是在标记的行上添加一个.read()
调用
contents[fname] = tar.extractfile(members[idx]) #<--- HERE
会报错:
tarfile.StreamError: seeking backwards is not allowed
那么如何获取文件的内容呢?
最佳答案
你拼错了 mode=
参数,你写了 more=
:
tar = tarfile.open(fileobj=p.stdout, mode='r|')
如果您正确指定模式,.tell()
将不会被调用。 :-)
然后您必须遍历 tarfile 对象以提取成员,您不能从 tarfile 中读取任意文件:
for entry in tar:
# test if this is a file you want.
if entry.name in files:
f = tar.extractfile(entry)
您不能使用任何 .getnames()
、.getmember()
或 .getmembers()
方法,因为这些方法需要完整的扫描文件,将文件指针放在末尾,让您无法读取条目数据本身。
关于python - 从子进程的标准输出的 tar 中读取单个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13667824/