[英]Check for a file's availability for a certain time and then break
我一直試圖打破一個循環,該循環旨在在某個位置查找文件。 我的意圖是讓我的腳本在特定時間內尋找該文件,然后中斷是否找到該文件,但我一無所知。
如何使腳本等待特定時間,然后在時間到時中斷?
這是我目前的腳本:
import os
import time
file_path = r"C:\Users\WCS\Desktop\item.txt"
time_limit = 5
while not os.path.exists(file_path):
time.sleep(1)
#is there any logic I can apply here to make the following line valid
# if waiting_time>=time_limit:break
print("Time's up")
def exists_timeout(path, timeout):
"""Return once <path> exists, or after <timeout> seconds,
whichever is sooner
"""
timer = timeout
while (not os.path.exists(path)) and timer > 0:
time.sleep(1)
timer -= 1
通過使用time.time()
函數執行actual time
減去 start time
來計算經過的時間,並分配一個將被修改的變量(此代碼中為file_exists
),並檢查文件是否存在並將其用於循環。
如下:
import os
import time
file_path = r"C:\Users\WCS\Desktop\item.txt"
time_limit = 5
start = time.time()
file_exists = os.path.exists(file_path)
while not file_exists:
time.sleep(1)
file_exists = os.path.exists(file_path)
elapsed = time.time() - start
if elapsed >= time_limit:
break
else:
print("File exist.")
print(elapsed)
print("Time's up")
import os
import time
file_path = r"C:\Users\WCS\Desktop\item.txt"
cTime=0
time_limit = 5
while cTime<time_limit:
if os.path.exists(file_path)==False:
cTime=cTime+1
time.sleep(1)
else:
pass
if cTime==5:
responce="Time's Up"
else:
responce='Found'
print(responce)
正如roganjosh所評論的那樣,如果您使用時間戳記,它將更加簡單。 我在下面添加了相關代碼:
import os
import time
from datetime import datetime, timedelta
file_path = r"C:\Users\WCS\Desktop\item.txt"
time_limit = datetime.now() + timedelta(seconds=5)
present = datetime.now()
while (not os.path.exists(path)) and present < time_limit:
present = datetime.now()
if present >= time_limit:
print("Time's up")
break
time.sleep(1)
這是使用threading.Timer()
類進行操作的方法。 可以將它們配置為延遲指定的時間,並根據您的選擇進行呼叫。
import os
from threading import Timer
import time
file_path = r"C:\Users\WCS\Desktop\item.txt"
# Timer callback function.
def timeout():
global time_ran_out
time_ran_out = True
time_limit = 5
time_ran_out = False # Define variable the callback function modifies.
timer = Timer(time_limit, timeout) # Create a timer thread object.
timer.start() # Start the background timer.
while not os.path.exists(file_path):
time.sleep(1)
if time_ran_out:
print('Times up!')
break
print("Done")
要檢查某個位置文件的可用性,可以嘗試以下操作。 一旦找到文件,腳本將立即中斷,否則將等待5秒鍾,直到文件可用為止。
import os
import time
file_path = r"C:\Users\WCS\Desktop\item.txt"
time_to_wait = 5
time_counter = 0
while not os.path.exists(file_path):
time.sleep(1)
time_counter += 1
if time_counter > time_to_wait:break
print("done")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.