在异常中包装“with”语句的最佳方法是什么?

2024-10-03 17:25:28 发布

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

从下面的代码中可以看到,我使用多个“with”语句通过SFTP下载。你知道吗

我想根据错误的来源提出自定义异常(或者通常更好地了解出了什么问题)。你知道吗

通常我只是把东西包装在单独的例外中,但我不知道如何在这里做到这一点。你知道吗

下面的代码不起作用,因为我的自定义异常突然出现,这意味着我总是得到ConnectionException。你知道吗

    try:
        with pysftp.Connection(self.sftp_details["host"], username=self.sftp_details["user"],
            private_key=env.root_dir+"/private.ppk", port=self.sftp_details["port"]) as sftp:

            try:
                with sftp.cd(self.sftp_details["folder"]):
                    try:
                        sftp.get(self.sftp_details["filename"],local_filename)
                    except Exception as e:
                        self.logErrorToSheet("The file could not be found on the server.")
                        raise FileNotFoundException(self.sftp_details)

            except Exception as e:
                self.logErrorToSheet("The folder could not be found.")
                ServerFolderNotFoundException(self.sftp_details)

    except Exception as e:
        self.logErrorToSheet("A connection could not be made. (%s)" %(e))
        raise ConnectionException(e, self.sftp_details)

编辑:

好吧,听起来我需要做一些事情,比如:

    try:
    with pysftp.Connection(self.sftp_details["host"], username=self.sftp_details["user"],
        private_key=env.root_dir+"/private.ppk", port=self.sftp_details["port"]) as sftp:
            with sftp.cd(self.sftp_details["folder"]):
                    sftp.get(self.sftp_details["filename"],local_filename)

except Connection as e:
    self.logErrorToSheet("A connection could not be made. (%s)" %(e))
    raise e

except IOError as e:
    self.logErrorToSheet("The file or folder could not be found on the server.")
raise e

我不太清楚如何区分文件夹错误(cd)和文件错误,但这是我可以研究的另一个问题。你知道吗


Tags: selfportaswithnotbeprivatefolder