(Python)linux命令unrar的问题,不能为我的生活找出原因

时间:2016-09-06 07:01:58

标签: python linux unrar

所以最近我在这里做了一个关于需要帮助的脚本,该脚本应该为我自动提取.rar文件和.zip文件,而无需用户交互。在人们的各种帮助下,我做到了这一点:

import os
import re
from subprocess import check_call
from os.path import join

rx = '(.*zip$)|(.*rar$)|(.*r00$)'
path = "/mnt/externa/Torrents/completed/test"

for root, dirs, files in os.walk(path):
    if not any(f.endswith(".mkv") for f in files):
        found_r = False
        for file in files:
            pth = join(root, file)
            try:
                 if file.endswith(".zip"):
                    print("Unzipping ",file, "...")
                    check_call(["unzip", pth, "-d", root])
                    found_zip = True
                 elif not found_r and file.endswith((".rar",".r00")):
                     check_call(["unrar","e","-o-", pth, root])
                     found_r = True
                     break
            except ValueError:
                print ("OOps! That did not work")

我第一次在.rar文件上运行这个脚本它工作得很棒,它将文件提取到正确的目录和一切,但如果我再次运行它会打印错误:

Extracting from /mnt/externa/Torrents/completed/test/A.Film/Subs/A.Film.subs.rar

No files to extract
Traceback (most recent call last):
  File "unrarscript.py", line 20, in <module>
    check_call(["unrar","e","-o-", pth, root])
  File "/usr/lib/python2.7/subprocess.py", line 541, in check_call
    raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['unrar', 'e', '-o-', '/mnt/externa/Torrents/completed/test/A.Film/Subs/A.Film.subs.rar', '/mnt/externa/Torrents/completed/test/A.Film/Subs']' returned non-zero exit status 10

所以我尝试使用Try / except,但我不认为我做对了,任何人都可以帮助完成这个剧本的最后润色吗?

1 个答案:

答案 0 :(得分:1)

当unrar返回的错误代码不为零时,check_call会引发CalledProcessError异常。

您的错误消息显示:

  

返回非零退出状态10

Rar.txt包含以下错误代码列表:(可在WinRAR安装文件夹中找到)

    Code   Description   

     0     Successful operation.
     1     Non fatal error(s) occurred.
     2     A fatal error occurred.
     3     Invalid checksum. Data is damaged.
     4     Attempt to modify an archive locked by 'k' command.
     5     Write error.
     6     File open error.
     7     Wrong command line option.
     8     Not enough memory.
     9     File create error
    10     No files matching the specified mask and options were found.
    11     Wrong password.
   255     User stopped the process.

我看到您使用-o-来&#34;跳过现有文件。&#34;当试图覆盖文件时。如果打包文件已存在,将返回错误代码10。如果您立即重新运行脚本,则抛出此错误是正常的。

C:\>unrar e -o- testfile.rar

UNRAR 5.30 freeware      Copyright (c) 1993-2015 Alexander Roshal


Extracting from testfile.rar

No files to extract

C:\>echo %errorlevel%
10

你可以做这样的事情来处理它:

except CalledProcessError as cpe:
    if cpe.returncode == 10:
        print("File not overwritten")
    else:
        print("Some other error")

我看到你尝试提取vobsubs。 vobubs rar中的.sub rar也有一个小概率具有相同的文件名。