gpt4 book ai didi

python - 如何使用 Python 的 UnRAR 库记录错误的密码?

转载 作者:行者123 更新时间:2023-12-01 06:41:32 26 4
gpt4 key购买 nike

以下代码(尝试“打开”提供错误密码的加密 RAR 文件):

from unrar import rarfile
import unrar

try:
rarfile.RarFile("encrypted.rar", pwd="wrong_password")
except Exception as e:
print(type(e))
print(e)

大多数情况下,虽然 RAR 文件没有其他问题(可以使用正确的密码解密而不会出现错误),但输出:

<class 'unrar.rarfile.BadRarFile'>
Invalid RAR file.

但有时它会输出:

<class 'RuntimeError'>
Bad password for Archive

如何在不链接异常的情况下使用 Python 的 UnRAR 库检查 RAR 文件的密码是否正确?

简而言之:UnRAR 库针对相同类型的错误(即提供的错误密码)引发(随机?)不同异常。在大多数情况下,它会引发 BadRarFile,但有时会引发 RuntimeError。捕获 RuntimeError 已经够糟糕了(但这里我们至少可以检查 args ),但如果还捕获了 except unrar.rarfile.BadRarFile ,人们甚至无法区分 (a) 密码错误或 (b) RAR 文件损坏的错误。

最佳答案

您可以链接多个 except 来缩小错误范围。不幸的是,如果提供了错误的密码,您的 unrar 库似乎会引发非特定异常 RuntimeError。因此,您无法 100% 确定密码错误是否是导致错误的原因。

try:
unrar.rarfile.RarFile("encrypted.rar", pwd="wrong_password")
except unrar.rarfile.BadRarFile:
print("Specified file doesn't seem to be a proper RAR archive")
except RuntimeError:
print("RuntimeError, possibly a wrong password")
except:
print("Something else happened")

不幸的是,除了使用不同的错误消息“密码错误或有缺陷的文件”和“密码错误或其他内容”之外,我看不到任何改进的可能性。

In short: UnRAR library raises (randomly?) different exception for the same type of error (namely, wrong password supplied). In most of the cases it raises BadRarFile but sometimes it raises RuntimeError.

根据 RAR 文件规范的版本,处理错误密码的方式可能会发生变化。对于较新版本的 RAR 文件,可能无法区分损坏的文件和错误的密码,而对于较旧的文件则可以区分。 (或者反过来。)

如果“原始”unrar 命令没有此问题,则可能是 Python 包装器库上游的错误。

关于python - 如何使用 Python 的 UnRAR 库记录错误的密码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59436516/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com