0

完整脚本在这里: http: //pastebin.com/d6isrghF

我承认我对 Python陌生,所以如果这是一个容易回答的问题,请原谅我的愚蠢。有问题的部分是这样的:

sourcePath = jobPath
while os.path.basename(sourcePath):
    if os.path.basename(os.path.dirname(sourcePath)).lower() == category.lower():
        break
    else:
        sourcePath = os.path.dirname(sourcePath)
if not os.path.basename(sourcePath):
    print "Error: The download path couldn't be properly determined"
    sys.exit()

jobPath 正在从 sabnzbd 提供给脚本,并且是:

/mnt/cache/.apps/sabnzbd/complete/name.of.folder

类别是:

tv

所以我想我的问题是:为什么这会因错误而失败?

4

1 回答 1

1

为什么它不起作用

您的代码无法工作,因为while执行 untilos.path.basename(sourcePath)未评估为True,然后if调用语句,该语句(因为它看起来像if not os.path.basename(sourcePath):)显然被评估为True,因此显示消息(您的“错误”):

带注释的源代码

sourcePath = jobPath

# This is executed until os.path.basename(sourcePath) is evaluated as true-ish:
while os.path.basename(sourcePath):
    if os.path.basename(os.path.dirname(sourcePath)).lower() == category.lower():
        break
    else:
        sourcePath = os.path.dirname(sourcePath)

# Then script skips to the remaining part, because os.path.basename(sourcePath)
# has been evaluated as false-ish (see above)

# And then it checks, whether os.path.basename(sourcePath) is false-ish (it is!)
if not os.path.basename(sourcePath):
    print "Error: The download path couldn't be properly determined"
    sys.exit()

何时(以及为什么)它有时会起作用

有时仅因为在路径中找到类别而起作用,这意味着即使仍然满足条件(关键字:之后的条件),while也会退出(使用)循环。因为循环中的条件仍然满足(即使满足,我们也退出了循环),不再满足下一条语句的条件( )并且不会打印消息(“错误”)。breakwhileos.path.basename(sourcePath)whilenot os.path.basename(sourcePath)

可能的解决方案

我相信其中一个解决方案是在您的代码中添加一个计数器,只有在特定数量的迭代中您将无法找到您需要的内容时才会打印错误。您还可以尝试捕获“递归太多”异常(当然,如果您将使用递归,但错误将是这样的:)RuntimeError: maximum recursion depth exceeded

但是,您应该重新设计它以满足您自己的需求。

于 2012-10-21T06:56:39.103 回答