运行 python subprocess.call 对 tgz 文件进行解压和流输出

Running python subprocess.call on tgz file to untar and stream output

我在命令行中使用子进程调用来取消tar一个文件,我需要使用该调用的输出流式传输到一个临时文件中,这样我就可以读取“ +CONTENTS" 文件夹中的 tgz 文件。

我失败的输出是:

./streamContents.py rsh: ftp: 没有与主机名关联的地址 tar (child): ftp://myftpserver.com/pkgsrc/doxygen_pkgs/test。 tgz:无法打开:Input/output 错误 tar (child): 错误不可恢复:现在退出

gzip: stdin: 意外的文件结尾 tar: Child 返回状态 2 tar: 之前的错误导致错误退出延迟 追溯(最近一次通话): 文件“./streamContents.py”,第 29 行,位于 流 = proc.stdout.read(8196) AttributeError: 'int' object 没有属性 'stdout'

#!/usr/bin/python

from io import BytesIO
import urllib2
import tarfile
import ftplib
import socket
import threading
import subprocess

tarfile_url = "ftp://myftpserver.com/pkgsrc/doxygen_pkgs/test.tg
z"

try:
    ftpstream = urllib2.urlopen(tarfile_url)
except URLerror, e:
    print "URL timeout"
except socket.timeout:
    print "Socket timeout"


# BytesIO creates an in-memory temporary file.
tmpfile = BytesIO()
last_size = 0
tfile_extract = ""

while True:
    proc = subprocess.call(['tar','-xzvf', tarfile_url], stdout=subprocess.PIPE)
    # Download a piece of the file from the ftp connection
    stream = proc.stdout.read(8196)
    if not stream: break
    tmpfile.write(bytes(stream))
    # Seeking back to the beginning of the temporary file.
    tmpfile.seek(0)
    # r|gz forbids seeking backward; r:gz allows seeking backward
    try:
       tfile = tarfile.open(fileobj=tmpfile, mode="r:gz")
       print tfile.extractfile("+CONTENTS")
       tfile_extract_text = tfile_extract.read()
       print tfile_extract.tell()
       tfile.close()
       if tfile_extract.tell() > 0 and tfile_extract.tell() == last_size:
          print tfile_extract_text
          break
       else:
          last_size = tfile_extract.tell()
    except Exception:
       tfile.close()
       pass


tfile_extract_text = tfile_extract.read()
print tfile_extract_text

# When you're done:
tfile.close()
tmpfile.close()

扩展我上面的评论,您需要使用 urllib2tempfile 下载 tar 文件到一个临时文件,然后使用 [=13= 打开这个临时文件].

这里有一些代码可以得到 started:

import urllib2
import tarfile
from tempfile import TemporaryFile

f_url = 'url_of_your_tar_archive'
ftpstream = urllib2.urlopen(f_url)
tmpfile = TemporaryFile()

# Download contents of tar to a temporary file
while True:
    s = ftpstream.read(16384)
    if not s:
        break
    tmpfile.write(s)
ftpstream.close()

# Access the temporary file to extract the file you need
tmpfile.seek(0)
tfile = tarfile.open(fileobj=tmpfile, mode='r:gz')
print tfile.getnames()
contents = tfile.extractfile("+CONTENTS").read()
print contents