COMPUTER SCIENCE
code 30424 a.y. 2018-19
Lesson 15
Expanding Python capabilities: the libraries
SEDIN
IT Education Services Center
2
Objectives of the lesson
Use the standard Python library and some useful extensions to
create interaction between Python and other tools such as: Excel,
a web browser etc.
3
The modules
• All programming languages can be enriched by extensions in order to execute
specialized additional functionalities
• In Python, additional functionalities come as modules: these are files acting
as containers, grouping useful functionalities by the topic they relate to
• Some are part of the basic Python installation, and we already met some
examples as math, turtle and copy
• Modules can be organized in libraries or «packages»
• Modules installed by default with Python make up the Python standard library
• There are many custom modules available for the most diverse purposes
4
Standard and custom modules
Modules
Standard Custom
Installation
Import
5
Importing modules
Assuming a module is installed, in order to use it we need to import it into the
program's running session.
Invoking a functionality of a module without having imported it, raise an error
message:
The command we need is import, which also allows to import different
modules at the same time:
N.B.: importing is valid only for the current session!
6
The dir function
The dir command shows the list of the loaded modules (those always
available in Python, and those loaded in the current session):
The same command also allows listing the functions and classes offered from
a specified module:
7
The help function on modules
As already seen for
functions and other objects,
you can also use the help to
get information about
modules:
Or on specific functions
they contain:
The help function can only be used if the module has been imported
8
The help function on modules
Standard
Library
Custom
modules
9
Modules from the standard library
We are going now to explore some other modules from the standard library,
showing some examples:
• os (to interact with the Operating System)
• random (to generate random numbers)
• webbrowser (to open web pages in the browser)
• smtplib (to send emails)
10
os module
It is a Python module to interact with the Operating System, quite useful to
inspect and manipulate files and folders.
Some functions:
os.listdir([path])
Returns a list with names of files and folders available in the folder specified as argument
os.path.join(path,filename)
Returns the complete path of a file in the specified folder
os.path.isfile(path)
Returns True if the path is referring to a file, False otherwise
https://docs.python.org/3/library/os.html
11
os module: example
The os module allows accessing the folder structure on the storage device,
obtaining the list of the elements in each folder and processing their
attributes:
12
random module
Allows generating random numbers, with some useful functions:
random.random()
Returns a random decimal number between 0 and 1
random.randint(min, max)
Returns a random integer number between min and max
random.choice([list])
Returns a random element from given list
random.randrange(min,max,step)
Returns a random integer between min and max with step increase
https://docs.python.org/3/library/random.html
13
webbrowser module
Allows opening a URL in the browser.
The relevant function is:
webbrowser.open(URL)
Which asks the browser to open URL
example
import webbrowser
webbrowser.open('www.unibocconi.eu')
https://docs.python.org/3/library/webbrowser.html
14
smtplib module
Allows sending email from Python.
Relevant functions:
smtplib.SMTP_SSL('address', port)
Returns an object representing a network connection done with the SMTP_SSL protocol
with the port of the server indicated as address
login('username', ’password’ )
Method of the above object which authenticates on a server with given credentials
https://docs.python.org/3/library/smtplib.html
15
smtplib module: example
The smtplib module allows connecting to and authenticating on a server
and delivering an email message.
16
Custom modules
Specialized modules, innovating or for niche audience, must be installed by
every user.
Where to find them?
PyPI - the Python Package Index is the official site collecting and categorizing
most of the available modules
There is a wide choice on web sites offering information and download of
modules. For instance UsefulModules: a list of the most popular Python
modules (aimed at a beginners’ audience) categorized by reference topic
17
Installing custom modules
To use a custom module it is necessary to download it and install it
following the instructions, or simply running pip install modulename from
the command line of the operating system:
• Write cmd in the search box of the Windows menu (in MacOS, open the
Terminal application)
• In the command line, we write
pip install modulename
18
Installing the modules for the lecture
We install now the modules we will need for the lesson:
• pyperclip
• openpyxl
• requests
• matplotlib
(it is a package: we will use its pyplot module)
19
pyperclip module
Allows the copy and paste functionalities:
pyperclip.copy('text to copy')
Copies the argument to the clipboard
pasted = pyperclip.paste()
Returns the content of the paste command as a string
https://github.com/asweigart/pyperclip
20
pyperclip module: example
In this example we use pyperclip and webbrowser to perform a search in
Google Maps through Python:
21
openpyxl module
Allows reading and writing Excel files. Some relevant commands:
wb = openpyxl.load_workbook('filename.xlsx’)
Opens the Excel workbook given as argument and returns it as an object (wb in this example)
xlws = wb[‘worksheetname']
Opens a worksheet contained in wb and returns it as an object (named xlws in the example)
xlws.cell(x,y).value
Returns the value of the cell at coordinates x,y of the worksheet xlws
https://openpyxl.readthedocs.io/en/stable/
22
openpyxl module example
We can see openpyxl in action, to read data from an Excel worksheet:
23
requests module
Allows Python to interacting directly with the Web, automating some
operations.
Relevant functions:
page = requests.get(URL)
Opens the web address specified as URL argument and downloads its content
page.text
Returns as a text the HTML content of the downloaded page
http://docs.python-requests.org/en/master/
24
requests module: example
This program extracts the HTML code from the Bocconi home page:
25
matplotlib.pyplot module
The pyplot module from the matplotlib library is a powerful library for 2D
graphics which allows charting scatter plots, histograms, spectrograms, bar
graphs and much more.
For instance:
matplotlib.pyplot.plot (X, Y, formats)
Draws on a cartesian plot the values from X and Y (these shall be lists of values).
The formats argument has a syntax to control the appearance of charts: e.g. '-' to draw a
continuous line, 'o' for circles, 'g' for green.
https://matplotlib.org
26
matplotlib.pyplot module: example
Example of a basic line plot:
27
Tools we learnt with today’s lesson
• Understand the logic of modules usage and the concept of code modularity
• Understand how to include the use of modules in our own code
• Understand how to install modules in our own working environment
• Know how to explore the available modules and use the documentation
• Get to know some of the most used modules of the standard library
• Know the main external modules and know how and where to find others in
order to fulfil our own studying and professional needs
28
Files of the lesson
In the zip file 30424 ENG - 30 - Lesson 15.zip you will find these files:
• 30424 lesson 15 slides.pdf: these slides
• .py files with examples shown during the lesson
• 30424 lesson 15 exercises.zip: exercises on the content of the lesson
29
Book references
Learning Python:
Chapter 11
(except paragraphs 11.2.5, 11.2.10, 11.2.11, 11.2.12, 11.2.13, 11.2.14, 11.2.15, 11.5)
Documentation of the modules (see url on each slide)
Assignment:
Exercises of lesson 15