1 回答

TA貢獻1802條經驗 獲得超6個贊
您的解決方案看起來不錯。
我唯一想建議的是在兩個單獨的函數中取出讀取和寫入上次運行時間戳邏輯,并將這兩個函數移動到一個單獨的模塊文件中。這與上述回復中@Tomalak 的建議相同。下面是代碼示例。
模塊文件:last_run.py
import datetime
fmt = "%Y-%m-%d %H:%M:%S"
def get_last_run_time_stamp():
"""
Get last run time stamp\n
====\n
When this function called\n
AND last_run.txt file is present\n
Then open the file and read the time-stamp stored in it\n
====\n
When this function is called\n
AND last_run.txt file is not present\n
Then print the following message on console: "last_run.txt file is not available"\n
"""
# try loading the datetime of the last run, else print warning
try:
with open("last_run.txt", mode="r") as file:
return datetime.datetime.strptime(file.read(), fmt)
except:
# Return with current time-stamp if last_run.txt file is not present
return datetime.datetime.now().strftime(fmt)
# ... run script code using the last_run variable as input ...
def save_last_run_time_stamp():
"""
Save last run time stamp\n
====\n
When this function called\n
AND last_run.txt file is present\n
Then Open the file, save it with current time stamp and close the file\n
====\n
When this function called\n
AND last_run.txt file is not present\n
Then Create the file, open the file, save it with current time stamp and close the file\n
"""
# update the script execution time and save it to the file
with open("last_run.txt", mode="w") as file:
current_timestamp = datetime.datetime.now().strftime(fmt);
file.write(current_timestamp)
然后,下面是 schedular 配置和運行的文件:
run_latest_scaped_files.py,
import last_run as lr
last_run = lr.get_last_run_time_stamp()
print(last_run)
# ... run script code using the last_run variable as input ...
lr.save_last_run_time_stamp()
就是這樣?。?!
添加回答
舉報