第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

SMILET 2022-07-19 16:48:39
我有以下帶有多個 if/else 和循環(huán)的 Python 代碼。它正在成為一個意大利面條代碼,如果可能的話,我想避免它。簡而言之,我希望腳本在無人值守的情況下運(yùn)行一段時間(幾天/幾周),但代碼的真正“核心”應(yīng)該只在上午 9 點(diǎn)到下午 5 點(diǎn)之間執(zhí)行。代碼可以進(jìn)一步簡化嗎?shouldweContinue = Truewhile 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()
查看完整描述

1 回答

?
隔江千里

TA貢獻(xiàn)1906條經(jīng)驗 獲得超10個贊

但代碼的真正“核心”應(yīng)該只在上午 9 點(diǎn)到下午 5 點(diǎn)之間執(zhí)行。


然后測試那個,只有那個。將該測試放入一個在 9 到 17 之間才會返回的函數(shù)中:


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())

此功能會一直阻塞到上午 9 點(diǎn)到下午 5 點(diǎn)之間。

其他要改變的事情:

  • 不要使用while flagvariable: ...,你可以使用break來結(jié)束一個while True:循環(huán)。

  • 我會使用sys.exit()而不是raise SystemExit().

  • 而不是if test: # do thingselse: exit,將退出條件放在前面,提早。因此if not test: exit,該# do things部分也不再需要縮進(jìn)。

連同wait_for_working_hours看起來像這樣的:

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)


查看完整回答
反對 回復(fù) 2022-07-19
  • 1 回答
  • 0 關(guān)注
  • 143 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號