在OSX中使用Python中的UnRARing文件

时间:2015-05-27 05:51:07

标签: python macos unrar

这让我疯了,我看着&为了解决这个问题,我在这里尝试了很多答案,但到目前为止还没有任何工作。

基本的问题是我有1300多个rar文件,我想提取并保持一定的组织,为了让事情变得更有趣,一些rar文件包含更多的rar文件(这就是为什么我是不愿意只是手工完成这个。

我的第一次尝试,我只是想我会做一个简单的python脚本直接调用unrar:

import os
import glob
import string
import subprocess

fileCount=0
files = glob.glob('Archives/*.rar')

for file in files:
  print file

  callstring = ["/usr/local/bin/unrar","e",file]
  output = subprocess.check_output(callstring)
  print output

此代码返回以下内容:

Traceback (most recent call last):
  File "/Users/Overlord/Documents/python/Unpacker.py", line 25, in <module>
    output = subprocess.check_output(callstring)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 573, in check_output
    raise CalledProcessError(retcode, cmd, output=output)
CalledProcessError: Command '['/usr/local/bin/unrar', 'e', 'testFile.rar']' returned non-zero exit status 10

(任何人都知道错误代码10是什么意思?) 从命令行使用unrar可以正常工作。

其次我尝试使用libarchive,但是尽管没有构建错误,我无法导入库。

接下来我选择了pyunpack:

from pyunpack import Archive

files = glob.glob('Archives/*.rar')

for file in files:
  print file
  Archive(file).extractall(".")

这引发了“没有这样的文件或目录”错误。

EasyProcessError: start error <EasyProcess cmd_param=['patool', 'extract', Path(u'/Users/Overlord/Documents/python/testFile.rar'), Path(u'--outdir=/Users/Overlord/Documents/python')] cmd=['patool', 'extract', Path(u'/Users/Overlord/Documents/python/testFile.rar'), Path(u'--outdir=/Users/Overlord/Documents/python')] oserror=[Errno 2] No such file or directory returncode=None stdout="None" stderr="None" timeout=False>

然后我尝试了patoolib:

import patoolib

files = glob.glob('Archives/*.rar')

for file in files:
  print file
  patoolib.extract_archive(file,outdir=".")

这个投掷了以下内容:

PatoolError: could not find an executable program to extract format rar; candidates are (rar,unrar,7z)

尽管我直接从命令行运行patool时出现此消息,但该文件没有问题。

所以我回到原来的子流程解决方案并尝试使用patool而不是unrar

import subprocess

fileCount=0
files = glob.glob('Archives/*.rar')

for file in files:
  print file

  callstring = ["/Library/Frameworks/Python.framework/Versions/2.7/bin/patool","extract",file]
  output = subprocess.check_output(callstring)
  print output

并取回以下内容:

CalledProcessError: Command '['/Library/Frameworks/Python.framework/Versions/2.7/bin/patool', 'extract', 'testFile.rar']' returned non-zero exit status 1

任何想法或建议,但我还有一些毛发,我还没有从头脑中拔出来?

1 个答案:

答案 0 :(得分:1)

您可以在此处使用rarfile库:

安装:

$ pip install rarfile

示例:

from rarfile import RarFile

with RarFile("myarchive.rar") as rf:
    for f in rf.infolist():
        with open(f.filename, "wb") as of:
            of.write(rf.read(f))

更新:或者您可以直接提取所有&#34;一步到位:

from rarfile import RarFile


with RarFile("myarchive.rar") as rf:
    rf.extracall()