python解压rar, 7z

572 views
Skip to first unread message

shug...@gmail.com

unread,
May 7, 2009, 1:22:17 AM5/7/09
to python-cn`CPyUG`华蟒用户组(中文Py用户组)
为了让程序跨平台,我去掉了
os.system('tar/unrar/unzip ...')

bz2和gz的好办,有现成的模块
但是rar和7z 不知道怎么解决

有个老外写了rarfile
http://grue.l-t.ee/~marko/src/rarfile/
但是一看到里面有
os.system('unrar ...')
就不靠谱了

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright (c) Shuge Lee <shug...@gmail.com> 2009
# 2009-05-07

import os
from os import path as osp
import zipfile, tarfile

def unpack(packed_file, save_path):
if not packed_file:
print '%s is None' % packed_file
return

if not save_path:
print '%s is None' % save_path
return
else:
save_path = osp.realpath(save_path)

if not osp.exists(save_path):
print '%s created' % save_path
os.makedirs(save_path)

# guess file type
file_type = osp.splitext(packed_file)[-1]
if file_type not in ['.7z', '.bz2', '.gz', '.zip']:
print 'Unpack file format - %s not recognized. Ignoring.' %
packed_file
return

# extract file
if file_type == '.7z':
print "We're sorry that Lee System doesn't support 7z
archive"
return

if file_type == '.zip':
try:
# for python 2.5
target_file = zipfile.ZipFile(packed_file)
for vary_file in target_file.namelist():
vary_file_name = osp.join(save_path, vary_file)

if vary_file_name.endswith('/'):
if not osp.exists(vary_file):
os.mkdir(vary_file)
else:
parent_folder = osp.dirname(vary_file_name)
if not osp.exists(parent_folder):
os.makedirs(parent_folder)

outfile = open(vary_file_name, 'wb')
outfile.write(target_file.read(vary_file))
outfile.close()

# # for python 2.6
# target_file = zipfile.open(packed_file)
# target_file.extractall()
# target_file.close()

except zipfile.BadZipfile, e:
print e
return

elif file_type in ['.bz2', '.gz']:
try:
target_file = tarfile.open(packed_file)
target_file.extractall(path=save_path)
target_file.close()
except tarfile.ReadError, e:
print e
return

elif file_type == '.rar':
print "We're sorry that Lee System doesn't support RAR
archive"
return

return True

if __name__ == '__main__':
import sys
if len(sys.argv) >= 2:
packed_file = sys.argv[1]

if len(sys.argv) > 2:
save_path = sys.argv[2]
else:
save_path = osp.dirname(osp.realpath(__file__))

unpack(packed_file, save_path)

Jiahua Huang

unread,
May 7, 2009, 1:28:49 AM5/7/09
to pyth...@googlegroups.com
2009/5/7 shug...@gmail.com <shug...@gmail.com>:

>
> 为了让程序跨平台,我去掉了
> os.system('tar/unrar/unzip ...')
>

不要去掉。
自带个 unrar.exe、7zr.exe 就好
Linux 可以用系统 rar、7z,
而 windows 下会自动用你带的 .exe

Shuge Lee

unread,
May 7, 2009, 1:42:41 AM5/7/09
to python-cn`CPyUG`华蟒用户组(中文Py用户组)

rar解决了,还是老外写了个模块。。。
http://www.averdevelopment.com/python/

没有在linux测试,应该问题不大
剩下7z

> os.system('tar/unrar/unzip ...')
对这个没好感。。。
先折腾,实在不行,就保留吧
偶喜欢优雅的代码:)

On May 7, 1:28 pm, Jiahua Huang <jhuangjia...@gmail.com> wrote:
> 2009/5/7 shuge....@gmail.com <shuge....@gmail.com>:

Shuge Lee

unread,
May 7, 2009, 1:44:06 AM5/7/09
to python-cn`CPyUG`华蟒用户组(中文Py用户组)
那个UnRar有点问题

改了一下

from __future__ import generators

import fnmatch
import os
import Queue
import threading
import time

import ctypes.wintypes

__version__ = '1.0'


On May 7, 1:28 pm, Jiahua Huang <jhuangjia...@gmail.com> wrote:
> 2009/5/7 shuge....@gmail.com <shuge....@gmail.com>:
>
>
>

Jiahua Huang

unread,
May 7, 2009, 1:49:47 AM5/7/09
to pyth...@googlegroups.com
2009/5/7 Shuge Lee <shug...@gmail.com>:

> 嗯
> rar解决了,还是老外写了个模块。。。
> http://www.averdevelopment.com/python/
>
> 没有在linux测试,应该问题不大

表,那个是使用 ctypes 调用 UnRAR.dll 的,
是 Windows only。

所以你还是继续 os.popen() 甚至 os.system() 好,
自带 unrar.exe、7zr.exe 就是了

Shuge Lee

unread,
May 7, 2009, 3:48:46 AM5/7/09
to python-cn`CPyUG`华蟒用户组(中文Py用户组)
thanks 花花~~

On May 7, 1:49 pm, Jiahua Huang <jhuangjia...@gmail.com> wrote:
> 2009/5/7 Shuge Lee <shuge....@gmail.com>:

Shuge Lee

unread,
May 7, 2009, 4:02:30 AM5/7/09
to python-cn`CPyUG`华蟒用户组(中文Py用户组)
done

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright (c) Shuge Lee <shug...@gmail.com> 2009
# 2009-05-07

import os
from os import path as osp
import zipfile, tarfile


#=======================================================================
# guess platform

import platform

p = platform.platform(terse=1).lower()

if p.find('linux') != -1:
lee_platform = 'linux'

lee_writelines = '\n'
lee_output_encode = 'utf8'
elif p.find('window') != -1:
lee_platform = 'windows'

lee_writelines = '\r\n'
havecolor = 0
lee_output_encode = 'gbk'
elif p.find('cygwin') != -1:
lee_platform = 'cygwin'

lee_writelines = '\r\n'
lee_output_encode = 'gbk'
else:
problem = _("We are sorry for that Lee System doesn't supports
your platform - %s now" % p)
solution = _('Report to Shuge developer')
std(problem, solution, 'quit')

#=======================================================================


def unpack(packed_file, save_path):
if not packed_file:
print '%s is None' % packed_file
return -1

if not save_path:
print '%s is None' % save_path
return -1
else:
save_path = osp.realpath(save_path)

if not osp.exists(save_path):
print '%s created' % save_path
os.makedirs(save_path)

# guess file type
file_type = osp.splitext(packed_file)[-1]
if file_type not in ['.7z', '.bz2', '.gz', '.zip', '.rar']:
print 'Unpack file format - %s not recognized. Ignoring.' %
packed_file
return -1

e = 0

# extract file
"""
0 No error
1 Warning (Non fatal error(s)). For example, one or more files
were
locked by some other application, so they were not compressed.
2 Fatal error
7 Command line error
8 Not enough memory for operation
255 User stopped the process
"""

if file_type in ['.7z', '.rar']:
if lee_platform == 'windows':
extract_app = '7z.exe'
elif lee_platform in ['linux', 'cygwin']:
extract_app = '7z'
else:
print "It doesn't support your platform"
sys.exit(-1)

extract_cmd = ' %s x "%s" -o"%s" ' % (extract_app,
packed_file, save_path)
e = os.system(extract_cmd)
#print "We're sorry that Lee System doesn't support RAR/7z
archive"
return e

elif file_type == '.zip':
try:
# for python 2.5
target_file = zipfile.ZipFile(packed_file)
for vary_file in target_file.namelist():
vary_file_name = osp.join(save_path, vary_file)

if vary_file_name.endswith('/'):
if not osp.exists(vary_file):
os.mkdir(vary_file)
else:
parent_folder = osp.dirname(vary_file_name)
if not osp.exists(parent_folder):
os.makedirs(parent_folder)

outfile = open(vary_file_name, 'wb')
outfile.write(target_file.read(vary_file))
outfile.close()

# # for python 2.6
# target_file = zipfile.open(packed_file)
# target_file.extractall()
# target_file.close()

except zipfile.BadZipfile, e:
return e

elif file_type in ['.bz2', '.gz']:
try:
target_file = tarfile.open(packed_file)
target_file.extractall(path=save_path)
target_file.close()
except tarfile.ReadError, e:
return e

return e

if __name__ == '__main__':
import sys
if len(sys.argv) >= 2:
packed_file = sys.argv[1]

if len(sys.argv) > 2:
save_path = sys.argv[2]
else:
save_path = osp.dirname(osp.realpath(__file__))

unpack(packed_file, save_path)




On May 7, 1:49 pm, Jiahua Huang <jhuangjia...@gmail.com> wrote:
> 2009/5/7 Shuge Lee <shuge....@gmail.com>:

xuzi...@gmail.com

unread,
May 9, 2009, 10:49:00 AM5/9/09
to pyth...@googlegroups.com
在2009-05-07的邮件[[CPyUG:85990] python解压rar, 7z]中写到:
shuge.lee> bz2和gz的好办,有现成的模块
shuge.lee> 但是rar和7z 不知道怎么解决
unrar的源代码,自己包装一下,编译一个出来:http://www.rarlab.com/rar/unrarsrc-3.9.2.tar.gz
7z的直接就有源代码,上官网找一下。

--
唉,啥都不行,只能回去扣腚

Shuge Lee

unread,
May 11, 2009, 8:33:48 AM5/11/09
to python-cn`CPyUG`华蟒用户组(中文Py用户组)
如huahua说,直接弄个7z.exe好了,简单,省事
Linux下,7z支持rar
现在没有哪个Lin用户会不安装7z的

Jiahua Huang

unread,
May 11, 2009, 8:40:40 AM5/11/09
to pyth...@googlegroups.com
2009/5/11 Shuge Lee <shug...@gmail.com>:
> Linux下,7z支持rar

p7zip 支持的 rar 版本似乎比 win7zip 支持的低,所以还是有限使用 rar X 好

> 现在没有哪个Lin用户会不安装7z的

另外,p7zip 对 zip 中文支持有问题(Linux 下的 7z 是 p7zip),
unzip 只是不会转码(可以解压后再转码,或打转码补丁,再不 zipfile 模块自己加转码)
而 7z 解压 zip 则无论 utf8、gb18030 中文通通乱码。

所以 .rar、.zip 还是用各自的 rar.exe、unzip.exe 解压好了,
不要通通都丢给 p7zip

MuSheng

unread,
May 14, 2009, 9:08:57 PM5/14/09
to pyth...@googlegroups.com
今天發現了一個東東,可以試下py7zlib。
http://pypi.python.org/pypi/pylzma
自己未試過。
在Win下為了省事直接用命令行7za來解決。



shug...@gmail.com 提到:
--

  祝!

安!

^_^_^_^_^_^_^_^_^_^_^_^_^

  永遠的萊鳥!

永遠謙卑的仰視大牛們!

阿木

xie wen

unread,
May 14, 2009, 9:46:52 PM5/14/09
to pyth...@googlegroups.com
Pylzma以前用过,可以的,对付rar记得有一个pyUnRar的模块。

2009/5/15, MuSheng <mu....@gmail.com>:
Reply all
Reply to author
Forward
0 new messages