尝试…其他…除了语法

2024-05-18 11:15:48 发布

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

我不明白。。。

无法运行此代码,我不知道它为什么是语法错误。


    try:
        newT.read()
        #existingArtist = newT['Exif.Image.Artist'].value
        #existingKeywords = newT['Xmp.dc.subject'].value

    except KeyError:
        print "KeyError"

    else:
        #Program will NOT remove existing values
        newT.read()
        if existingArtist != "" :
            newT['Exif.Image.Artist'] = artistString


        print existingKeywords

        keywords = os.path.normpath(relativePath).split(os.sep)
        print keywords
        newT['Xmp.dc.subject'] = existingKeywords + keywords

        newT.write()
    except:
        print "Cannot write tags to ",filePath

最后一个“except:”出现语法错误。同样…我不知道为什么python会抛出语法错误(在这个问题上花了~3hrs)。


Tags: imagereadartistvaluedcexifsubjectprint
3条回答

查看python文档:http://docs.python.org/reference/compound_stmts.html#the-try-statement看起来不可能使用try拥有多个else。也许你的意思是最后?

else之后不能有另一个excepttryexceptelse块与函数调用或其他代码不同-不能随意混合和匹配它们。总是一个特定的序列:

try:
    # execute some code
except:
    # if that code raises an error, go here
    # (this part is just regular code)
else:
    # if the "try" code did not raise an error, go here
    # (this part is also just regular code)

如果要捕获在else块期间发生的错误,则需要另一个try语句。就像这样:

try:
    ...
except:
    ...
else:
    try:
        ...
    except:
        ...

仅供参考,如果要捕获在except块期间发生的错误,同样适用-在这种情况下,还需要另一个try语句,如下所示:

try:
    ...
except:
    try:
        ...
    except:
        ...
else:
    ...

阅读文档会给你一个短语:

The try ... except statement has an optional else clause, which, when present, must follow all except clauses.

把其他的移到处理程序的末尾。

相关问题 更多 >