2014年5月9日金曜日

開発環境

Head First Programming A learner's guide to programming using the Python language (David Griffiths(著)、Paul Barry(著)、 O'Reilly Media; )のChapter 3(functions: Let's get organized)、Sharpen your pencil(p.97)を解いてみる。

Sharpen your pencil(p.97)

コード(BBEdit)

sample97,.py

#!/usr/bin/env python3
#-*- coding: utf-8

import urllib.request
import time

def sendToTwitter(msg):
    print(msg)

def getPrice():
    page = urllib.request.urlopen(
        'http://www.beans-r-us.appspot.com/prices.html')
    text = page.read().decode('utf8')
    where = text.find('>$')
    start_of_price = where + 2
    end_of_price = start_of_price + 4
    return text[start_of_price:end_of_price]

question = input('Is price required immediately?(Y/N): ')

if question == 'Y':
    sendToTwitter(getPrice())
else:
    price = 99.99
    # s = 60 * 15
    s = 5
    while price > 4.74:
        time.sleep(s)
        price = float(getPrice())
        # テスト用
        print(time.gmtime().tm_sec)
        print('price: {0}'.format(price))
    sendToTwitter('Buy!({0})'.format(price))

入出力結果(Terminal)

$ ./sample97.py 
Is price required immediately?(Y/N): Y
5.90
$ ./sample97.py 
Is price required immediately?(Y/N): N
45
price: 6.24
51
price: 6.82
  C-c C-cTraceback (most recent call last):
  File "./sample97.py", line 28, in <module>
    time.sleep(s)
KeyboardInterrupt
$

0 コメント:

コメントを投稿