Python The Complete Manual
Python The Complete Manual
Publishing Director
Aaron Asadi
Head of Design
Ross Andrews
Editor in Chief
Jon White
Production Editor
Ross Hamilton
Designer
Alexander Phoenix
Photographer
James Sheppard
Printed by
William Gibbons, 26 Planetary Road, Willenhall, West Midlands, WV13 3XT
Distributed in Australia by
Gordon & Gotch Australia Pty Ltd, 26 Rodborough Road, Frenchs Forest, NSW, 2086 Australia
Tel +61 2 9972 8800 www.gordongotch.com.au
Disclaimer
The publisher cannot accept responsibility for any unsolicited material lost or damaged in the
post. All text and layout is the copyright of Imagine Publishing Ltd. Nothing in this bookazine may
be reproduced in whole or part without the written permission of the publisher. All copyrights are
recognised and used specifically for the purpose of criticism and review. Although the bookazine has
endeavoured to ensure all information is correct at time of print, prices and availability may change.
This bookazine is fully independent and not affiliated in any way with the companies mentioned herein.
Python is a trademark of Python Inc., registered in the U.S. and other countries.
Python © 2016 Python Inc.
Python The Complete Manual Second Edition © 2016 Imagine Publishing Ltd
Part of the
bookazine series
Contents
What you can find inside the bookazine
Code
& create
with
Python!
6
Get started
with
Python 8 Masterclass
Discover the basics of Python
7
Get with
started
Python
Always wanted to have a go at programming? No more
excuses, because Python is the perfect way to get started!
Python is a great programming language for both beginners and experts. It
is designed with code readability in mind, making it an excellent choice for
beginners who are still getting used to various programming concepts.
The language is popular and has plenty of libraries available, allowing
programmers to get a lot done with relatively little code.
You can make all kinds of applications in Python: you could use the
Pygame framework to write simple 2D games, you could use the GTK
libraries to create a windowed application, or you could try something
a little more ambitious like an app such as creating one using Python’s
Bluetooth and Input libraries to capture the input from a USB keyboard and
relay the input events to an Android phone.
For this tutorial we’re going to be using Python 2.x since that is the
version that is most likely to be installed on your Linux distribution.
In the following tutorials, you’ll learn how to create popular games using
Python programming. We’ll also show you how to add sound and AI to
these games.
8
Get started with Python Getting started
9
Hello World
Let’s get stuck in, and what better way than with the programmer’s
best friend, the ‘Hello World’ application! Start by opening a terminal.
Its current working directory will be your home directory. It’s probably
a good idea to make a directory for the files that we’ll be creating in
this tutorial, rather than having them loose in your home directory.
You can create a directory called Python using the command mkdir
Python. You’ll then want to change into that directory using the
command cd Python.
The next step is to create an empty file using the command ‘touch’
followed by the filename. Our expert used the command touch
hello_world.py. The final and most important part of setting up the
file is making it executable. This allows us to run code inside the hello_
world.py file. We do this with the command chmod +x hello_world.
py. Now that we have our file set up, we can go ahead and open it up
in nano, or alternatively any text editor of your choice. Gedit is a great
editor with syntax highlighting support that should be available on any
distribution. You’ll be able to install it using your package manager if
you don’t have it already.
Our Hello World program is very simple, it only needs two lines.
The first line begins with a ‘shebang’ (the symbol #! – also known
10
Get started with Python Getting started
#!/usr/bin/env python2
print(“Hello World”)
As well as these main data types, there are sequence types (technically,
Tip a string is a sequence type but is so commonly used we’ve classed it
At this point, it’s worth explaining as a main data type):
that any text in a Python file
that follows a # character will be
ignored by the interpreter. This List Contains a collection of data in a specific order
is so you can write comments in
your code. Tuple Contains a collection immutable data in a specific
order
12
Get started with Python Getting started
You could
hello_list = list()
also create the
hello_list.append(“Hello,”)
same list in the
hello_list.append(“this”)
following way
hello_list.append(“is”)
hello_list.append(“a”)
hello_list.append(“list”)
13
Getting started Get started with Python
We might as well as we# are using the same variable name as the
create a dictionary previous list.
while we’re at it.
Notice how we’ve hello_dict = { “first_name” : “Liam”,
aligned the colons “last_name” :
below to make the “Fraser”,
code tidy “eye_colour” : “Blue” }
Remember
that tuples are print(str(hello_tuple[0]))
immutable, # We can’t change the value of those elements
although we like we just did with the list
can access the # Notice the use of the str function above to
elements of them explicitly convert the integer
like so # value inside the tuple to a string before
printing it.
Let’s create a
sentence using
the data in our print(hello_dict[“first_name”] + “ “ + hello_
hello_dict dict[“last_name”] + “ has “ +
hello_dict[“eye_colour”] + “ eyes.”)
A much tidier way
of doing this would
be to use Python’s print(“{0} {1} has {2} eyes.”.format(hello_
string formatter dict[“first_name”],
hello_dict[“last_name”],
hello_dict[“eye_colour”]))
14
Get started with Python Getting started
Indentation in detail
Control structures
In programming, a control structure is any kind of statement that can
change the path that the code execution takes. For example, a control
structure that decided to end the program if a number was less than 5
would look something like this:
#!/usr/bin/env python2
import sys # Used for the sys.exit function
int_condition = 5
if int_condition < 6:
sys.exit(“int_condition must be >= 6”)
else:
print(“int_condition was >= 6 - continuing”)
The path that the code takes will depend on the value of
the integer int_condition. The code in the ‘if’ block will only be
executed if the condition is true. The import statement is used to
load the Python system library; the latter provides the exit function,
allowing you to exit the program, printing an error message. Notice
that indentation (in this case four spaces per indent) is used to indicate
which statement a block of code belongs to. ‘If’ statements are
probably the most commonly used control structures. Other control
[liam@liam-laptop Python]$ ./
construct.py
How many integers? acd
You must enter an integer
[liam@liam-laptop Python]$ ./
construct.py
How many integers? 3
Please enter integer 1: t
You must enter an integer
Please enter integer 1: 5
Please enter integer 2: 2
Please enter integer 3: 6
Using a for loop
5
2
6
Using a while loop
5
2
6
48
Practical Python tips and projects Work with Python
49
Work with Python Replace your shell with Python
1. File management
The Python module shutil provides support for file and directory
operations. It provides support for file attributes, directory copying,
archiving etc. Let’s look at some of its important functions.
shutil module
50
Replace your shell with Python Work with Python
copy (src,dst): Copy the src file to the destination directory. In this
mode permissions bits are copied but metadata is not copied.
copy2 (src,dst): Same as copy() but also copies the metadata.
copytree(src, dst[, symlinks=False[, ignore=None]]): This is
similar to ‘cp -r’, it allows you to copy an entire directory.
ignore_patterns (*patterns): ignore_patterns is an interesting
function that can be used as a callable for copytree(), it allows you to
ignore files and directories specified by the glob-style patterns.
rmtree(path[, ignore_errors[, onerror]]): rmtree() is used to
delete an entire directory.
move(src,dst): Similar to mv command it allows you to recessively
move a file or directory to a new location.
Example:
from shutil import copytree, ignore_patterns
copytree(source, destination, ignore=ignore_patterns(‘*. Above You may never need to use Bash
pyc’, ‘tmp*’)) again, with some dedicated Python
modules at hand
Example
from shutil import make_archive
import os
archive_name = os.path.expanduser(os.path.join(‘~’,
‘ludarchive’))
root_dir = os.path.expanduser(os.path.join(‘~’, ‘.ssh’))
make_archive(archive_name, ‘gztar’, root_dir)
‘/Users/kunal/ludarchive.tar.gz’
os module
environ: environment represents the OS environment variables in a
string object.
Example:
import os
os.environ
You can also find out the value for an environment value:
os.environ[‘HOME’]
‘/Users/kunaldeo’
52
Replace your shell with Python Work with Python
Example:
os.listdir(“/home/homer”)
Example:
import os
path = “/home/kunal/greatdir”
os.makedirs( path, 0755 );
53
Work with Python Replace your shell with Python
recessively if necessary.
subprocess:
Example:
import subprocess
print subprocess.call([“ls”,”-l”])
total 3684688
drwx------+ 5 kunaldeo staff 170 Aug 19 01:37 Desktop
drwx------+ 10 kunaldeo staff 340 Jul 26 08:30
Documents
drwx------+ 50 kunaldeo staff 1700 Aug 19 12:50
Downloads
drwx------@ 127 kunaldeo staff 4318 Aug 19 01:43 Dropbox
drwx------@ 42 kunaldeo staff 1428 Aug 12 15:17 Library
drwx------@ 3 kunaldeo staff 102 Jul 3 23:23 Movies
drwx------+ 4 kunaldeo staff 136 Jul 6 08:32 Music
drwx------+ 5 kunaldeo staff 170 Aug 12 11:26 Pictures
drwxr-xr-x+ 5 kunaldeo staff 170 Jul 3 23:23 Public
-rwxr-xr-x 1 kunaldeo staff 1886555648 Aug 16 21:02
androidsdk.tar
drwxr-xr-x 5 kunaldeo staff 170 Aug 16 21:05 sdk
drwxr-xr-x 19 kunaldeo staff 646 Aug 19 01:47 src
-rw-r--r-- 1 root staff 367 Aug 16 20:36
umbrella0.log
Example :
In [3]: import o {hit tab}
objc opcode operator optparse os os2emxpath
In [3]: import os
Built In Object Explorer: You can add ‘?’ after any Python object
to view its details such as Type, Base Class, String Form, Namespace, File
and Docstring.
55
Work with Python Replace your shell with Python
Example:
In [28]: os.path?
Type: module
Base Class: <type ‘module’>
String Form:<module ‘posixpath’ from ‘/System/Library/
Frameworks/Python.framework/Versions/2.7/lib/python2.7/
posixpath.pyc’>
Namespace: Interactive
File: /System/Library/Frameworks/Python.framework/
Versions/2.7/lib/python2.7/posixpath.py
Docstring:
Common operations on POSIX pathnames.
Example:
In [45]: %lsmagic
Available magic functions:
%alias %autocall %autoindent %automagic %bookmark %cd
%colors %cpaste %debug %dhist %dirs %doctest_mode %ed
%edit %env %gui %hist %history %install_default_config
%install_profiles %load_ext %loadpy %logoff %logon
%logstart %logstate %logstop %lsmagic %macro %magic
56
Replace your shell with Python Work with Python
Example :
In [5]: !ps
PID TTY TIME CMD
4508 ttys000 0:00.07 -bash
84275 ttys001 0:00.03 -bash
17958 ttys002 0:00.18 -bash
Matplotlib
www.matplotlib.org
computing
with NumPy
Make some powerful calculations with NumPy,
SciPy and Matplotlib
NumPy is the primary Python package for performing scientific
computing. It has a powerful N-dimensional array object, tools
for integrating C/C++ and Fortran code, linear algebra, Fourier
transform, and random number capabilities, among other things.
NumPy also supports broadcasting, which is a clever way for
universal functions to deal in a meaningful way with inputs that do
not have exactly the same form.
Apart from its capabilities, the other advantage of NumPy is that it
can be integrated into Python programs. In other words, you may
get your data from a database, the output of another program, an
external file or an HTML page and then process it using NumPy.
This article will show you how to install NumPy, make calculations,
plot data, read and write external files, and it will introduce you to
some Matplotlib and SciPy packages that work well with NumPy.
NumPy also works with Pygame, a Python package for creating
games, though explaining its use is unfortunately beyond of the
scope of this article.
It is considered good practice to try the various NumPy
commands inside the Python shell before putting them into
Python programs. The examples in this article use either Python
shell or iPython.
58
Scientific computing with NumPy Work with Python
59
Work with Python Scientific computing with NumPy
>>> twoD[1,2]
assigning it to a new array variable can
be done as follows: 08 A special subtype of a two-
dimensional NumPy array is
a matrix. A matrix is like an array except
You can also select a part of an array (a aa = np.loadtxt(“timeN.txt”) that matrix multiplication replaces
slice) using the following notation: element-by-element multiplication.
Matrices are generated using
>>> twoD[:1,1:3] Writing to files the matrix (or mat) function as follows:
60
Scientific computing with NumPy Work with Python
You can add matrices named AA and dependencies that you should
BB by typing AA + BB. Similarly, you also install. The first thing you will
can multiply them by typing AA * BB. learn is how to plot a polynomial “Try the various
Plotting with Matplotlib
function. The necessary commands
for plotting the 3x^2-x+1 NumPy
polynomial are the following: commands inside
09 The first move you should
make is to install Matplotlib.
As you can see, Matplotlib has many
import numpy as np
import matplotlib.pyplot
the Python shell”
61
Work with Python Scientific computing with NumPy
“For plotting
polynomial
functions,
experiment more”
62
Scientific computing with NumPy Work with Python
63
Work with Python Python for system administrators
setuptools
setuptools allows you to download,
build, install, upgrade, and uninstall
Python packages with ease
administrators
Learn how Python can help by daring to replace the
usual shell scripting…
System administration is an important part of our computing
Note environment. It does not matter whether you are managing systems
This is written for the Python at your work our home. Linux, being a UNIX-based operating system,
2.X series, as it is still the most already has everything a system administrator needs, such as the
popular and default Python
distribution across all the world-class shells (not just one but many, including Bash, csh, zsh etc),
platforms (including all Linux handy tools, and many other features which make the Linux system an
distros, BSDs and Mac OS X).
administrator’s dream. So why do we need Python when Linux already
has everything built-in? Being a dynamic scripting language, Python
is very easy to read and learn. That’s just not us saying that, but many
Linux distributions actually use Python in core administrative parts. For
example, Red Hat (and Fedora) system setup tool Anaconda is written
in Python (read this line again, got the snake connection?). Also, tools like
GNU Mailman, CompizConfig Settings Manager (CCSM) and hundreds
of tiny GUI and non-GUI configuration tools are written using Python.
Python does not limit you on the choice of user interface to follow – you
can build command-line, GUI and web apps using Python. This way, it
has got covered almost all the possible interfaces. Here we will look into
executing sysadmin-related tasks using Python.
64
Python for system administrators Work with Python
and is completely language-independent. JSON is For this section we will use the simplejson.load
also used as the configuration file format for modern function, which allows us to deserialise a JSON object
applications such as Mozilla Firefox and Google into a Python object.
Chrome. JSON is also very popular with modern
web services such as Facebook, Twitter, Amazon EC2 @code: LUDSearch.py
etc. In this section we will use the Python module import simplejson, urllib
‘simplejson’ to access Yahoo Search (using the Yahoo APP_ID = ‘xxxxxxxx’ # Change this to
Web Services API), which outputs JSON data. your APP ID
To use this section, you should have the following: SEARCH_BASE = ‘http://search.yahooapis.
com/WebSearchService/V1/webSearch’
1. Python module: simplejson.
Note: You can install Python modules using the class YahooSearchError(Exception):
command ‘easy_install <module name>’. This pass
command assumes that you have a working internet
connection. def search(query, results=20, start=1,
2. Yahoo App ID: **kwargs):
The Yahoo App ID can be created from https:// kwargs.update({
developer.apps.yahoo.com/dashboard/createKey. ‘appid’: APP_ID,
html. The Yahoo App ID will be generated on the ‘query’: query,
next page. See the screenshot below for details. ‘results’: results,
simplejson is very easy to use. In the following ‘start’: start,
example we will use the capability of mapping ‘output’: ‘json’
JSON data structures directly to Python data types. })
This gives us direct access to the JSON data without url = SEARCH_BASE + ‘?’ + urllib.
developing any XML parsing code. urlencode(kwargs)
result = simplejson.load(urllib.
urlopen(url))
JSON PYTHON DATA MAPPING
if ‘Error’ in result:
JSON Python
# An error occurred; raise an
object dict exception
array list raise YahooSearchError,
string unicode result[‘Error’]
number (int) int, long
return result[‘ResultSet’]
/dev/disk0s2 300G 175G 124G 59.0 / hfs / import base64, getpass, os, socket, sys,
local socket, traceback
devfs 191K 191K 0 - /dev devfs / import paramiko
none import interactive
# setup logging
Accessing Secure Shell (SSH) services paramiko.util.log_to_file(‘demo_simple.
SSH (Secure Shell) is a modern replacement for an log’)
old remote shell system called Telnet. It allows data to # get hostname
be exchanged using a secure channel between two username = ‘’
networked devices. System administrators frequently if len(sys.argv) > 1:
use SSH to administrate networked systems. In hostname = sys.argv[1]
addition to providing remote shell, SSH is also used if hostname.find(‘@’) >= 0:
for secure file transfer (using SSH File Transfer Protocol, username, hostname = hostname.
or SFTP) and remote X server forwarding (allows split(‘@’)
you to use SSH clients as X server). In this section we else:
will learn how to use the SSH protocol from Python hostname = raw_input(‘Hostname: ‘)
using a Python module called paramiko, which if len(hostname) == 0:
implements the SSH2 protocol for Python. print ‘*** Hostname required.’
paramiko can be installed using the following steps: sys.exit(1)
port = 22
$ git clone https://github.com/robey/ if hostname.find(‘:’) >= 0:
paramiko.git hostname, portstr = hostname.
$ cd paramiko split(‘:’)
$ sudo python setup.py install port = int(portstr)
# get username
To the core of paramiko is the SSHClient class. This if username == ‘’:
class wraps L{Transport}, L{Channel}, and L{SFTPClient} default_username = getpass.getuser()
to handle most of the aspects of SSH. You can use username = raw_input(‘Username [%s]:
SSHClient as: ‘ % default_username)
if len(username) == 0:
client = SSHClient() username = default_username
client.load_system_host_keys() password = getpass.getpass(‘Password for
client.connect(‘some.host.com’) %s@%s: ‘ % (username, hostname))
stdin, stdout, stderr = client.exec_ # now, connect and use paramiko Client
command(‘dir’) to negotiate SSH2 across the connection
try:
The following example demonstrates a full SSH client client = paramiko.SSHClient()
written using the paramiko module. client.load_system_host_keys()
client.set_missing_host_key_
@code: PySSHClient.py policy(paramiko.WarningPolicy)
69
Work with Python Python for system administrators
To run this code you will also need a custom Python kunal@ubuntu-vm-kdeo:~/.ssh$ ssh
class interactive.py which implements the interactive luduser@192.168.1.2
shell for the SSH session. Look for this file on FileSilo The authenticity of host ‘192.168.1.2
and copy it into the same folder where you have (192.168.1.2)’ can’t be established.
created PySSHClient.py . RSA key fingerprint is be:01:76:6a:b9:bb:6
9:64:e3:dc:37:00:a4:36:33:d1.
@code_Output Are you sure you want to continue
kunal@ubuntu-vm-kdeo:~/src/paramiko/ connecting (yes/no)? yes
demos$ python demo_simple.py Warning: Permanently added ‘192.168.1.2’
Hostname: 192.168.1.2 (RSA) to the list of known hosts.
Username [kunal]: luduser
Password for luduser@192.168.1.2: So now you’ve seen just how easy it can be to carry
*** Connecting... out the complex sysadmin tasks using Python’s
<paramiko.Transport at 0xb76201acL versatile language.
(cipher aes128-ctr, 128 bits) (active; 1 As is the case with all Python coding, the code that
open channel(s))> is presented here can fairly easily be adopted into
*** SSH Server Connected! *** your GUI application (using software such as PyGTK
Last login: Thu Jan 13 02:01:06 2011 or PyQt) or a web application (using a framework
from 192.168.1.9 such as Django or Grok).
70
Python for system administrators Work with Python
def main(entry_value=’1’,kernels=[]): Start the tool using the sudo command (as it reads the grub.
try: conf file)
(default_value, entry_value,
kernels)=readBootDB() $ sudo grub_tui.py
except:
print >> sys.stderr, (“Error reading /boot/
grub/grub.conf.”)
sys.exit(10)
screen=SnackScreen()
while True:
g=GridForm(screen, (“Boot configuration”),1,5)
if len(kernels)>0 :
li=Listbox(height=len(kernels), width=20,
returnExit=1)
for i, x in enumerate(kernels):
li.append(x,i)
g.add(li, 0, 0)
li.setCurrent(default_value)
e=Entry(3, str(entry_value))
l=Label((“Timeout (in seconds):”))
71
Work with Python Scrape Wikipedia with Beautiful Soup
Beautiful Soup
Use the Beautiful Soup Python library to parse
Wikipedia’s HTML and store it for offline reading
In this tutorial we’ll use the popular Python library Beautiful Soup to
scrape Wikipedia for links to articles and then save those pages for offline
reading. This is ideal for when travelling or in a location with a poor
internet connection.
The plan is simple: using Beautiful Soup with the HTML5Lib Parser,
we’re going to load a Wikipedia page, remove all of the GUI and
unrelated content, search the content for links to other Wikipedia articles
and then, after a tiny bit of modification, write them to a file.
Even though it’s now the de facto knowledge base of the world,
Wikipedia isn’t great when it comes to DOM consistency – that is, IDs and
classes are sometimes quite loose in their usage. Because of this, we will
also cover how to handle all of the excess bits and bobs of the Wikipedia
GUI that we don’t need, as well as the various erroneous links that won’t
be of much use to us. You can find the CSS stylings sheet and a Python
script pertaining to this tutorial at http://bit.ly/19MibBv.
atexit.register(cleanUp)
def isValidLink(link):
if “/wiki/” in link and “:” not in link and “http://” not in link and “wikibooks”
not in link and “#” not in link and “wikiquote” not in link and “wiktionary” not in
link and “wikiversity” not in link and “wikivoyage” not in link and “wikisource” not
in link and “wikinews” not in link and “wikiversity” not in link and “wikidata” not
in link:
return True
else:
return False
04
opener = urllib2.build_opener()
opener.addheaders = [(‘User-agent’, ‘Mozilla/5.0’)]
req = opener.open(URL)
73
Work with Python Scrape Wikipedia with Beautiful Soup
03 In the first few lines of this function, we’re just creating a helper statement.
Afterwards, we’re parsing any arguments passed into the program on its
execution and looking for a -URL flag and a -levels flag. The -levels flag is optional as
we already have a preset depth that we’ll follow the links to, but we need a link to
start from so if the -URL flag is missing, we’ll prompt the user and exit. If we have a link,
then we quickly check whether or not we have a directory to store files in – which
we’ll create if we don’t – and then we’ll fire off the function to get that page. Finally, we
register a handler for when the script tries to exit. We’ll get to that bit later.
04 Here we’re using URLLib2 to request the page the the user has asked for
and then, once we’ve received that page, we’re going to pass the content
through to Beautiful Soup with the soup variable. This gives us access to the
methods we’re going to call as we parse the document.
05 Wikipedia has a lot of nodes that we don’t want to parse. The content
variable allows us to straight away ignore most of Wikipedia’s GUI, but
there are still lots of elements that we don’t want to parse. We remedy this by
iterating through the list ‘undesirables’ that we created earlier on in the document.
For each different div/section/node that we don’t want, we call Beautiful Soup’s
find_all() method and use the extract() method to remove that node from the
document. At the end of the undesirables loop, most of the content we don’t
want any more will be gone. We also look for the ‘also’ element in the Wiki page.
Generally, everything after this div is of no use to us. By calling the find_all_next()
method on the also node, we can get a list of every other element we can
remove from that point on.
page = req.read()
req.close()
content = soup.find(id=”mw-content-text”)
if hasattr(content, ‘find_all’):
4 Get the page
global undesirables
Here we grab the
page we want to for notWanted in undesirables:
store and remove 04
the bits of the removal = content.find_all(notWanted[‘element’], notWanted[‘attr’])
if len(removal) > 0:
document we
for el in removal:
don’t need el.extract()
Styling
also = content.find(id=”See_also”)
Currently, the HTML page will use the
if(also != None): built-in browser styles when rendering the
also.extract() page. If you like, you can include the style
tail = also.find_all_next() sheet included in the tutorial resources
if(len(tail) > 0): to make it look a little nicer. To use it, you
for element in tail:
can minify the script and include it inside
element.extract()
a <style> tag in the head string on line
for link in content.find_all(‘a’): 102, or you can rewrite the head string to
something like:
href = link[“href”]
head = “<head><meta
5 Check links if isValidLink(href): charset=\”UTF-8\” /><title>” +
Then we iterate fileName + “</title><style>” +
through all of the if level < maxLevel: str(open(“/PATH/TO/STYLES”, ‘r’).
<a> tags and check read()) + “</style></head>”
stored = False;
if there’s a valid link
05 for addr in addresses:
to another page if addr == link.get(“href”):
we can grab, and stored = True
tweak them for our
own use if(stored == False):
title = link.get(‘href’).replace(“/wiki/”, “”)
addresses.append(str(title + “.html”))
grabPage(“http://en.wikipedia.org” + link.get(‘href’), level +
1, title)
print title
fileName = str(name)
06 if level == maxLevel:
deepestAddresses.append(fileName.replace(‘/’, ‘_’) + “.html”)
75
Work with Python Scrape Wikipedia with Beautiful Soup
Writing to file
07 Now we create a file to store the newly parsed document in for later
reading. We change any ‘/’ in the filename to ‘_’ so the script doesn’t
try and write to a random folder. We also do a quick check to see how many
links we’ve followed since the first page. If it’s the max level, we’ll add it to the
deepestAddresses list. We’ll use this a little bit later.
76
Scrape Wikipedia with Beautiful Soup Work with Python
08 After our script has iterated through every link on every page to the
maximum level of depth that it can, it will try to exit. On line 34 of the
code (on the disc and online) in the init function, we registered the function
cleanUp to execute on the program trying to exit; cleanUp’s job is to go through
the documents that we’ve downloaded and check that every link we’ve left in
the pages does in fact link to a file that we have available. If it can’t match the link
in the href to a file in the addresses list, it will remove it. Once we’re done, we will
have a fully portable chunk of Wikipedia we can take with us.
def cleanUp():
print(“Complete”)
8 Initialise
This is how we will
initialise our script 08 if __name__ == “__main__”:
init()
77
Create with Python Have fun with programming
78
Have fun with programming Create with Python
If you have any problems with pip, you can use easy_install via easy_
install kivy.
There are also packages or repositories available for several popular
distros. You can find more information on Kivy’s website. A kivy
application is started by instantiating and running an ‘App’ class. This is
what initialises our pp’s window, interfaces with the OS, and provides an
80
Build tic-tac-toe with Kivy Create with Python
class TicTacToeApp(App):
pass
if __name__ == “__main__”:
TicTacToeApp().run()
You can already run this, your app will start up and
you’ll get a plain black window. Exciting! Above The game with final additions, making the grid square and
extending the interface
We can build our own GUI out of Kivy widgets.
Each is a simple graphics element with some
specific behaviour of its own ranging from def build(self):
standard GUI functionality (eg the Button, Label return Label(text=’Hello World!’,
or TextInput), to those that impose positioning on font_size=100,
their child widgets (eg the BoxLayout, FloatLayout color=0, 1, 0, 1)) # (r, g, b, a)
or GridLayout), to those abstracting a more
involved task like interacting with hardware (eg The ‘build’ method is called when the ‘App’ is run,
the FileChooser, Camera or VideoPlayer). Most and whatever widget is returned automatically
importantly, Kivy’s widgets are designed to be easily becomes the root widget of that App’. In our case
combined - rather than including a widget for every that’s a Label, and we’ve set several properties - the
need imaginable, widgets are kept simple but are ‘text’, ‘font_size’ and ‘color’. All widgets have different
easy to join to invent new interfaces. We’ll see some properties controlling aspects of their behaviour,
of that in this tutorial. which can be dynamically updated to alter their
Since ‘Hello World!’ is basically compulsory in any appearance later, though here we set them just once
programming tutorial, let’s get it over with by using a upon instantiation.
simple ‘Label’ widget to display the text: Note that these properties are not just Python
attributes but instead Kivy properties. These are
from kivy.uix.label import Label accessed like normal attributes but provide extra
functionality by hooking into Kivy’s event system.
We’ll display the ‘Label’ by returning it as our app’s We’ll see examples of creating properties shortly,
root widget. Every app has a single root widget, the and you should do the same if you want to use your
top level of its widget tree, and it will automatically variables with Kivy’s event or binding functionality.
be sized to fill the window. We’ll see later how to That’s all you need to show some simple text, so
construct a full GUI by adding more widgets for this run the program again to check that this does work.
one, but for now it’s enough to set the root widget You can experiment with the parameters if it’s unclear
by adding a new method to the ‘App’: what any of them are doing.
81
Create with Python Build tic-tac-toe with Kivy
Our own widget: tic-tac-toe child widgets. This example demonstrates the
Since Kivy doesn’t have a tic-tac-toe widget, we’ll have former, creating a rule for the ‘TicTacToeGrid’ widget
to make our own! It’s natural to create a new widget by declaring that every ‘TicTacToeGrid’ instantiated
class to contain this behaviour: should have its ‘cols’ property set to 3.
We’ll use some more kv language features later, but
from kivy.uix.gridlayout import GridLayout for now let’s go back to Python to create the buttons
class TicTacToeGrid(GridLayout): that will be the entries in our tic-tac-toe grid.
pass
from kivy.uix.button import Button
Now this obviously doesn’t do anything yet, from kivy.properties import ListProperty
except that it inherits all the behaviour of the Kivy
GridLayout widget - that is, we’ll need to tell it how class GridEntry(Button):
many columns to have, but then it will automatically coords = ListProperty([0, 0])
arrange any child widgets to fit nicely with as many
rows as necessary. Tic-tac-toe requires three columns This inherits from Kivy’s ‘Button’ widget, which
and nine children. interacts with mouse or touch input, dispatching
Here we introduce the Kivy language (kv), a events when interactions toggle it. We can hook
special domain-specific language for making into these events to call our own functions when
rules describing Kivy widget trees. It’s very simple a user presses the button, and can set the button’s
but removes a lot of necessary boilerplate for ‘text’ property to display the ‘X’ or ‘O’. We also created
manipulating the GUI with Python code - as a loose a new Kivy property for our widget, ‘coords’ – we’ll
analogy you might think of it as the HTML/CSS to show how this is useful later on. It’s almost identical
Python’s JavaScript. Python gives us the dynamic to making a normal Python attribute by writing ‘self.
power to do anything, but all that power gets in the coords = [0, 0]’ in ‘GridEntry.__init__’.
way if we just want to declare the basic structure As with the ‘TicTacToeGrid’, we’ll style our new class
of our GUI. Note that you never need kv language, with kv language, but this time we get to see a more
you can always do the same thing in Python alone, interesting feature.
but the rest of the example may show why Kivy
programmers usually like to use kv. <GridEntry>:
Kivy comes with all the tools needed to use kv font_size: self.height
language; the simplest way is to write it in a file with
a name based on our App class. That is, we should As before, this syntax defines a rule for how a
place the following in a file named ‘tictactoe.kv’: ‘GridEntry’ widget should be constructed, this time
setting the ‘font_size’ property that controls the size
<TicTacToeGrid>: of the text in the button’s label. The extra magic is
cols: 3 that kv language automatically detects that we’ve
referenced the Button’s own height and will create
This is the basic syntax of kv language; for each a binding to update this relationship – when a
widget type we may write a rule defining its ‘GridEntry’ widget’s height changes, its ‘font_size’
behaviour, including setting its properties and adding will change so the text fits perfectly. We could have
82
Build tic-tac-toe with Kivy Create with Python
made these bindings straight from Python (another display them and knows it should automatically
usage of the ‘bind’ method used later on), but that’s arrange them into a grid with the number of
rarely as convenient as referencing the property we columns we set earlier.
want to bind to. Now all we have to do is replace our root widget
Let’s now populate our ‘TicTacToeGrid’ with (returned from ‘App.build’) with a ‘TicTacToeGrid’ and
‘GridEntry’ widgets. we can see what our app looks like.
You can run your app again to see exactly what this This covers the basic detection of a won or drawn
did, and you’ll find that clicking each button now board, but it only prints the result to stdout. At this
places an ‘O’ or ‘X’ as well as a coloured background stage we probably want to reset the board so that
depending on whose turn it is to play. Not only that, the players can try again, along with displaying a
but you can only play one move in each button graphical indicator of the result.
thanks to our status array that keeps track of the
existing moves. def reset(self, *args):
This is enough to play the game but there’s one self.status = [0 for _ in range(9)]
vital element missing... a big pop-up telling you when
you’ve won! Before we can do that, we need to add for child in self.children:
some code to check if the game is over. child.text = ‘’
Kivy properties have another useful feature child.background_color = (1, 1, 1, 1)
here, whenever they change they automatically
call an ‘on_propertyname’ method if it exists and self.current_player = 1
dispatch a corresponding event in Kivy’s event
system. That makes it very easy to write code that Finally, we can modify the `on_status` method to
will run when a property changes, both in Python both reset the board and display the winner
and kv language. In our case we can use it to in a ‘ModalView’ widget.
check the status list every time it is updated, doing
something special if a player has filled a column, from kivy.uix.modalview import ModalView
row or diagonal.
84
Build tic-tac-toe with Kivy Create with Python
winner = None
if -3 in sums:
winner = ‘Xs win!’
elif 3 in sums:
winner = ‘Os win!’
elif 0 not in self.status:
winner = ‘Draw...nobody wins!’
Above A tic-tac-toe grid now accepting input, adding in an O or X
alternately, each go
if winner:
popup = ModalView(size_hint=0.75, 0.5))
victory_label = Label(text=winner, Time to experiment
font_size=50) This has been a quick tour through some of Kivy’s
popup.add_widget(victory_label) features, but hopefully it demonstrates how to think
popup.bind(on_dismiss=self.reset) about building a Kivy application. Our programs
popup.open() are built from individual Kivy widgets, interacting
by having Python code run when their properties
This mostly uses the same ideas we already covered, change (eg our ‘on_status’ method) or when they
adding the ‘Label’ widget to the ‘ModalView’ then dispatch events (eg ‘Button’ ‘on_release’). We also
letting the ‘ModalView’ take care of drawing itself briefly saw kv language and experienced how it can
and its children on top of everything else. We also automatically create bindings between properties.
use another binding; this time to ‘on_dismiss’, which You can find a copy of the full program on FileSilo,
is an event dispatched by the ‘ModalView’ when reference this to check you’ve followed everything
it is closed. Finally, we made use of the ‘size_hint’ correctly. We’ve also added an extra widget, the
property common to all widgets, which in this case ‘Interface’, with a structure coded entirely in kv
is used to set the ‘ModalView’ size proportional to language that demonstrates how to add child
the window – while a ‘ModalView’ is open you can widgets. Test it by uncommenting the ‘return
resize the window to see it dynamically resize, always Interface()’ line in ‘TicTacToeGrid.build’. It doesn’t
maintaining these proportions. This is another trick do anything fundamentally different to what we
made possible by a binding with the ‘size_hint’ Kivy already covered, but it does make extensive use of
property, this time managed internally by Kivy. kv language’s binding ability to automatically update
That’s it, a finished program! We can now not only a label showing the current player, and to resize the
play tic-tac-toe, but our program automatically tells TicTacToeGrid so it is always square to fit within its
us when somebody has won, and resets the board parent. You can play with the settings to see how it
so we can play again. Simply run your program and fits together, or try swapping out the different widget
enjoy hours of fun! types to see how other widgets behave.
85
Create with Python Make a Pong clone with Python
SimpleGUITk
https://github.com/dholm/simpleguitk/
clone with
Python
We update the retro classic Pong for the Linux
generation with a new library called SimpleGUITk
Below ‘Tux for Two’ is a great little
Pong clone using the beloved Linux
mascot, Tux, in the centre of the action
The Raspberry Pi is a fantastic way to start learning how to code.
One area that can be very rewarding for amateur coders is game
programming, allowing for a more interactive result and a greater sense
of accomplishment. Game programming can also teach improvisation
and advanced mathematics skills for code. We’ll be using the fantastic
SimpleGUITk module in Python, a very straightforward way of creating
graphical interfaces based on Tkinter.
01 Head to the websites we’ve listed in ‘What you’ll need’ and download a zip of
the source files from the GitHub pages. Update your Raspbian packages and
then install the following:
05 The important parts in the
draw function are the draw_
line, draw_image and draw_text
$ sudo apt-get install python-dev python-setuptools tk8.5-dev functions. These are specifically from
tcl8.5-dev SimpleGUI, and allow you to easily put
these objects on the screen with a
Install the modules Write your code position, size and colour. You need to
tie them to an object, though – in this
case, canvas. This tells the software
02 Open the terminal and use cd
to move to the extracted Pillow
folder. Once there, type:
03 Launch IDLE 2, rather than IDLE 3,
and open a new window. Use the
code listing to create our game ‘Tux for
that we want to put these items on
the screen for people to see.
$ sudo python setup.py install Two’. Be careful to follow along with the
Once that’s complete, move to the code to make sure you know what you’re SimpleGUI setup code
simpleguitk folder and use the same doing. This way, you can make your own
command to install that as well. changes to the game rules if you wish.
04 There’s nothing too groundbreaking to start the code: Tux’s and the paddles’
initial positions are set, along with the initial speed and direction of Tux. These
are also used when a point is won and the playing field is reset. The direction and
to work in. The frame is then told what
functions handle the graphics, key
functions etc. Finally, we give it frame.
speed is set to random for each spawn. start() so it starts.
86
Make a Pong clone with Python Create with Python
87
Create with Python Program a Space Invaders clone
Pygame
www.pygame.org/docs
Invaders clone
Write your own RasPi shooter in 300 lines of Python
When you’re learning to program in a new language or trying to master
a new module, experimenting with a familiar and relatively simply
project is a very useful exercise to help expand your understanding of
the tools you’re using. Our Space Invaders clone is one such example
that lends itself perfectly to Python and the Pygame module – it’s a
simple game with almost universally understood rules and logic.
We’ve tried to use many features of Pygame, which is designed to
make the creation of games and interactive applications easier. We’ve
Did you know… extensively used the Sprite class, which saves dozens of lines of extra
Space Invaders was one of the
code in making collision detection simple and updating the screen and
biggest arcade hits in the world. its many actors a single-line command.
It’s a great first game since
everyone knows how to play!
Have fun with the project and make sure you tweak and change
things to make it your own!
Right Pivaders is
a Space Invaders
clone we’ve made
especially for the Pi
88
Program a Space Invaders clone Create with Python
89
Continued on page 91
Create with Python Program a Space Invaders clone
03 With Pygame installed and the project cloned to your machine (you can also
find the .zip on this issue’s cover DVD – simply unpack it and copy it to your
home directory to use it), you can take it for a quick test drive to make sure everything’s
06 A class is essentially a
blueprint for an object you’d
like to make. In the case of our player,
set up properly. All you need to do is type python pivaders.py from within the it contains all the required info, from
pivaders directory in the terminal to get started. You can start the game with the which you can make multiple copies
space bar, shoot with the same button and simply use the left and right arrows on (we create a player instance in the
your keyboard to move your ship left and right. make_player() method halfway
through the project). The great thing
about the classes in Pivaders is that
Creating your own clone they inherit lots of capabilities and
shortcuts from Pygame’s Sprite class,
04 Once you’ve racked up a good high score (anything over 2,000 points is
respectable) and got to know our simple implementation, you’ll get more
from following along with and exploring the code and our brief explanations of
as denoted by the pygame.sprite.
Sprite found within the braces of the
first line of the class. You can read
what’s going on. For those who want to make their own project, create a new the docs to learn more about the
project folder and use either IDLE or Leafpad (or perhaps install Geany) to create Sprite class via
and save a .py file of your own. www.pygame.org/docs/ref/sprite.html.
91 Continued on page 93
Create with Python Program a Space Invaders clone
09 Our final class is called Game. This is where all the main functionality of
the game itself comes in, but remember, so far this is still just a list of
ingredients – nothing can actually happen until a ‘Game’ object is created (right
screen. On the other hand, we also
need to check to see if we’ve killed all
the aliens, from within win_round().
at the bottom of the code). The Game class is where the central mass of the Assuming we’re not dead, but the
game resides, so we initialise Pygame, set the imagery for our protagonist and aliens are, we know we can call the
extraterrestrial antagonist and create some GameState attributes that we use to next_round() method, which creates
control key aspects of external classes, like changing the player’s vector (direction). a fresh batch of aliens and increases
their speed around the screen. Finally,
The main loop we refresh the screen so everything
that’s been moved, shot or killed can
10 There are a lot of methods (class functions) in the Game class, and each is
designed to control a particular aspect of either setting up the game or
the gameplay itself. The logic that dictates what happens within any one round
be updated or removed from the
screen. Remember, the main loop
happens 20 times a second – so the
of the game is contained in the main_loop() method right at the bottom of the fact we don’t call for the screen to
pivaders.py script and is the key to unlocking exactly what variables and functions update right at the end of the loop is
you need for your game. of no consequence.
92
Program a Space Invaders clone Create with Python
Continued from page 91
missile.vector = 1 self.refresh_screen()
missile.rect.x = shooter.rect.x + 15 pygame.time.delay(3000)
missile.rect.y = shooter.rect.y + 40 return True
missile.speed = 10
self.missile_group.add(missile) def calc_collisions(self):
self.all_sprite_list.add(missile) pygame.sprite.groupcollide(
self.missile_group, self.barrier_group,
def make_barrier(self, columns, rows, spacer): True, True)
for column in range(columns): pygame.sprite.groupcollide(
for row in range(rows): self.bullet_group, self.barrier_group,
barrier = Block(WHITE, (BLOCK_SIZE)) True, True)
barrier.rect.x = 55 + (200 * spacer) if pygame.sprite.groupcollide(
+ (row * 10) self.bullet_group, self.alien_group,
barrier.rect.y = 450 + (column * 10) True, True):
self.barrier_group.add(barrier) self.score += 10
self.all_sprite_list.add(barrier) if pygame.sprite.groupcollide(
self.player_group, self.missile_group,
def make_defenses(self): False, True):
for spacing, spacing in self.lives -= 1
enumerate(xrange(4)):
self.make_barrier(3, 9, spacing) def next_round(self):
for actor in [self.missile_group,
def kill_all(self): self.barrier_group, self.bullet_group]:
for items in [self.bullet_group, self. for i in actor:
player_group, i.kill()
self.alien_group, self.missile_group, self.alien_wave(self.level_up)
self.barrier_group]: self.make_defenses()
for i in items: self.level_up += 50
i.kill()
def main_loop(self):
def is_dead(self): while not GameState.end_game:
if self.lives < 0: while not GameState.start_screen:
self.screen.blit(self.game_font.render( GameState.game_time = pygame.time.
“The war is lost! You scored: “ + str( get_ticks()
self.score), 1, RED), (250, 15)) GameState.alien_time = pygame.time.
self.rounds_won = 0 get_ticks()
self.refresh_screen() self.control()
pygame.time.delay(3000) self.make_missile()
return True for actor in [self.player_group,
self.bullet_group,
def win_round(self): self.alien_group, self.missile_group]:
if len(self.alien_group) < 1: for i in actor:
self.rounds_won += 1 i.update()
self.screen.blit(self.game_font.render( if GameState.shoot_bullet:
“You won round “ + str(self.rounds_won) + self.make_bullet()
“ but the battle rages on”, 1, RED), self.calc_collisions()
(200, 15)) if self.is_dead() or self.defenses_
self.refresh_screen() breached():
pygame.time.delay(3000) GameState.start_screen = True
return True if self.win_round():
self.next_round()
def defenses_breached(self): self.refresh_screen()
for alien in self.alien_group: self.splash_screen()
if alien.rect.y > 410: pygame.quit()
self.screen.blit(self.game_font.render(
“The aliens have breached Earth if __name__ == ‘__main__’:
defenses!”, pv = Game()
1, RED), (180, 15)) pv.main_loop()
93
Create with Python Pivaders part 2: graphics and sound
Pygame
www.pygame.org/docs
Art assets
graphics & sound
opengameart.org This time we’ll expand our Space Invaders clone to
include immersive animation and sound
We had great fun creating our basic Space Invaders clone, Pivaders,
in the previous guide. Pygame’s ability to group, manage and detect
collisions thanks to the Sprite class really made a great difference to
our project, not just in terms of code length, but in simplicity too. If
you missed the first part of the project, you can find the v0.1 code
listing on GitHub via git.io/cBVTBg, while you can find version v0.2
of the code, including all the images, music and sound effects we’ve
used at git.io/8QsK-w.
To help keep our project code manageable and straightforward
(as your projects grow keeping your code easy to follow becomes
increasingly harder) we integrated a few animation methods into
Did you know… our Game class and opted to use a sprite sheet. Not only does it
make it very easy to draw to the screen, but it also keeps the asset
Space Invaders is one of
the most cloned games in the count under control and keeps performance levels up, which is
world! It makes a great first especially important for the Raspberry Pi. We hope you have fun
project for game programmers.
using our techniques to add animation and sound to your projects!
94
Pivaders part 2: graphics and sound Create with Python
95
Continued on page 96
Create with Python Pivaders part 2: graphics and sound
def control(self):
player looks on screen by changing for event in pygame.event.get():
Player.image. First, we need to load our if event.type == pygame.QUIT:
ship sprite sheet with pygame.image. GameState.start_screen = False
load(). Since we made our sheet with GameState.end_game = True
a transparent background, we can if event.type == pygame.KEYDOWN \
append .convert_alpha() to the end
and event.key == pygame.K_ESCAPE:
if GameState.start_screen:
of the line so the ship frames render GameState.start_screen = False
correctly (without any background). We GameState.end_game = True
then use subsurface to set the initial self.kill_all()
Player.image to the middle ship sprite else:
on the sheet. This is set by self.ani_pos, GameState.start_screen = True
which has an initial value of 5. Changing self.keys = pygame.key.get_pressed()
this value will alter the ship image if self.keys[pygame.K_LEFT]:
drawn to the screen: ‘0’ would draw it
GameState.vector = -1
self.animate_left = True
leaning fully left, ‘11’ fully to the right. self.animate_right = False
elif self.keys[pygame.K_RIGHT]:
Animation flags GameState.vector = 1
self.animate_right = True
self.animate_left = False
08 Slightly further down the list
in the initialising code for the
Game class, we also set two flags for
else:
GameState.vector = 0
self.animate_right = False
our player animation: self.animate_left self.animate_left = False
and self.animate_right. As you’ll see in
the Control method of our Game class, if self.keys[pygame.K_SPACE]:
we use these to ‘flag’ when we want if GameState.start_screen:
animations to happen with True and GameState.start_screen = False
False. It also allows us to ‘automatically’ self.lives = 2
self.score = 0
animate the player sprite back to its self.make_player()
natural resting state (otherwise the self.make_defenses()
ship will continue to look as if it’s flying self.alien_wave(0)
left when it has stopped). else:
GameState.shoot_bullet = True
self.bullet_fx.play()
The animation method
def animate_player(self):
96
Pivaders part 2: graphics and sound Create with Python
def alien_explosion(self):
11 Pygame makes it easy to add a
musical score to a project. Just
obtain a suitable piece of music in
if self.alien_explode:
if self.alien_explode_pos < 9: your preferred format (we found ours
self.alien_explode_graphics = self.alien_ via freemusicarchive.org) and load it
explosion_ sheet.subsurface(0, self.alien_explode_pos*96, 94, using the Mixer Pygame class. As it’s
96) already been initialised via pygame.
self.alien_explode_pos += 1 init(), we can go ahead and load the
self.screen.blit(self.alien_explode_graphics, music. The music.play(-1) requests
[int(self. explodey_alien[0]) - 50 , int(self.explodey_alien[1]) - that the music should start with the
60])
app and continue to loop until it quits.
else:
self.alien_explode = False If we replaced -1 with 5, the music
self.alien_explode_pos = 0 would loop five times before ending.
self.explodey_alien = [] Learn more about the Mixer class via
www.pygame.org/docs/ref/
def splash_screen(self): mixer.html.
while GameState.start_screen:
self.kill_all()
self.screen.blit(self.intro_screen, [0, 0]) Using sound effects
self.screen.blit(self.intro_font.render(
“PIVADERS”, 1, WHITE), (265, 120))
self.screen.blit(self.game_font.render(
“PRESS SPACE TO PLAY”, 1, WHITE), (274, 191))
12 Loading and using sounds
is similar to how we do so
for images in Pygame. First we load
pygame.display.flip()
self.control() the sound effect using a simple
self.clock.tick(self.refresh_rate / 2) assignment. For the laser beam, the
initialisation looks like this:
def make_player(self): self.bullet_fx = pygame.
self.player = Player() mixer.Sound(‘location/of/file’)
Find the rest of the code at github.com/russb78/pivaders Then we simply trigger the sound
effect at the appropriate time. In the
case of the laser, we want it to play
“Sprite sheets make it easy to draw to the whenever we press the space bar
to shoot, so we place it in the Game
screen, but it also keeps the asset count class’s Control method, straight
down and performance levels up” after we raise the shoot_bullet
flag. You can get different sounds
from www.freesound.org.
97
Create with Python Make a visual novel game
98
Make a visual novel game Create with Python
$ hg clone https://bitbucket.
X. The rest of the tutorial will work in
any OS.
06 For the moment the
script file is small and
literally just holds the script for
org/pygame/pygame
the game. It’s made up of events
Which will download it to the folder for the visual novel to move
‘pygame’. Move to that using CD between, line by line, by splitting
pygame in the terminal so we can it up into scenes. This includes
continue building it. the location of each line, the
character, the actual line itself
and information on how the
Build the Pygame module game flows. These are matrices
with the information in, and are
03 To install it, we need to do it in two
steps. First we need to prepare the
code to install using the terminal with:
Get the visual novel files completely customisable.
99
Create with Python Make a visual novel game
100
Make a visual novel game Create with Python
101
Use Python with Pi Create amazing projects
102
Create amazing projects Use Python with Pi
103
Use Python with Pi Using Python on Raspberry Pi
t Basic arithmetic
t Comparison operators, for example ‘equal to’ and ‘not equal to’
t Control structures, for example loops and if statements
Staying organised
01 We don’t want to have messy folders on our new Pi, so let’s go to the file
manager and organise ourselves. Open the file manager by clicking the icon
next to the menu icon on the bottom left of the screen. Create a new folder by
right-clicking and selecting New>Folder, then type a name and click OK. We created
a folder called Python, and inside that created a folder called Hello World v2.
104
Using Python on Raspberry Pi Use Python with Pi
Starting Geany
02 Start Geany by going to the LXDE menu and going to Programs. From
here, select Geany. Once you’re in the Geany interface, create a new
Python file from a template by selecting ‘New (with template)>main.py’. Delete
everything in this template apart from the first line: #!/usr/bin/env python. This
line is important because it means you can run the code from the command line
and the Bash shell will know to open it with the Python interpreter.
105
Use Python with Pi Programming in Python on the Raspberry Pi
Setting it up
“It’s a good habit to be well organised
04 Having detailed comments
in your code is important
because it allows you to note down
when programming”
things you find confusing and
document complex procedures. If
another programmer has to work Variables
with your code in the future, they’ll
be extremely grateful. Start by adding
a comment with a description of
what the program will do and your
05 A variable is data that is stored in memory and can be accessed via a
name. Our program is going to start by asking for your first name, store
that in a variable and then print out a welcome message. We’re going to add a
name. All comment lines start with comment that explains this and create a variable called firstName. Notice how
a hash (#) and are not interpreted we’ve capitalised the first letter of the second word to make it easier to read.
as code by the Python interpreter. We want the firstName variable to hold the value returned by a function
We import the sys library so we can called raw_input, that will ask the user for input. The question is passed into the
use the sys.exit function to close the print function within brackets, and because this is a string it is enclosed within
program later on. We also import quotation marks. A string type is basically a collection of characters. Note the extra
everything from the decimal library space we’ve added after the colon because the user types their input straight
because we want to make use of the after this question.
decimal type.
Printing a message
106
Programming in Python on the Raspberry Pi Use Python with Pi
08 Now we’ve done that part, why not test it? It’s worth noting that you have
to save before running the program, or anything you’ve done since you
last saved won’t be interpreted by Python. Run the program by pressing the F5
key. Input your name by typing it and then pressing the Enter key. Once you have
done this, you’ll see a welcome message. If the program exits with the code 0
Fixing a small issue then everything was run successfully. Press Enter to close the terminal.
107
Use Python with Pi Programming in Python on the Raspberry Pi
Performing arithmetic
10 The main arithmetic operators in Python are + - / *, the latter two being
divide and multiply respectively. We’ve created three new variables
called numberHalved, numberDoubled and numberSquared. Notice that we
don’t need to specify that they should be decimal because Python gives a
type to its variables from the type of their initial value. The number variable is a
decimal type, so all values returned from performing arithmetic on that number
will also be of a decimal type.
11 Now that we have performed our arithmetic, we need to print the results
using the print function. The print function only accepts string values
passed to it. This means that we need to convert each decimal value to a string
using the str() function before they can be printed. We’re using a print statement
with nothing between the quotation marks to print one blank line. This works
because the print function always adds a new line at the end of its output unless
told otherwise, so printing an empty string just prints a new line.
Below The Raspberry Pi takes the ‘Pi’ part
of its name from its compatibility with the
Python programming language
108
Programming in Python on the Raspberry Pi Use Python with Pi
Incrementing numbers
with a loop
109
Use Python with Pi Send an SMS from your Pi
110
Send an SMS from your Pi Use Python with Pi
01 The first step of this project is to register for a Twilio account and Twilio
number. This is free and will enable you to send an SMS to a registered,
verified phone. Once signed up, you will receive a verification code via SMS to the
registered phone. When prompted, enter this onto the Twilio site to authenticate
your account and phone. Go to twilio.com/try-twilio and create your account.
02 Your Twilio account is a trial account (unless you pay the upgrade fee),
which means you can only send and receive communications from a
validated phone number. Enter the phone number of the mobile that you want
to verify, ensuring that you select the correct country code. Twilio will text you a
verification code. Enter this code into the website form and press submit.
The dashboard
03 Once registered and logged in, visit the dashboard page, which will display
your AccountSid and your Auth Token. These are both required to use the
Twilio REST. Keep these secure and private, but be sure to make a note of them as you
will need them for your Python program later.
111
Use Python with Pi Send an SMS from your Pi
05 Now you are ready to create the SMS program that will send the text
message to your mobile phone. Open your Python editor and import the
Twilio REST libraries (line one, below). Next, add your AccountSid and Auth Token,
replacing the X with yours, as you will find on your dashboard:
112
Send an SMS from your Pi Use Python with Pi
07 To send the message, you need to add the code line below and your
two phone numbers. The first number is your mobile phone number,
which is registered and validated with Twilio (Step 2). The second number is
other communication programs
beyond sending SMS, such as making
phone calls, recording your calls, and
your Twilio account number, which can be retrieved from your dashboard page retrieving data including caller IDs and
under ‘Call the Sandbox number’. Change the Sandbox number to your country call duration.
location and remember to add the international country code. The API also complements a
wide range of other programming
message = client.messages.create(to=“+44YOURMOBNUMBER”, languages, including Ruby, PHP, Java
from_=“+44YOURTWILIONUMBER”, body=message) and Node.js (twilio.com/api).
113
Use Python with Pi Voice synthesizer
We’ve shown how the Raspberry Pi can be used to power all kinds
of projects, but as a tiny computer it can also be the centre of an
Internet of Things in your house too. For these reasons and more,
using the Raspberry Pi for text-to-voice commands could be just
Did you know… what you’re looking for. Due to the Debian base of Raspbian, the
powerful eSpeak library is easily available for anyone looking to
Using eSpeak you can control
the way the words are spoken make use of it. There’s also a module that allows you to use eSpeak
to add emphasis or make the in Python, going beyond the standard command-line prompts so
voice sound different
you can perform automation tasks.
114
Voice synthesizer Use Python with Pi
115
Create with Python Visualise music in Minecraft with the PianoHAT
the PianoHAT
Combine code, Minecraft and the PianoHAT to play
music and create a visualisation of the melody
Pimoroni has created the PianoHAT, the ultimate mini musical
companion for your Raspberry Pi! It is inspired by Zachary Igielman’s
PiPiano and made with his blessing. The HAT consists of a dinky
eight-key piano add-on, with touch-sensitive keys and LEDs.
It can be used for many creative and musical purposes, such
as playing music in Python, controlling software synths on your
Raspberry Pi, taking control of hardware synthesisers, or unlocking
your inner Mozart.
This tutorial will show you how to set up the hardware, introduce
you to the basic features of the software and show you how to
combine these together in Minecraft to create musical blocks and a
visualisation of your melodies. You can view a demonstration video
here: www.youtube.com/watch?v=ezJgXp01MPk
Visualise music in Minecraft with the PianoHAT Create with Python
Minecraft
Musical silence
The new Raspberry Pi OS image comes with Minecraft and the required
06 Python library pre-installed. If you are using an old OS version, it will be worth
04 The program called leds.py is
useful; when you run this and
press a key or note, the corresponding
downloading and updating to either the new Jessie or Raspbian image downloadable
here: https://www.raspberrypi.org/downloads/
LED lights up but the note is not Go to the start menus and load Minecraft from the programming tabs. Be aware
‘sounded’. It demonstrates how you that the Minecraft window is a little glitchy when full size and it is recommended to
can separately control the PianoHAT reduce the size so you can view both your Python code and the game at the same
LEDs and the sounds. You can turn all time. Let’s look at some simple Minecraft hacks that will be used in the final Musical
of the LEDs on or off, which is useful for Blocks program.
creating a visual metronome, prompting
a user which key to press next before a
sound is played. Assuming you are still in
the home/pi/Pimoroni/pianohat folder,
type sudo python leds.py in order to
run the program.
118
Visualise music in Minecraft with the PianoHAT Create with Python
flower = 38
while True:
x, y, z = mc.player getPos()
mc.setBlock(x, y, z, flower)
time.sleep(0.1)
119
Create with Python Visualise music in Minecraft with the PianoHAT
Finding your
13 In step nine you learned how to place a block: use this code to place
the block that corresponds to the channel number you stored in the
previous step. Within the if statement on line 56 under the samples[channel].
positon again play(loops=0), add the code to place a block, mc.setBlock(move, y+3, z+3,
Block_number) This places the block into the Minecraft world.
120
Visualise music in Minecraft with the PianoHAT Create with Python
121
Use Python with Pi Code your own Twitter bot
Twitter bot
Create your very own Twitter bot that can retweet
chunks of wisdom from others
Twitter is a useful way of sharing information with the world and it’s
our favourite method of giving our views quickly and conveniently.
Many millions of people use the microblogging platform from
their computers, mobile devices and possibly even have it on
their televisions.
You don’t need to keep pressing that retweet button, though.
With a sprinkling of Python, you can have your Raspberry Pi do it for
you. Here’s how to create your own Twitter bot…
import sys
package lists using the command
import time
sudo apt-get update. Then install
from datetime import datetime
the Python Package installer using
from twython import Twython
sudo apt-get install python-pip. Once
you’ve done that, run sudo pip install
class bot:
twython to install the Twitter library
def __init__(self, c_key, c_secret, a_token, a_token_
we’ll be using.
secret):
# Create a Twython API instance
Registering your ‘app’ self.api = Twython(c_key, c_secret, a_token,
with Twitter a_token_secret)
122
Code your own Twitter bot Use Python with Pi
constructor. We take the tokens from # Loop through each tweet and check if it was
the previous steps as parameters and # posted since we were last called
use them to create an instance of the for t in timeline:
Twython API. We also have a variable, tweet_time = bot.timestr_to_datetime
last_ran, which is set to the current (t[‘created_at’])
time. This is used to check if there are if tweet_time > self.last_ran:
new tweets later on. print “Retweeting {0}”.format(t[‘id’])
self.api.retweet(id = t[‘id’])
Retweeting a user
if __name__ == “__main__”:
tokens, and then go into an infinite # Retweet anything new by @LinuxUserMag every 5 minutes
loop. In this loop, we check for any while True:
new retweets from the users we are # Update the time after each retweet_task so we’re
monitoring (we could run the retweet # only retweeting new stuff
task with different users), then update twitter.retweet_task(“LinuxUserMag”)
the time everything was last run, and twitter.last_ran = datetime.now()
sleep for five minutes. time.sleep(5 * 60)
123
Use Python with Pi Build your own networked Hi-Fi
124
Build your own networked Hi-Fi Use Python with Pi
125
Use Python with Pi Build your own networked Hi-Fi
cd ~/pyPlaylist
framework. Once configured it will
give us a way of controlling our ./add_stations.sh
Hi-Fi through a web-browser. The
following will install pyPlaylist on Reviewing the stations
Raspbian:
cd ~
t $ mpc ls
git clone https://github.
com/alexellis/pyPlaylist t BBC6Music
cd pyPlaylist t BBCRadio1
./raspbian_install.sh t BBCRadio2
t BBCRadio4
t CapitalXtra
t KissFM
If you want to remove one of the stations then type in the following:
crontab -e
@reboot /usr/bin/
python /home/pi/
pyPlaylist/app.py
126
Build your own networked Hi-Fi Use Python with Pi
07 Now that we have some stations, we can run the web-server from the
pyPlaylist directory. Then open up a web browser to start playing a radio
station. The following command reveals your IP address on Raspbian:
been employed to make the
pages responsive (compatible
with your PC, phone and
tablet). The code has been
released under GPL, so why not
$ ./raspbian_get_ip.sh fork the code and tweak it to
192.168.0.20 your own needs?
http://192.168.0.20:5000/
08 Now put together a sub-directory with your music files under /var/lib/mpd/
music/ and ensure that mpd:audio has access to read it. Then we: update
mpd’s database, clear out the current playlist and add in all the tracks from the new
directory (ambient) finally saving it as a new playlist.
mpc update
mpc clear
mpc ls ambient | mpc add
mpc save ambient station. The following command reveals your IP
address on Raspbian:
$ ./raspbian_get_ip.sh
192.168.0.20
Once you know the IP address, then connect to the URL in a web-browser on port
5000, i.e.
http://192.168.0.20:5000/
Finishing up
09 Now your music player is functioning, all that’s left to do is to add some
speakers, obviously! Almost anything with an RCA or 3.5mm input source
will work for this purpose. That part we will leave up to you. To take a look at the
code here in full, check out our FileSilo. Enjoy the tunes!
127
of al
r
al ci
fe
tri Spe
Enjoyed
this book?
Exclusive offer for new
Try
3 issues
for just
£5 *
* This offer entitles new UK direct debit subscribers to receive their first three issues for £5. After these issues,
subscribers will then pay £25.15 every six issues. Subscribers can cancel this subscription at any time. New
subscriptions will start from the next available issue. Offer code ZGGZINE must be quoted to receive this special
subscriptions price. Direct debit guarantee available on request. This offer will expire 31 October 2017.
** This is a US subscription offer. The USA issue rate is based on an annual subscription price of £65 for 13 issues,
which is equivalent to approx $102 at the time of writing compared with the newsstand price of $16.99 for 13 issues
$220.87. Your subscription will start from the next available issue. This offer expires 31 October 2017.
128
The only magazine
all about Linux
Written for you
Linux User & Developer is the only
magazine dedicated to advanced users, developers
and IT professionals
subscribers to…
129
HOW TO USE
EVERYTHING YOU NEED TO KNOW ABOUT
ACCESSING YOUR NEW DIGITAL DEPOSITORY
facebook.com/ImagineBookazines
facebook.com/LinuxUserUK
130
Python The Complete Manual
www.imaginebookshop.co.uk