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 things
,else: 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)
添加回答
舉報