处理嵌套 if/else 和 while 的 Pythonic 方式

我有以下带有多个 if/else 和循环的 Python 代码。它正在成为一个意大利面条代码,如果可能的话,我想避免它。


简而言之,我希望脚本在无人值守的情况下运行一段时间(几天/几周),但代码的真正“核心”应该只在上午 9 点到下午 5 点之间执行。


代码可以进一步简化吗?


shouldweContinue = True


while shouldweContinue:


    today = dt.datetime.now()

    if somefunction():

        if today.time() >= dt.time(9,0):

            instances = functionX()

            shouldweContinueToday = True

            cTime = dt.datetime.now()

            if cTime <= dt.time(17,0):

                for i in instances:

                    print('something here')

            else:

                shouldweContinueToday = False

        elif today.time() >= dt.time(17,0):

            time.sleep(12 * 60 * 60) # sleep for 12 hours i.e. basically wait for tomorrow

        else:

            time.sleep(60) # sleep for 1 min to avoid non-stop looping

    else:

        raise SystemExit()


SMILET
浏览 130回答 1
1回答

隔江千里

但代码的真正“核心”应该只在上午 9 点到下午 5 点之间执行。然后测试那个,只有那个。将该测试放入一个在 9 到 17 之间才会返回的函数中:def wait_for_working_hours():&nbsp; &nbsp; now = dt.datetime.now()&nbsp; &nbsp; if 9 <= now.hour < 17:&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; # not within working hours, sleep until next 9 o'clock&nbsp; &nbsp; next9_day = now.date()&nbsp; &nbsp; if now.hour >= 17:&nbsp; &nbsp; &nbsp; &nbsp; # between 17:00 and 23:59:59.999999, next 9am is tomorrow&nbsp; &nbsp; &nbsp; &nbsp; next9_day += dt.timedelta(days=1)&nbsp; &nbsp; delta = dt.datetime.combine(next9_day, dt.time(9)) - now&nbsp; &nbsp; time.sleep(delta.total_seconds())此功能会一直阻塞到上午 9 点到下午 5 点之间。其他要改变的事情:不要使用while flagvariable: ...,你可以使用break来结束一个while True:循环。我会使用sys.exit()而不是raise SystemExit().而不是if test: # do things,&nbsp;else: exit,将退出条件放在前面,提早。因此if not test: exit,该# do things部分也不再需要缩进。连同wait_for_working_hours看起来像这样的:while True:&nbsp; &nbsp; if not some_function():&nbsp; &nbsp; &nbsp; &nbsp; sys.exit()&nbsp; &nbsp; wait_for_working_hours()&nbsp; &nbsp; # do things that need to be done during working hours&nbsp; &nbsp; # ...&nbsp; &nbsp; if some_condition:&nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; # then sleep for a minute before doing it again.&nbsp; &nbsp; time.sleep(60)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python