在特定时间内忽略异常

Ignoring exceptions for a specific amount of time

试图在循环中使 try 变为 运行,因为我正在启动一台包含网络服务器的机器,我想使其变为 运行 而不是直接转到除了并停止脚本。我已经为 http-status 代码做了一段时间,但这只有在机器启动时才有效。

所以我的问题是如何让 try 在进入 except 之前循环 5 分钟?抱歉我的解释不当。

try:
    r = requests.head("http://www.testing.co.uk")

    while r.status_code != 200:
        print "Response not == to 200."
        time.sleep(30)
        r = requests.head("http://www.testing.co.uk")

    else:
        print "Response is 200 - OK"

except requests.ConnectionError:
    print "NOT FOUND - ERROR"

你可以这样做:

import requests, time, datetime

# Determine "end" time -- in this case, 5 minutes from now
t_end = datetime.datetime.now() + datetime.timedelta(minutes=5)

while True:
    try:
        r = requests.head("http://www.testing.co.uk")

        if r.status_code != 200:
            # Do something
            print "Response not == to 200."
        else:
            # Do something else
            print "Response is 200 - OK"
            break  # Per comments

        time.sleep(30)  # Wait 30 seconds between requests

    except requests.ConnectionError as e:
        print "NOT FOUND - ERROR"
        # If the time is past the end time, re-raise the exception
        if datetime.datetime.now() > t_end: raise e
        time.sleep(30)  # Wait 30 seconds between requests

重要的一行是:

if datetime.datetime.now() > t_end: raise e

如果不满足条件(已过去不到 5 分钟),异常将被静默忽略并继续 while 循环。

如果条件 满足,例外情况是 re-raised 由其他一些外部代码处理或根本不处理——在这种情况下你我会看到异常 "break"(用你的话来说)程序。

使用这种方法的好处(而不是 while True:):

while datetime.datetime.now() > t_end:

是,如果您发现自己在 while 循环之外,您就知道您是从 break 而不是 5 分钟后到达那里的。如果您想在这种情况下做一些特殊的事情,您还可以保留异常。