【发布时间】:2015-06-11 04:27:38
【问题描述】:
我正在使用子进程调用在命令行中解压缩文件,我需要使用该调用的输出流式传输到临时文件中,以便可以读取“+CONTENTS”文件夹中的内容.tgz 文件。
我失败的输出是:
./streamContents.py rsh: ftp: 没有与主机名关联的地址 焦油(子):ftp://myftpserver.com/pkgsrc/doxygen_pkgs/test。 tgz:无法打开:输入/输出错误 tar(子):错误不可恢复:现在退出
gzip:标准输入:文件意外结束 焦油:孩子返回状态2 tar:从先前的错误延迟错误退出 回溯(最近一次通话最后): 文件“./streamContents.py”,第 29 行,在 流 = 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()
【问题讨论】:
-
你为什么在循环中反复调用 tar?
-
抱歉,我没听清楚,我知道这是我的问题的一部分。最初我试图直接从 tar 文件中流式传输。 tarfile 模块不允许我直接从中流式传输,因为它需要先构建索引才能让我流式传输。
-
另外,在 ftp URL 上运行
tar似乎是错误的。您需要将文件保存到磁盘并在本地文件上运行tar。 -
我已经从尝试直接打开 tarfile_url 改为调用 ftpstream 变量。
proc = subprocess.call(['tar','-xzvf', ftpstream], stdout=subprocess.PIPE)因此,如果我正确地遵循@vikramls 所说的话,我正在尝试解压仍在 ftp 服务器上的文件,对吧?