Skip to content

Commit

Permalink
Chapter 15 finished.
Browse files Browse the repository at this point in the history
  • Loading branch information
chenguohui committed Jul 9, 2017
1 parent 3bf0bfd commit 321d1df
Show file tree
Hide file tree
Showing 11 changed files with 142 additions and 0 deletions.
12 changes: 12 additions & 0 deletions 15-time/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# time
<pre>
import time
now = time.time()
</pre>

# datetime
1. import datetime
2. datetime.datetime.now()
3. datetime.datetime.fromtimestamp(time.time())
4. datetime.timedelta()

4 changes: 4 additions & 0 deletions 15-time/about30YearsLater.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import datetime

aboutThirtyYears = datetime.timedelta(days=365*30)
print(datetime.datetime.now() + aboutThirtyYears)
9 changes: 9 additions & 0 deletions 15-time/calcProd.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import time
startTime = time.time()
# Calculate the product of the first 100,000 numbers.
product = 1
for i in range(1, 100000):
product = product * i
endTime = time.time()
print('The result is %s digits long.' % (len(str(product))))
print('Took %s seconds to calculate.' % (endTime - startTime))
13 changes: 13 additions & 0 deletions 15-time/countdown.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
#! python3
# countdown.py - A simple countdown script.

import time, subprocess

timeLeft = 10
while timeLeft > 0:
print(timeLeft, end='')
time.sleep(1)
timeLeft = timeLeft - 1

# At the end of the countdown, play a sound file.
subprocess.Popen(['start','alarm.wav'], shell=True)
43 changes: 43 additions & 0 deletions 15-time/multidownloadXkcd.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#! python3
# multidownloadXkcd.py - Downloads XKCD comics using multiple threads.

import requests, os, bs4, threading
os.makedirs('xkcd', exist_ok=True) # store comics in ./xkcd

def downloadXkcd(startComic, endComic):
for urlNumber in range(startComic, endComic):
# Download the page.
print('Downloading page http://xkcd.com/%s...' % (urlNumber))
res = requests.get('http://xkcd.com/%s' % (urlNumber))
res.raise_for_status()

soup = bs4.BeautifulSoup(res.text)

# Find the URL of the comic image.
comicElem = soup.select('#comic img')
if comicElem == []:
print('Could not find comic image.')
else:
comicUrl = comicElem[0].get('src')
# Download the image.
print('Downloading image %s...' % (comicUrl))
res = requests.get(comicUrl)
res.raise_for_status()

# Save the image to ./xkcd
imageFile = open(os.path.join('xkcd', os.path.basename(comicUrl)), 'wb')
for chunk in res.iter_content(100000):
imageFile.write(chunk)
imageFile.close()

# Create and start the Thread objects.
downloadThreads = [] # a list of all the Thread objects
for i in range(0, 1400, 100): # loops 14 times, creates 14 threads
downloadThread = threading.Thread(target=downloadXkcd, args=(i, i + 99))
downloadThreads.append(downloadThread)
downloadThread.start()

# Wait for all threads to end.
for downloadThread in downloadThreads:
downloadThread.join()
print('Done.')
25 changes: 25 additions & 0 deletions 15-time/stopwatch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#! python3
# stopwatch.py - A simple stopwatch program.

import time

# Display the program's instructions.
print('Press enter to begin. Afterwards, press ENTER to "click" the stopwatch. Press Ctrl-C to quit.')
input() # press Enter to begin
print('Started.')
startTime = time.time() # get the first lap's start 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), end='')
lapNum += 1
lastTime = time.time() # reset the last lap time
except KeyboardInterrupt:
# Handle the Ctrl-C exception to keep its error message from displaying.
print('\nDone.')
5 changes: 5 additions & 0 deletions 15-time/thousandDaysLater.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import datetime

dt = datetime.datetime.now()
thousandDays = datetime.timedelta(days=1000)
print(dt + thousandDays)
11 changes: 11 additions & 0 deletions 15-time/threadDemo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import threading, time
print('Start of program.')

def takeANap():
time.sleep(5)
print('Wake up!')

threadObj = threading.Thread(target=takeANap)
threadObj.start()

print('End of program.')
6 changes: 6 additions & 0 deletions 15-time/threadWithParameters.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import threading

threadObj = threading.Thread(target=print, args=['Cats', 'Dogs', 'Frogs'],
kwargs={'sep': ' & '})
threadObj.start()

8 changes: 8 additions & 0 deletions 15-time/timeSleep.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import time

for i in range(3):
print('Tick')
time.sleep(1)
print('Tock')
time.sleep(1)

6 changes: 6 additions & 0 deletions 15-time/until.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import datetime
import time
tm = datetime.datetime(2017, 7, 8, 8, 27, 0)
while datetime.datetime.now() < tm:
time.sleep(1)
print('Done')

0 comments on commit 321d1df

Please sign in to comment.