Python3 script to query free TOEFL seats

应同学要求,写了一个爬托福考试空闲考位的脚本。这是第一次真正用Python3写。

通过调用get_seat_status,传入省名(如’Jiangsu’),时间(如’201104′),您可以得到这样的数据结构:

[ [datetime.datetime(2011, 4, 23, 10, 0),  'STN80085B',  '南通市教育装备与勤工俭学管理中心',  '1415',  True],
 [datetime.datetime(2011, 4, 23, 10, 0), 'STN80086A', '扬州大学', '1415', True]]

下面是一个多线程调用的例子:

#! /usr/bin/python3

import threading
import pprint
from toeflgraber import get_seat_status

# 查询江浙沪 2011年3月和4月的考位
locations = ['Jiangsu', 'Shanghai', 'Zhejiang']
months = ['201103', '201104']

def descartes(x, y):
    for i in x:
        for j in y:
            yield (i, j)

lock = threading.RLock()
tasks = len(locations) * len(months)
e = threading.Event()
results = []

def task(location, month):
    global results, tasks
    all_seats = get_seat_status(location, month)
    available_seats = filter(lambda x: x[4], all_seats)
    with lock:
        results.extend(available_seats)
        tasks -= 1
        if tasks == 0:
            e.set()

for t in descartes(locations, months):
    t = threading.Thread(target=task, args=t)
    t.daemon = True
    t.start()

e.wait()
pprint.pprint(results)

Enjoy it.