import subprocess
cmd = ['7z', 'a', 'Test.7z', 'Test', '-mx9']
sp = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
1. 安装rarfile
pip install rarfile
2. 下载 unrar windows 版本文件:
http://www.rarlab.com/rar_add.htm
http://www.rarlab.com/rar/unrarw32.exe
然后执行 unrarw32.exe 解压路径设置为当前工程路径。
3. 在 python 脚本里面测试即可。
try :
f = rarfile.RarFile(local_file)
f.extractall(local_path)
f.close()
except Exception as e:
print 'ERROR: Extract RAR file %s exception:'%local_file, e
但是这样只能使用 rarfile 解压,如果要支持其他格式比如zip或者7z就得用其他工具了。
在 win7 下 python2.7 64位用 pip 安装 zipfile 提示找不到,只能系统调用了,最好的工具是 7zip:
或者使用 pylzma :http://www.joachim-bauch.de/projects/pylzma/
easy_install pylzma
使用封装:
import py7zlib
class SevenZFile(object):
@classmethod
def is_7zfile(cls, filepath):
'''
Class method: determine if file path points to a valid 7z archive.
'''
is7z = False
fp = None
try:
fp = open(filepath, 'rb')
archive = py7zlib.Archive7z(fp)
n = len(archive.getnames())
is7z = True
finally:
if fp:
fp.close()
return is7z
def __init__(self, filepath):
fp = open(filepath, 'rb')
self.archive = py7zlib.Archive7z(fp)
def extractall(self, path):
for name in self.archive.getnames():
outfilename = os.path.join(path, name)
outdir = os.path.dirname(outfilename)
if not os.path.exists(outdir):
os.makedirs(outdir)
outfile = open(outfilename, 'wb')
outfile.write(self.archive.getmember(name).read())
outfile.close()
或者:
# Compress the input file (as a stream) to a file (as a stream)
i = open(source_file, 'rb')
o = open(compressed_file, 'wb')
i.seek(0)
s = pylzma.compressfile(i)
while True:
tmp = s.read(1)
if not tmp: break
o.write(tmp)
o.close()
i.close()
# Decomrpess the file (as a stream) to a file (as a stream)
i = open(compressed_file, 'rb')
o = open(decompressed_file, 'wb')
s = pylzma.decompressobj()
while True:
tmp = i.read(1)
if not tmp: break
o.write(s.decompress(tmp))
o.close()
i.close()