2013-03-25 36 views
3

我試圖持續運行一個WHILE循環來檢查每十五分鐘的情況。當使用time.sleep(900)時,它會首先執行WHILE循環15分鐘,然後在條件滿足時停止運行。在Python 3.3中的time.sleep()函數?

我相信Python 2因爲這個原因使用了這個函數,Python 3.3不會跟着這個嗎?如果不是,即使條件已滿足,我將如何無限期地通過while循環運行?

下面是我的代碼片段目前:

if price_now == 'Y': 
    print(get_price()) 
else: 
    price = "99.99" 
    while price > "7.74": 
     price = get_price() 
     time.sleep(5) 

編輯:更新基於eandersson反饋。

if price_now == 'Y': 
    print(get_price()) 
else: 
    price = 99.99 
    while price > 7.74: 
     price = get_price() 
     time.sleep(5) 

get_price()功能:

def get_price(): 
    page = urllib.request.urlopen("link redacted") 
    text = page.read().decode("utf8") 
    where = text.find('>$') 
    start_of_price = where + 2 
    end_of_price = start_of_price + 4 
    price = float(text[start_of_price:end_of_price]) 
    return(price) 
+0

更新您的問題,包括原代碼,以防止任何混淆。 :) – eandersson 2013-03-25 02:16:30

回答

2

我認爲在這種情況下,問題是,你比較字符串,而不是浮動。

price = 99.99 
while price > 7.74: 
    price = get_price() 
    time.sleep(5) 

而且你需要更改get_price函數返回一個浮動,或float()

我甚至做了一個小測試功能,以確保包裝它和它的作品如預期的睡眠功能。

price = 99.99 
while price > 7.74: 
    price += 1 
    time.sleep(5) 

編輯:Updated based on comments.

if price_now == 'Y': 
    print(get_price()) 
else: 
    price = 0.0 
    # While price is lower than 7.74 continue to check for price changes. 
    while price < 7.74: 
     price = get_price() 
     time.sleep(5) 
+0

嘿,謝謝!我改變了get_price()函數以包含浮動換行而不是字符串比較,以及改變price =和price>爲整數而不是字符串。我通過time.sleep(5)測試了代碼,但它似乎仍然運行一次,然後退出循環。 – Keith 2013-03-25 01:58:19

+0

你能更新例子中的代碼嗎? – eandersson 2013-03-25 01:59:30

+0

而@KMcK get_price()在測試期間現在返回什麼? – eandersson 2013-03-25 02:00:48