3

15分ごとに状態をチェックするためにWHILEループを継続的に実行しようとしています。time.sleep(900)を使用する場合、代わりに、最初に15分間WHILEループの実行を保留し、条件が満たされると実行を停止します。

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)
4

1 に答える 1

2

この場合の問題は、フロートではなく文字列を比較していることだと思います。

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

そしてget_price、floatを返すように関数を変更するか、それをラップする必要があります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)
于 2013-03-25T01:52:02.223 に答える