为什么它不起作用
您的代码无法工作,因为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
也会退出(使用)循环。因为循环中的条件仍然满足(即使满足,我们也退出了循环),不再满足下一条语句的条件( )并且不会打印消息(“错误”)。break
while
os.path.basename(sourcePath)
while
not os.path.basename(sourcePath)
可能的解决方案
我相信其中一个解决方案是在您的代码中添加一个计数器,只有在特定数量的迭代中您将无法找到您需要的内容时才会打印错误。您还可以尝试捕获“递归太多”异常(当然,如果您将使用递归,但错误将是这样的:)RuntimeError: maximum recursion depth exceeded
。
但是,您应该重新设计它以满足您自己的需求。