我使用子进程调用来解压缩命令行中的文件,我需要使用该调用的输出流式传输到临时文件中,以便我可以读取" + CONTENTS&的内容#34; tgz文件中的文件夹。
我失败的输出是:
./ streamContents.py rsh:ftp:没有与主机名关联的地址 tar(孩子):ftp://myftpserver.com/pkgsrc/doxygen_pkgs/test。 tgz:无法打开:输入/输出错误 tar(child):错误无法恢复:现在退出
gzip:stdin:意外的文件结束 tar:孩子返回状态2 tar:从先前错误延迟的错误退出 Traceback(最近一次调用最后一次): 文件" ./ streamContents.py",第29行,in stream = proc.stdout.read(8196) AttributeError:' int'对象没有属性' 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()
答案 0 :(得分:0)
扩展上面的评论,您需要使用urllib2
和tempfile
将tar文件下载到临时文件,然后使用tarfile
打开此临时文件。
以下是一些入门代码:
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