【问题标题】:Executing a try inside of a while loop in Python [duplicate]在 Python 的 while 循环中执行 try [重复]
【发布时间】:2017-08-29 23:42:05
【问题描述】:

我正在尝试在 while 循环内发送电子邮件,但如果 sendmail 失败,我希望脚本记录错误并继续:

当真时:

input_state = GPIO.input(5)
if input_state == True:
    now = datetime.datetime.now().strftime("%m-%d-%y-%H%M%S")
    logging.debug('Motion detected at ' + now)
    name = 'tempimage.jpg'
    camera.capture(name)
    new_name = '/home/pi/image' + str(now) + '.jpg'
    os.rename(name, new_name)
    try:
        server = smtplib.SMTP( "smtp.gmail.com", 587 )
        server.starttls()
        server.login( '<login to gmail>', '<password>' )
        server.sendmail( 'Front Porch', '<myphone number>@vtext.com', 'Picture just taken on Front Porch' ) #Chuck
        server.close()
    else:
        logging.debug('Send of text failed ' + now)
    time.sleep(3)
else:
    now = datetime.datetime.now().strftime("%m-%d-%y-%H%M%S")
    logging.debug('No Motion ' + now)
    time.sleep(3)

当我在启动时执行此操作时,它会在尝试时停止。我知道这是一个正在酝酿的 Duh 时刻,但真的需要它发挥作用。非常感谢任何帮助。

【问题讨论】:

  • 您有一个try,但没有exceptfinally。这不会停在try;这将完全无法编译。
  • 也许你的意思是except AppropriateExceptionType而不是else
  • 你们太棒了!我知道这一定是一个糟糕的时刻。非常感谢,添加一个例外捕获如下修复一切。

标签: python python-3.x


【解决方案1】:
input_state = GPIO.input(5)
if input_state == True:
    now = datetime.datetime.now().strftime("%m-%d-%y-%H%M%S")
    logging.debug('Motion detected at ' + now)
    name = 'tempimage.jpg'
    camera.capture(name)
    new_name = '/home/pi/image' + str(now) + '.jpg'
    os.rename(name, new_name)
    try:
        server = smtplib.SMTP( "smtp.gmail.com", 587 )
        server.starttls()
        server.login( '<login to gmail>', '<password>' )
        server.sendmail( 'Front Porch', '<myphone number>@vtext.com', 'Picture just taken on Front Porch' ) #Chuck
        server.close()
    except Exception as e:
        logging.debug('Send of text failed ' + now + 'Exception '+e)
    time.sleep(3)
else:
    now = datetime.datetime.now().strftime("%m-%d-%y-%H%M%S")
    logging.debug('No Motion ' + now)
    time.sleep(3)

试试这段代码(我使用了except,而不是else并记录了异常)。

【讨论】:

  • 完美运行!非常感谢。
猜你喜欢
  • 2015-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-18
  • 2017-06-28
  • 1970-01-01
  • 2021-06-30
  • 2014-09-11
相关资源
最近更新 更多