我怎样才能从命令的标准输出中读取单个文件的内容而不敲击磁盘?
我想出了这样的事情:
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:不允许向后搜索
那么如何获取文件的内容呢?