为什么是os.path.basename()使我的HTPC脚本失败?

2024-10-01 05:05:33 发布

您现在位置:Python中文网/ 问答频道 /正文

此处为完整脚本: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()

作业路径正在从sabnzbd输入到脚本,它是:

^{pr2}$

类别是:

tv

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


Tags: path脚本comhttpifoslower章节
1条回答
网友
1楼 · 发布于 2024-10-01 05:05:33

为什么不起作用

您的代码无法工作,因为执行while,直到os.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()

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

有时,只有在路径中找到category才有效,这意味着while循环将退出(使用break),即使仍然满足条件(while关键字后的条件:os.path.basename(sourcePath))也是如此。因为来自while循环的条件仍然满足(即使满足了我们也退出了循环),下一个语句的条件(not os.path.basename(sourcePath))将不再满足,并且不会打印消息(“the error”)。在

可能的解决方案

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

但是,您应该重新设计它,而不是满足您自己的需要。在

相关问题 更多 >