Python try/exep的语法无效

2024-10-01 00:15:48 发布

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

我正在尝试根据文件是否已被删除来创建异常:

def remove_file():
    print("Removing the output file: ", output_file)
    try:
        os.remove(output_file)
    except RemoveFileError,e:
        remove_stat = e.returncode
    if remove_stat == 0:
        print("File Removed!")

但我得到了以下错误:

  File ".\aws_ec2_list_instances.py", line 198
    except RemoveFileError,e:
                          ^
SyntaxError: invalid syntax

我想我可以随便叫这个例外。不是这样吗?我怎样才能把这个写对呢?你知道吗


Tags: 文件theoutputosdefremovestatfile
1条回答
网友
1楼 · 发布于 2024-10-01 00:15:48

您使用的是哪个版本的Python?因为Python2和Python3之间的语法发生了变化。你知道吗

在Python2中,它(主要)在Python3中的except Exception, var:位置。你知道吗

请注意,python3语法是后端口到python2.6和2.7的,因此在这些版本中看到except Exception as var并不罕见(如果您希望这段特定的代码同时在python2.6+和3+上工作,那么这应该是首选)。你知道吗

相关问题 更多 >