仅当另一个函数成功时才执行函数的正确语法

发布于 2024-12-08 04:40:36 字数 840 浏览 0 评论 0原文

我有以下代码,它是我在程序中使用的电子邮件类的一部分。目前,无论连接函数中是否建立了与 SMTP 服务器的连接,我都正在运行退出函数。我知道我可以在发送电子邮件后将 quit 函数放在 try 语句中,但我想弄清楚如何编写代码来表示相当于“如果与服务器的连接打开,则关闭它”。用 Python 编写它的最佳方法是什么?

谢谢!

def connect(self, headers, msg):

    try:
        self.server.starttls()

        try:
            self.server.login(self.usrname,self.pswd)

            try:
                self.server.sendmail(self.sendfrom, self.sendto, headers + "\r\n\r\n" + msg)
            except Exception as sendmailfail:
                print(sendmailfail)

        except Exception as emailfail:
            print (emailfail)

    except Exception as error:
        print(error)

def quit(self):
    self.server.quit()
    print("The SMTP connection is closed")



first = GmailSmpt('x','y','z','zz')
x , y = first.message()
first.connect(x,y)
first.quit()

I have the following code that is part of my email class that I use in my programs. Currently I am running the quit function whether or not a connection to the SMTP server was made in the connect function. I know I could put the quit function inside of the try statement after the email is sent, but I would like to figure out how to write the code to say the equivalent of "if a connection to the server is open, close it." What is the best way to write that in Python?

Thanks!

def connect(self, headers, msg):

    try:
        self.server.starttls()

        try:
            self.server.login(self.usrname,self.pswd)

            try:
                self.server.sendmail(self.sendfrom, self.sendto, headers + "\r\n\r\n" + msg)
            except Exception as sendmailfail:
                print(sendmailfail)

        except Exception as emailfail:
            print (emailfail)

    except Exception as error:
        print(error)

def quit(self):
    self.server.quit()
    print("The SMTP connection is closed")



first = GmailSmpt('x','y','z','zz')
x , y = first.message()
first.connect(x,y)
first.quit()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

じее 2024-12-15 04:40:36

您需要完成本教程的“错误和异常”部分

try:
  possibly_fail()
except ...:
  handle_exception()
else:
  no_exceptions()
finally:
  always_run_this()

You need to finish the "Errors and Exceptions" section of the tutorial.

try:
  possibly_fail()
except ...:
  handle_exception()
else:
  no_exceptions()
finally:
  always_run_this()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文