python - 从子进程的标准输出的 tar 中读取单个文件

标签 python

如何在不访问磁盘的情况下从命令的标准输出中读取单个文件的内容?

我想出了这样的事情:

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/

相关文章:

c++ - 同时支持 Tcl 和 Python?

python - 如何从 pandas 数据框中选择平均值大于某个限制的列?

python - 删除 matplotlib 子图并避免留空

python - 我的第一个 Scrapy Spider 不支持 MySQL 数据库

python - PyDict_SetItemString 段错误

python - 如何通过挤压将WAV音频文件的长度更改为适合固定长度

python - 返回参数在 Python 中抛出异常

python - 有没有办法使 rfind() 不区分大小写?

缓冲到文件的 Python 类列表对象?

python - 添加 'class' 作为字典键