Chapter 15 – Keeping Time, Scheduling Tasks, and Launching Programs
非计算机出身,最近一直在看《Automate the Boring Stuff with Python》,为了能够很好的理解和学习,一直坚持在做文后的练习题。但一个人学习实在是太累太难,准备将自己的做的练习题记录下来,希望得到高手的指导,来拓展个人解决问题的思路、提升代码质量。
传送门:
Chapter 12 – Working with Excel Spreadsheets
Chapter 13 – Working with PDF and Word Documents
Chapter 14 – Working with CSV Files and JSON Data
Chapter 17 – Manipulating Images
Chapter 18 – Controlling the Keyboard and Mouse with GUI Automation
Prettified Stopwatch
Expand the stopwatch project from this chapter so that it uses the rjust() and ljust() string methods to “prettify” the output. (These methods were covered in Chapter 6.) Instead of output such as this:
<pre class="programlisting" style="color: rgb(0, 0, 0); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 254, 238); text-decoration-style: initial; text-decoration-color: initial;">Lap #1: 3.56 (3.56)
Lap #2: 8.63 (5.07)
Lap #3: 17.68 (9.05)
Lap #4: 19.11 (1.43)</pre>
... the output will look like this:
<pre class="programlisting" style="color: rgb(0, 0, 0); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 254, 238); text-decoration-style: initial; text-decoration-color: initial;">Lap # 1: 3.56 ( 3.56)
Lap # 2: 8.63 ( 5.07)
Lap # 3: 17.68 ( 9.05)
Lap # 4: 19.11 ( 1.43)</pre>
Note that you will need string versions of the lapNum, lapTime, and totalTime integer and float variables in order to call the string methods on them.
Next, use the pyperclip module introduced in Chapter 6 to copy the text output to the clipboard so the user can quickly paste the output to a text file or email.
#! python3
# stopWatch.py - A simple stopwatch program.
import time
import pyperclip
# Display the program's instructions.
print('Press ENTER to begin. Afterwards,press ENTER to "click" the stopwatch. print Ctrl-c to quit.')
input()
print('Started.')
startTime = time.time()
lastTime = startTime
lapNum = 1
# Start tracking the lap times.
try:
while True:
input()
lapTime = round(time.time() - lastTime, 2)
totalTime = round(time.time() - startTime, 2)
# print('Lap # %s:%s(%s)'%(lapNum,totalTime,lapTime))
print('Lap #' + str(lapNum).rjust(3) + str(totalTime).rjust(8) + ' (' + str(lapTime).rjust(6) + ')')
outPutTxt = 'Lap # ' + str(lapNum).rjust(3) + str(totalTime).rjust(8) + ' (' + str(lapTime).rjust(6) + ')'
lapNum += 1
lastTime = time.time()
except KeyboardInterrupt:
# Handle the Ctrl-c exception to keep its errors message from displaying.
print('\nDone')
pyperclip.copy(outPutTxt)