Python提取/解压RAR文件错误

3
我正在尝试在Python脚本中提取RAR文件。我只找到了两种可能的方法:使用patoolib或使用rarfile。不幸的是,这两个选项都在我的代码中引发了很多错误,我不知道如何解决这个问题。
首先,我尝试了只使用patool和patoolib。在出现错误后,我切换到了rarfile和unrar。第一个似乎更容易,但我不理解错误。第二个需要在环境变量中进行许多操作,我不确定我是否做对了。
import patoolib
patoolib.extract_archive("my_file.rar", outdir=r"C:\Users\User1\Desktop\Example_dir")

错误信息如下:
if verbosity >= 0:
TypeError: '>=' not supported between instances of 'str' and 'int'

我从这里得到了这个选项。我知道这个错误是关于字符串变量的,但我不知道如何解释它。

第二个选项是使用rarfile和unrar。

import patoolib
from unrar import rarfile
from pyunpack import Archive

rarfile.UNRAR_TOOL = r"C:\Program Files (x86)\UnrarDLL\x64\UnRAR64.dll"


rarpath = 'my_file.rar'
rf = rarfile.RarFile(rarpath)
rf.extractall()
rf.extractall(r"C:\Users\User1\Desktop\Example_dir")


该选项会抛出一个恼人的错误:
PatoolError('patool can not unpack\n' + str(p.stderr)) pyunpack.PatoolError: patool can not unpack patool error: error extracting G:\program\test.rar: could not find an executable program to extract format rar; candidates are (rar,unrar,7z),

此外,还有另一个错误:
RarCannotExec: Unrar not installed? (rarfile.UNRAR_TOOL='unrar')

根据文档,rarfile要求UNRAR_TOOL是unrar.exe的路径。我已经使用"pip"安装了所有上述库,并按照此答案下载了UnRARDLL(http://www.rarlab.com/rar/UnRARDLL.exe),但我不知道应该将哪个.exe文件分配给UNRAR_TOOL。 我已将环境路径添加到C:\ Program Files(x86)\ UnrarDLL \ x64 \ UnRAR64.dll作为UNRAR_LIB_PATH,但未能解决问题。

我只想通过Python脚本解压缩一些文件。越简单越好。您能告诉我我做错了什么吗?也许还有其他解压文件的方法?


如果你的回答不是一个答案,请不要在问题中添加回答。请编辑你的问题。SyntaxError: EOL while scanning string literal 是因为你在 program=r" 后忘记了一个闭合的引号 ",在你的闭合括号 ) 之前。 - nyov
3个回答

2
TypeError异常表示您试图比较字符串和整数。如果对if verbosity >= 0:的引用是正确的,那么这意味着verbosity变量是一个字符串。
也许您之前设置了verbosity = '1'而不是verbosity = 1
另一个错误就是字面意思:could not find an executable program to extract format rar; candidates are (rar,unrar,7z)
代码期望找到其中一个可执行程序的格式为rarunrar7z(7zip)的可执行文件。如果您已经安装了它们,也许需要以某种方式告诉patoolib它们的位置。
该行:
rarfile.UNRAR_TOOL = r"C:\Program Files (x86)\UnrarDLL\x64\UnRAR64.dll"

看起来还好,但如果不起作用,您可能需要按照您链接的答案中的步骤设置UNRAR_LIB_PATH环境变量。
以下是如何在Windows上设置环境变量的说明:https://helpdeskgeek.com/windows-10/add-windows-path-environment-variable/


我在代码中没有设置任何值的冗长度。 - KS0232
另外,我已经设置了UNRAR_LIB_PATH环境变量,与您的链接相同,也与我的链接相同。错误仍然是一样的。 - KS0232

1

刚才我找到了patoolib的主源代码。现在我知道,patoolib.extract_archive函数的参数是:patoolib.extract_archive(archive, verbosity, outdir, program, format, compression)。我不知道这个函数中的verbosity是什么作用。另外,我应该如何设置program?目前我的代码看起来像这样:

import patoolib
patoolib.extract_archive(archive="my_file.rar", verbosity=0 ,outdir=r"C:\Users\User1\Desktop\Example_dir", program=r"C:\Program Files (x86)\UnrarDLL\x64\UnRAR64.dll)

The error says:

SyntaxError: EOL while scanning string literal

1

您需要前往https://www.rarlab.com/rar_add.htm下载 UnRAR for Windows - 命令行免费软件的 Windows 版本,然后将其解压到文件夹并添加:

rarfile.UNRAR_TOOL = r"C:\YourPath\UnRAR.exe"

因为rar文件不是在寻找.dll文件,而是在寻找可执行的.exe文件。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接