亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

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

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

SMILET 2022-07-19 16:48:39
我有以下帶有多個 if/else 和循環的 Python 代碼。它正在成為一個意大利面條代碼,如果可能的話,我想避免它。簡而言之,我希望腳本在無人值守的情況下運行一段時間(幾天/幾周),但代碼的真正“核心”應該只在上午 9 點到下午 5 點之間執行。代碼可以進一步簡化嗎?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貢獻1906條經驗 獲得超10個贊

但代碼的真正“核心”應該只在上午 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())

此功能會一直阻塞到上午 9 點到下午 5 點之間。

其他要改變的事情:

  • 不要使用while flagvariable: ...,你可以使用break來結束一個while True:循環。

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

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

連同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)


查看完整回答
反對 回復 2022-07-19
  • 1 回答
  • 0 關注
  • 153 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號