Added example answers for chapters 13 and 14 to fix #1
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
# Read all files in a directory and sum the size of the files by
|
||||
# reading each file using `multiprocessing`
|
||||
|
||||
import logging
|
||||
import multiprocessing
|
||||
import pathlib
|
||||
|
||||
# Directory to process
|
||||
PATH = pathlib.Path(__file__).parent.parent
|
||||
|
||||
# We need to setup the logging outside of the
|
||||
# `if __name__ == '__main__'` block because the
|
||||
# `multiprocessing` module will not execute that section.
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
|
||||
def get_size(path: pathlib.Path):
|
||||
size = path.stat().st_size
|
||||
logging.info(
|
||||
'%s is %d bytes',
|
||||
path.relative_to(PATH),
|
||||
size,
|
||||
)
|
||||
return size
|
||||
|
||||
|
||||
def main(path: pathlib.Path):
|
||||
with multiprocessing.Pool() as pool:
|
||||
total_size = sum(pool.map(get_size, path.iterdir()))
|
||||
|
||||
print(f'Total size for {path} is: {total_size}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main(PATH)
|
||||
@@ -0,0 +1,45 @@
|
||||
# Read all files in a directory and sum the size of the files by
|
||||
# reading each file using `threading`
|
||||
|
||||
import logging
|
||||
import pathlib
|
||||
import threading
|
||||
|
||||
# Directory to process
|
||||
PATH = pathlib.Path(__file__).parent.parent
|
||||
|
||||
|
||||
class FileSizeThread(threading.Thread):
|
||||
|
||||
def __init__(self, path: pathlib.Path):
|
||||
super().__init__()
|
||||
self.path = path
|
||||
self.size = 0
|
||||
|
||||
def run(self):
|
||||
self.size = self.path.stat().st_size
|
||||
logging.info(
|
||||
'%s is %d bytes',
|
||||
self.path.relative_to(PATH),
|
||||
self.size,
|
||||
)
|
||||
|
||||
|
||||
def main(path: pathlib.Path):
|
||||
threads = []
|
||||
for child in path.iterdir():
|
||||
thread = FileSizeThread(child)
|
||||
thread.start()
|
||||
threads.append(thread)
|
||||
|
||||
total_size = 0
|
||||
for thread in threads:
|
||||
thread.join()
|
||||
total_size += thread.size
|
||||
|
||||
print(f'Total size for {path} is: {total_size}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
main(PATH)
|
||||
Reference in New Issue
Block a user