15.3 项目:超级秒表
项目要求:自己用 Python 写一个简单的秒表程序
#! python3
# A simple stopwatch program.
import time
print('Press ENTER to begin. Afterwards, press ENTER to "click" the stopwatch. Press Ctrl-C to quit.')
input()
print('Started.')
startTime = time.time()
lastTime = startTime
lapNum = 1
try:
while True:
input()
laptime = round((time.time() - lastTime), 2)
totalTime = round((time.time() - startTime), 2)
print('Lap: %s; laptime: %s; totalTime: %s' % (lapNum, laptime, totalTime), end=' ')
lapNum += 1
lastTime = time.time()
except KeyboardInterrupt:
print('\nDONE!')
input('click any key to exit')
15.7 项目:多线程 XKCD 下载程序
项目要求:多线程程序中有一些线程在下载漫画,同时另一些线程在建立连接,或将漫画图像文件写入硬盘。它更有效地使用 Internet 连接,更迅速地下载这些漫画。打开一个新的文件编辑器窗口,并保存为 multidownloadXkcd.py。你将修改这个程序,添加多线程。
#! python3
# Downloads XKCD comics using multiple threads.
import os, bs4, requests
urls = 'http://xkcd.com'
os.makedirs('xkcd', exist_ok = True)
def comic_download_kxcd(startComic, endComic):
for num in range(startComic, endComic):
# todo: download the page
url = urls + '/%s/' % num
print('Downloading page %s...' % url)
res = requests.get(url)
try:
res.raise_for_status()
except requests.exceptions.HTTPError:
pass
soup = bs4.BeautifulSoup(res.text, "html.parser")
# todo: find the url of comic page
comicElems = soup.select('#comic img')
if comicElems == []:
print('Could not find comic image!')
else:
comicUrl = 'http:' + comicElems[0].get('src')
# todo: download the jpg
print('Downloading image %s' % comicUrl)
res = requests.get(comicUrl)
res.raise_for_status()
# todo: save jpg to ./xkcd
image_name = os.path.join('xkcd', os.path.basename(comicUrl))
with open(image_name, 'wb') as imageFile:
for chunk in res.iter_content(100000):
imageFile.write(chunk)
# todo: get the prev button's url
prevLink = soup.select('a[rel="prev"]')[0]
# Create and start the Thread objects.
import threading
comic_threads = []
for i in range(1,1400,100): # loops 14 times, creates 14 threads
comic_thread = threading.Thread(target=comic_download_kxcd, args=(i, i+5))
comic_threads.append(comic_thread)
comic_thread.start()
# Wait for all threads to end.
for comic_thread in comic_threads:
comic_thread.join()
print('Done.')
思路:
- 多线程这个真的很惊艳,第一次接触会觉得“居然还有这种操作?!”
- 按照书中步骤一步步码
15.9 项目:简单的倒计时程序
项目要求:让我们来写一个倒计时程序,在倒计时结束时报警。
#! python3
# A simple countdown script.
import time, subprocess
while True:
try:
time_l = int(input('Please input a time(seconds): '))
except Exception:
print('number please!')
else:
break
while time_l > 0:
print(time_l) # 不知道为什么这里传入end=" "会不显示数字进行倒计时
time.sleep(1)
time_l = time_l - 1
print('\nalert!!')
time.sleep(2)
a = subprocess.Popen(['start','abc001.txt'], shell=True)
15.12.1 实践项目:美化的秒表
项目要求:扩展本章的秒表项目,让它利用 rjust()和 ljust()字符串方法“美化”的输出。
#! python3
# A simple stopwatch program.
import time
print('Press ENTER to begin. Afterwards, press ENTER to "click" the stopwatch. Press Ctrl-C to quit.')
input()
print('Started.')
startTime = time.time()
lastTime = startTime
lapNum = 1
try:
while True:
input()
laptime = round((time.time() - lastTime), 2)
totalTime = round((time.time() - startTime), 2)
print('Lap #' + str(lapNum).rjust(2) + ':' + ('%.2f'%totalTime).rjust(6) +
' (' + ('%.2f'%laptime).rjust(5) + ')',end=' ')
lapNum += 1
lastTime = time.time()
except KeyboardInterrupt:
print('\nDONE!')
input('click any key to exit')
15.12.2 实践项目:计划的 Web 漫画下载
- 容我偷个懒
环境:python3
想做这个系列文章,就是因为当时看这本书时,想看看网上有没更优美的解决,但是略难找到。所以就把自己的项目练习放在了一个txt文件中,现在把练习代码放到这里,有不足之处希望大家能给出指导意见及相互交流、提升。