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

处理嵌套if/else和while的Pythonic方法,python,Python,我有以下带有多个if/else和循环的Python代码。它正在成为一个意大利面代码,如果可能的话,我想避免它 简单地说,我希望脚本在无人参与的情况下运行一段时间(天/周),但真正的代码“核心”应该只在上午9点到下午5点之间执行 代码可以进一步简化吗 shouldweContinue = True while shouldweContinue: today = dt.datetime.now() if somefunction(): if today.time(

我有以下带有多个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()

shouldweecontinue=True
我们应该继续:
今天=dt.datetime.now()
如果somefunction():
如果今天.time()>=dt.time(9,0):
实例=函数x()
shouldweContinueToday=真
cTime=dt.datetime.now()
如果cTime=dt.时间(17,0):
时间。睡眠(12*60*60)#睡眠12小时,即基本上等待明天
其他:
时间。睡眠(60)#睡眠1分钟以避免不停循环
其他:
提升系统退出()
但真正的“核心”代码应该只在上午9点到下午5点之间执行

然后测试那个,而且只测试那个。将该测试放入一个在9到17之间才会返回的函数:

def wait_for_working_hours():
    now = dt.datetime.now()
    if 9 <= now.hour < 17:
        return

    # not within working hours, sleep until next 9 o'clock
    next9_day = now.date()
    if now.hour >= 17:
        # between 17:00 and 23:59:59.999999, next 9am is tomorrow
        next9_day += dt.timedelta(days=1)
    delta = dt.datetime.combine(next9_day, dt.time(9)) - now
    time.sleep(delta.total_seconds())

您是否只需要运行functionX的cron或芹菜任务?您始终可以反转测试,尤其是当您希望提前退出时:
如果不是somefunction():raise SystemExit()
。这允许您取消缩进现在缩进到
if somefunction():
下的代码。从软件工程的角度来看,尝试使用函数而不是大型嵌套结构。
shouldweecontinuetoday
已设置但未使用-或者这是
shouldweecontinue
的输入错误吗?不要直接引发
SystemExit
;只需调用
sys.exit
while True:
    if not some_function():
        sys.exit()

    wait_for_working_hours()

    # do things that need to be done during working hours
    # ...
    if some_condition:
        break

    # then sleep for a minute before doing it again.
    time.sleep(60)