100% found this document useful (9 votes)
362 views

PDF Getting Started with Python and Raspberry Pi 1st Edition Nixon download

Python

Uploaded by

opeltvijyaef
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (9 votes)
362 views

PDF Getting Started with Python and Raspberry Pi 1st Edition Nixon download

Python

Uploaded by

opeltvijyaef
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

Download the full version of the ebook at

https://ebookfinal.com

Getting Started with Python and Raspberry Pi


1st Edition Nixon

https://ebookfinal.com/download/getting-started-
with-python-and-raspberry-pi-1st-edition-nixon/

Explore and download more ebook at https://ebookfinal.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Raspberry Pi 3 Cookbook for Python Programmers Third


Edition Tim Cox

https://ebookfinal.com/download/raspberry-pi-3-cookbook-for-python-
programmers-third-edition-tim-cox/

ebookfinal.com

Raspberry Pi for Python Programmers Cookbook 2nd, revised


Edition Tim Cox

https://ebookfinal.com/download/raspberry-pi-for-python-programmers-
cookbook-2nd-revised-edition-tim-cox/

ebookfinal.com

Getting Started with BeagleBone Linux Powered Electronic


Projects With Python and JavaScript 1st Edition Matt
Richardson
https://ebookfinal.com/download/getting-started-with-beaglebone-linux-
powered-electronic-projects-with-python-and-javascript-1st-edition-
matt-richardson/
ebookfinal.com

Industrial Vision Systems with Raspberry Pi Build and


Design Vision products Using Python and OpenCV 1st Edition
Mohaideen A
https://ebookfinal.com/download/industrial-vision-systems-with-
raspberry-pi-build-and-design-vision-products-using-python-and-
opencv-1st-edition-mohaideen-a/
ebookfinal.com
Portable Python Projects Run Your Home on a Raspberry Pi
Mike Riley

https://ebookfinal.com/download/portable-python-projects-run-your-
home-on-a-raspberry-pi-mike-riley/

ebookfinal.com

Learning Raspberry Pi 1st Edition Shah

https://ebookfinal.com/download/learning-raspberry-pi-1st-edition-
shah/

ebookfinal.com

getting started with java 1st Edition Jonathan Jackson

https://ebookfinal.com/download/getting-started-with-java-1st-edition-
jonathan-jackson/

ebookfinal.com

Getting Started with Neurofeedback John N. Demos

https://ebookfinal.com/download/getting-started-with-neurofeedback-
john-n-demos/

ebookfinal.com

Getting Started with Grails Second Edition Scott Davis

https://ebookfinal.com/download/getting-started-with-grails-second-
edition-scott-davis/

ebookfinal.com
Getting Started with Python and Raspberry Pi 1st
Edition Nixon Digital Instant Download
Author(s): Nixon, Dan
ISBN(s): 9781783551590, 1783551593
Edition: 1
File Details: PDF, 4.62 MB
Year: 2015
Language: english
Getting Started with Python
and Raspberry Pi

Learn to design and implement reliable Python


applications on Raspberry Pi, using a range of external
libraries, the Raspberry Pi's GPIO port, and the camera
module

Dan Nixon

BIRMINGHAM - MUMBAI
Getting Started with Python and Raspberry Pi

Copyright © 2015 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embedded in
critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy
of the information presented. However, the information contained in this book is
sold without warranty, either express or implied. Neither the author, nor Packt
Publishing, and its dealers and distributors will be held liable for any damages
caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.

First published: September 2015

Production reference: 1210915

Published by Packt Publishing Ltd.


Livery Place
35 Livery Street
Birmingham B3 2PB, UK.

ISBN 978-1-78355-159-0

www.packtpub.com

[ FM-2 ]
Credits

Author Copy Editor


Dan Nixon Alpha Singh

Reviewers Project Coordinator


Ankit Aggarwal Suzanne Coutinho
Neil Broers
Yash Gajera Proofreader
Safis Editing
Bhavyanshu Parasher
David Whale
Indexer
Tejal Soni
Commissioning Editor
Dipika Gaonkar
Graphics
Jason Monteiro
Acquisition Editor
Indrajit Das
Production Coordinator
Manu Joseph
Content Development Editor
Zeeyan Pinheiro
Cover Work
Manu Joseph
Technical Editor
Namrata Patil

[ FM-3 ]
About the Author

Dan Nixon is a software and electronics engineer living in the north of England.
He has past experience of creating software for data analysis, process control, and
business intelligence applications. In most of these projects, Python was one of the
main languages used.

Dan previously authored another book on the uses of the Raspberry Pi, called
Raspberry Pi Blueprints, and has worked on many personal projects that use both
Python and the Raspberry Pi.

I would like to thank my mother and father for their support in


writing this book and Greg Fenton for his help in testing some of
the examples included.

[ FM-4 ]
About the Reviewers

Ankit Aggarwal has been fascinated with science and technology since childhood.
He likes to experiment and learn new things. He is a software engineer and
researcher by profession and loves computer science. He wants to solve problems
using technology. His interests include science, technology, academic research,
music, photography, entrepreneurship, DIY, movies, anime, and much more.

He has worked in the fields of networking, distributed systems, pervasive/mobile


computing, data science, AI, and computer vision; the list goes on. Ankit has
authored IEEE Xplore research papers and is an active contributor to and author
of several open source projects. He is socially active, blogs occasionally, and
maintains his website at http://ankitaggarwal.me.

In his free time, he reads, takes part in competitive programming, captures photos
of nature with a lens, and watches TV shows, movies, and anime. When he is not
doing these things, he can be found jogging at the nearest ground.

Neil Broers is a Python developer by day and a hardware hacker by night,


building his "Smart Home," one Raspberry Pi at a time. He is an avid technical
blogger on www.foo.co.za, where he documents his adventures with home
automation. In 2014, he presented a talk on the Raspberry Pi and the Internet
of Things at the PyConZA conference in South Africa.

[ FM-5 ]
Yash Gajera is an embedded software engineer at Insignex in Anand, India.
He studied electronics and communication engineering and graduated in 2014
from the A. D. Patel Institute of Technology, Anand. At Insignex, he has worked
on fully automated irrigation control systems. He did his final year project on the
Internet of Things. It was selected as the best project from the EC department at
Gujarat Technological University in 2014. Yash wrote a Python library for the
Zigbee protocol to work with the Raspberry Pi. He also has a lot of experience
in embedded system development and web technologies.

Bhavyanshu Parasher holds a BTech degree in computer science engineering.


He is currently working toward getting a master's degree in computer science.
He has been developing web applications since 2011. He also has experience in
developing apps for Android and Linux. He has authored and contributed to
various open source projects. Apart from computer science, he is also interested in
electronics. He has developed various projects using the Raspberry Pi, including
service bots, weather monitoring systems, and data analysis automation tools.
When he is not writing code, he spends time writing tutorials on his blog at
https://bhavyanshu.me.

David Whale is a software developer living in Essex, UK. He started coding as


a schoolboy aged 11, inspired by the school science technician to build his own
computer from a kit, and quickly progressed to writing machine code programs
because they were "small and fast." These early experiments led to some of his
code being used in a saleable educational word game when he was only 13.

David has been developing software professionally ever since, mainly writing
small and fast code that goes into electronic products, including automated
machinery, electric cars, mobile phones, energy meters, and wireless doorbells.

[ FM-6 ]
These days, he runs his own software consultancy called Thinking Binaries.
He spends much of his time helping design the next wave of the Internet, called
the Internet of Things. This means connecting electronic devices to the Internet.
The rest of the time, he volunteers for The Institution of Engineering and Technology,
running training courses for teachers, designing and running workshops and clubs
for school children, and generally being busy with his Raspberry Pi.

David was the technical editor of the book Adventures in Raspberry Pi. He is a coauthor
of the book Adventures in Minecraft and is the technical editor of the official Raspberry
Pi magazine, the MagPi.

I was really pleased to be asked to review this new book. Dan Nixon
has done an excellent job of getting you started with Python and
your Raspberry Pi, and he presents the material in an easy-to-follow
format. There are lots of fun ideas and building blocks here, which
I hope many readers will extend into bigger and more ambitious
projects of their own.

[ FM-7 ]
www.PacktPub.com

Support files, eBooks, discount offers, and more


For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF
and ePub files available? You can upgrade to the eBook version at www.PacktPub.com
and as a print book customer, you are entitled to a discount on the eBook copy. Get in
touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles,


sign up for a range of free newsletters and receive exclusive discounts and offers
on Packt books and eBooks.
TM

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital
book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?
• Fully searchable across every book published by Packt
• Copy and paste, print, and bookmark content
• On demand and accessible via a web browser

Free access for Packt account holders


If you have an account with Packt at www.PacktPub.com, you can use this to access
PacktLib today and view 9 entirely free books. Simply use your login credentials for
immediate access.

[ FM-8 ]
Table of Contents
Preface v
Chapter 1: Your First Steps with Python on the Pi 1
Installing and setting up Raspbian 2
Writing to the SD card 2
Windows 2
Linux and Mac 4
Booting the Pi for the first time 6
The Python development tools 13
Python 2 versus Python 3 15
Running some simple Python scripts 15
Summary 17
Chapter 2: Understanding Control Flow and Data Types 19
Data in Python 19
Numerical types 21
Operations on numerical types 25
String manipulation 28
String functions 29
String formatting 32
String templates 33
Control flow operators 36
Using functions 39
Summary 42
Chapter 3: Working with Data Structures and I/O 43
Data structures 43
Lists 43
Creating lists 44
List operations 46

[i]
Table of Contents

Dictionaries 48
Creating dictionaries 48
Dictionary operations 49
Sets 51
Set operations 52
Frozen sets 53
Tuples 54
Input/output 55
The os.path module 55
Reading and writing files 57
Summary 58
Chapter 4: Understanding Object-oriented Programming
and Threading 59
Object-oriented programming 59
Classes in Python 61
Operation.py 61
Calculator.py 62
Using the module 63
Inheritance 64
Threading 66
Locks 68
Summary 70
Chapter 5: Packaging Code with setuptools 71
Using packages in your Python code 71
Importing modules 71
Installing modules manually 72
Installing modules using pip 74
Installing modules using apt 75
Packaging your own Python modules 76
Packaging a library 77
Adding an entry point 79
Summary 81
Chapter 6: Accessing the GPIO Pins 83
Digital electronics 84
The GPIO library 85
Single LED output 86
PWM output 87
Multiple outputs 89
Basic switch 90
Switch using interrupt 92

[ ii ]
Table of Contents

Universal Asynchronous Receiver/Transmitter (UART) 94


Setting up the serial port 94
Using pySerial 96
Additional libraries 98
Summary 99
Chapter 7: Using the Camera Module 101
Setting up the camera module 101
Installing and testing the Python library 106
Writing applications for the camera 107
A time lapse recorder 107
A point-and-shoot camera 109
An image effect randomizer 112
Summary 114
Chapter 8: Extracting Data from the Internet 115
Using urllib2 to download data 115
Parsing JSON APIs 117
Parsing XML APIs 119
The DOM method 120
The SAX method 123
Parsing a web page using BeautifulSoup 125
Summary 130
Chapter 9: Creating Command-line Interfaces 131
Unit conversion application 131
Command-line interface 134
Summary 139
Chapter 10: Debugging Applications with PDB and Log Files 141
The Python debugger 141
Writing log files 146
Unit testing 149
Summary 154
Chapter 11: Designing Your GUI with Qt 155
Setting up the codebase 155
Building the UI with Qt Designer 156
Writing the UI code 170
Launching the UI 172
Packaging the code 173
Summary 174
Index 175

[ iii ]
Preface

Preface
The Raspberry Pi is one of the smallest and most affordable single board computers
that has taken over the world of hobby electronics and programming, and the Python
programming language makes this the perfect platform to start coding with.

Getting Started with Python and Raspberry Pi will guide you through the process of
designing, implementing, and debugging your own Python applications to run on
the Raspberry Pi and will help you interact with some of its unique hardware.

What this book covers


Chapter 1, Your First Steps with Python on the Pi, introduces the Python development
tools as you install and set them up on the Raspberry Pi after installing the Raspbian
operating system.

Chapter 2, Understanding Control Flow and Data Types, introduces you to the control
flow and conditional execution operations. Also, the basic data types and the
operations that can be performed on them will be covered in this chapter.

Chapter 3, Working with Data Structures and I/O, gives you an overview of the standard
Python data structures (for example, list, dict, and tuple) and how they can be used
within an application. Also, this chapter will provide an introduction to reading and
writing files on the Raspberry Pi's filesystem, including reading from the sysfs to get
data such as the current temperature of the processor.

Chapter 4, Understanding Object-oriented Programming and Threading, introduces


the concept of object-oriented programming and compares it to the functional
programming that has been done up to this point in this book.

[v]
Preface

Chapter 5, Packaging Code with setuptools, introduces you to the setup tools in the
Python package, which are used to package Python applications and libraries for
easier installation. This will also include an introduction to the pip utility and PyPi
package repository.

Chapter 6, Accessing the GPIO Pins, gives you an overview of the Python library for
accessing the GPIO pins on the Raspberry Pi and a brief introduction to some basic
electronics needed for the tutorials in the chapter.

Chapter 7, Using the Camera Module, covers using the picamera Python library to
interact with the camera module, the options that can be configured using the
library, and writing a simple application to record a section of video in several
different modes.

Chapter 8, Extracting Data from the Internet, covers the use of several libraries
(including requests and urllib2) to connect to webservers and request data, and
will include obtaining weather forecasts from an online API. Also, you will be
introduced to several third-party libraries that access data from specific sources.

Chapter 9, Creating Command-line Interfaces, covers interaction with applications via


the command line using the argparse Python module.

Chapter 10, Debugging Applications with PDB and Log Files, introduces you to the PDB
(Python debugger) tool, discusses how it can be used to diagnose and fix issues in
Python programs, and covers how the logging Python module can be used to capture
information from an application to be used later for debugging. This includes a tutorial
in which code with several issues placed into it will be debugged and corrected.

Chapter 11, Designing Your GUI with Qt, provides an introduction to GUI design with
Qt using Qt Designer and the Python Qt package.

What you need for this book


You will need:

• A Raspberry Pi
• An SD card (4 GB or higher)

[ vi ]
Preface

Who this book is for


This book is designed for those who are unfamiliar with the art of Python development
and want to get to know their way around the language and the many additional
libraries that allow you to get a full application up and running in no time.

Conventions
In this book, you will find a number of styles of text that distinguish between
different kinds of information. Here are some examples of these styles, and an
explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions,
pathnames, dummy URLs, user input, and Twitter handles are shown as follows:
"We can include other contexts through the use of the include directive."

A block of code is set as follows:


flan = "495"
flan
type(flan)
flan_i = int(flan)
flan_i
type(flan_i)

Any command-line input or output is written as follows:


sudo python setup.py install

New terms and important words are shown in bold. Words that you see on the
screen, in menus or dialog boxes for example, appear in the text like this: "Next we
will disable the LineEdit widget that will be used for displaying the result of a unit
conversion, this is done by selecting the widget and removing the tick in the enabled
property in the Property Editor as shown in the following screenshot."

Warnings or important notes appear in a box like this.

Tips and tricks appear like this.

[ vii ]
Preface

Reader feedback
Feedback from our readers is always welcome. Let us know what you think about
this book—what you liked or may have disliked. Reader feedback is important for
us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to [email protected],


and mention the book title via the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing
or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer support
Now that you are the proud owner of a Packt book, we have a number of things to
help you to get the most from your purchase.

Downloading the example code


You can download the example code files for all Packt books you have purchased
from your account at http://www.packtpub.com. If you purchased this book
elsewhere, you can visit http://www.packtpub.com/support and register to
have the files e-mailed directly to you.

Errata
Although we have taken every care to ensure the accuracy of our content, mistakes
do happen. If you find a mistake in one of our books—maybe a mistake in the text or
the code—we would be grateful if you could report this to us. By doing so, you can
save other readers from frustration and help us improve subsequent versions of this
book. If you find any errata, please report them by visiting http://www.packtpub.
com/submit-errata, selecting your book, clicking on the Errata Submission Form
link, and entering the details of your errata. Once your errata are verified, your
submission will be accepted and the errata will be uploaded to our website or added
to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/


content/support and enter the name of the book in the search field. The required
information will appear under the Errata section.

[ viii ]
Preface

Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media.
At Packt, we take the protection of our copyright and licenses very seriously. If you
come across any illegal copies of our works, in any form, on the Internet, please
provide us with the location address or website name immediately so that we can
pursue a remedy.

Please contact us at [email protected] with a link to the suspected


pirated material.

We appreciate your help in protecting our authors, and our ability to bring you
valuable content.

Questions
You can contact us at [email protected] if you are having a problem
with any aspect of the book, and we will do our best to address it.

[ ix ]
Your First Steps with
Python on the Pi
In this chapter, we will look at setting up the Raspbian operating system on the
Raspberry Pi and have a quick look at the Python development tools that come
pre-installed on it, along with looking at some basic ways in which we can execute
the Python code.

The only things that are required here are:

• A Raspberry Pi
• A USB power source capable of delivering at least 1A
• USB keyboard
• USB mouse
• TV with HDMI port
• An SD card (or microSD card for the model B+ and Pi 2) of at least
4GB capacity
• An SD card reader
• A USB hub (if you wish to connect more USB devices that there are ports
on the Raspberry Pi)
• Optionally, a WiFi adapter if you want to connect the Pi to your network
wirelessly (the list of supported USB WiFi adapters is available at
elinux.org/RPi_USB_Wi-Fi_Adapters)

[1]
Your First Steps with Python on the Pi

Installing and setting up Raspbian


The first thing we need to do is head to the Raspberry Pi downloads page at
https://www.raspberrypi.org/downloads/ and download the latest version of
Raspbian. This is a version of the Debian Linux distribution, specifically designed
for the Raspberry Pi.

1. On the downloads page select the Download ZIP option under RASPBIAN.

2. Once the file has downloaded, extract the Zip archive using the default
tool on your OS. You should now have a single file ending with the file
extension .img.

Writing to the SD card


The next step is to write the just downloaded operating system image to the SD
card so that it can be used with the Pi. The way this is done varies depending on
the operating system you use on your main PC.

Windows
On Windows, we will use a tool called Win32 Disk Imager to write the OS
image to the SD card. This tool can be downloaded from the SourceForge page
at sourceforge.net/projects/win32diskimager.

1. Once downloaded and installed, insert your SD card and open Win32 Disk
Imager. You should see a window similar to the following screenshot:

[2]
Chapter 1

The important thing to check is that a drive letter appears in the Device
drop down list. If this does not happen then Win32 Disk Imager has failed
to recognize your SD card. In such a case, try it in a different SD card reader.
If it still does not work then it could indicate that the card has failed.

2. Next, browse to select the .img file you had previously extracted from
the downloaded Zip archive and click the Write button as shown in the
following screenshot, after first making sure that the correct device is
selected in the Device drop down list:

3. You will then see a confirmation dialog similar to the one shown in the next
screenshot, asking you to confirm that the image and device are correct.
Assuming they are, click on Yes.

[3]
Your First Steps with Python on the Pi

4. Win32 Disk Imager will now write the image file to the SD card. This can
take a few minutes. Once complete, you will see a confirmation dialog box
as seen in the following screenshot:

You now have Raspbian loaded on the SD card and can now move on to the Boot Pi
for the first time. This will be covered in the following sections.

Linux and Mac


On Linux and Mac, the dd command line utility can be used to write the operating
system image to the SD card.

1. First, we need to determine the path to the storage device you want to write
to. On Linux, the easiest way to do this is by using the udev management
tool to monitor the udev logs. This is done by using the following command:
udevadm monitor --udev

2. Now insert the SD card and you should see a series of log messages printed
to the console, similar to those shown in the following image. The last few
should contain the paths to the partitions already on the drive (in my case,
/dev/sdb1 and /dev/sdb2; from this we can deduce that the path to the
SD card is /dev/sdb).

[4]
Chapter 1

3. Next, we need to ensure that none of the existing partitions are mounted
before we try to write to the SD card. This can be done by running the
following command for every partition discovered using udevadm:
umount PATH

Here PATH is the path to the partition. This should give an output similar
to the following image if the partition was not mounted; otherwise the
command will exit without printing any output:

[5]
Your First Steps with Python on the Pi

4. At this point, the SD card is ready to be written to. For this we will use the
following command:
sudo dd if=[path to .img] of=[path to SD]

Here [path to .img] is the path to the .img file extracted from the Zip
archive downloaded earlier and [path to SD] is the path to the SD card
we just discovered.
This process will take some time (up to 20 minutes) and is complete when
the command exits and you see the next shell prompt as shown in the
following screenshot. If the writing fails then an error message will be
printed to the terminal.

Booting the Pi for the first time


Now that you have an SD card with Raspbian installed on it, you are ready to boot
the Pi for the first time and perform the first time configuration steps required to get
the Pi up and running.

Note that to fully setup the Pi, you will need to have a way to connect it to the
internet in order to install and update the software packages. This can either be
wired (using an Ethernet cable) or wireless (using a USB WiFi adapter).

1. Firstly, connect the mouse, keyboard, monitor, and either the WiFi adapter
or the Ethernet cable to the Pi. Insert the SD card and connect a USB power
source. You should see the red PWR LED (Light Emitting Diode) light up
and shortly after that, the green ACT LED would start to blink.
Note that the USB power source should be able to supply at least 1.5A to
ensure reliable operation of the Pi. Usually, the USB chargers supplied with
the tablets are a good choice of power supply.

[6]
Chapter 1

2. Once the Pi has booted, you will see the configuration utility as shown in the
following screenshot. The first thing we need to do here is to expand the root
partition on the SD card to fill the entire SD card. This ensures that we have the
maximum space available once we start using the Pi. This is done by selecting
the Expand Filesystem option at the top of the list and pressing Enter.

3. Once the filesystem has been modified, you will see a message similar to the
one shown next. Press Enter to return to the main menu.

4. Next, we will change the password for the default Pi user. This is done
by selecting the second option on the main menu, Change User Password,
and pressing Enter.

[7]
Your First Steps with Python on the Pi

5. You will now see a message box similar to the one shown next, with
instructions on entering a new password. Press Enter to continue.

6. You will now be required to enter a new password. Press Enter when
finished. Once you have done this, you will be asked to enter the password
again to confirm.

Note that when entering a password you will not see any
characters appear on the screen.

7. Now that the password has been changed, we need to set the default boot
action to start LXDE, the desktop manager used on Raspbian. Select Enable
Boot to Desktop/Scratch and press Enter.

[8]
Chapter 1

8. Now select the second Desktop option and press Enter.

9. You may also wish to change the default locale using the Internationalisation
Options menu option. By default, the Pi is configured for the UK.
10. Once you are ready to reboot the Pi to apply all of the new settings. This is
done by selecting the Finish option and pressing Enter.
11. You will be asked for a confirmation that you want to reboot. Select Yes and
press Enter.

[9]
Your First Steps with Python on the Pi

12. If you are using Ethernet to connect to your network then you can skip
this step. Otherwise, we will now setup the WiFi adapter and connect to
a wireless network.
1. Open wpa_gui by choosing the WiFi Configuration utility in the
Preferences submenu from the main menu in Raspbian.

2. Click on Scan to search for wireless networks in range. When complete,


you should see a list similar to the one in the following screenshot:

[ 10 ]
Chapter 1

3. When the scan completes, double click on the WiFi network you wish
to connect to and you will be shown a window similar to the one in the
following image, with some of the details of the network filled in:

4. Here all that is usually needed to be done is to enter the WiFi


password in the PSK field and click on Add.

[ 11 ]

www.allitebooks.com
Your First Steps with Python on the Pi

5. When done, the network should be selected in the Network drop


down box automatically. Now click on Connect to connect to the
network. Assuming all went well, you should see the Status of the
connection show Connected, as shown in this next screenshot:

13. Now that we have an internet connection on the Pi, the final setup is to
update the software packages already installed on the Pi. This can be done
by opening a terminal, by clicking on the black monitor in the top left corner
of the screen and typing the following commands:
sudo apt-get update
sudo apt-get upgrade

Each of these commands will take a few minutes to execute. The first updates
the list of the available packages and the second updates each of the installed
packages to the latest version.

Now that we have Raspbian setup on the Pi, we can move on to having a look at
some of the tools we can use to write and execute Python scripts on the Pi.

[ 12 ]
Chapter 1

The Python development tools


Now that the Pi is set up and running Raspbian, we can have a look at some of the
tools we will use to develop Python scripts (small text files containing commands)
and applications. Most of the time we will be using either the interactive Python
terminal to execute the code line by line or the python executable to run full scripts
and applications.

We will first look at the interactive terminal. First open a terminal by clicking on
the black monitor icon in the top right corner of the desktop. This will open an
LXTerminal window. In this window, type python and press Enter. This will start
the interactive terminal as shown in the following screenshot:

From here we can type the Python code line by line; each line is executed as soon as
it is typed, making this tool useful for quick testing and debugging (I also find that
it makes a nice command line calculator). To demonstrate this, type in the following
code and press Enter:
print "Hello, world!"

[ 13 ]
Your First Steps with Python on the Pi

This will print the test Hello, world! on the line next to where you typed it in,
as shown in the following screenshot:

The python executable can also be used to run the existing Python script files
(which have the .py file extension), which we will look at later in the chapter.

One alternative to the interactive terminal is the IDLE Integrated Development


Environment (IDE) which can be used both as an interactive terminal and a source
file editor, and provides syntax highlighting for the Python files. It can be found by
selecting Python 2 from the Programming submenu of the main menu on Raspbian,
as shown in the following screenshot:

When first opened, it will be in the interactive terminal mode and can be used
in the same way as the terminal ran from the command line, as shown in the
following screenshot:

[ 14 ]
Chapter 1

Python 2 versus Python 3


You will notice that there are two versions of Python installed by default on Raspbian:
Python 2.7 and Python 3.1. Whilst the fundamentals of Python programming have
not greatly changed between the two versions, there are notable differences that may
prevent a code that was written for one version from working when executed with the
interpreter for a different version.

For this reason, we will only use Python 2.7 in this book as this has the widest library
support and is still the default Python version on many operating systems.

More information of the differences between Python versions


is available on the Python Wiki at wiki.python.org/moin/
Python2orPython3.

Running some simple Python scripts


Now we will look at writing a Python script in a file and executing it. For this we will
use IDLE as it will provide syntax highlighting on the code. However, any text editor
(for example, LeafPad, GEdit, nano, vim) can be used to write the Python files.

1. First open IDLE and select New Window from the File menu, as shown in
the following screenshot. This will open a new text editor window which
will allow you to write and edit the script files.

[ 15 ]
Your First Steps with Python on the Pi

2. Now type the following code into the editor. This is a simple script that
imports the time module and prints a string containing the current time
to the terminal.
import time
print "The current time is: " + time.ctime()

Keep in mind that the indentation level in Python is very


important as this defines the scope that a line of code fits
into. This will become clearer later on in the book when
we start writing more complex codes.

3. Save the file as time.py in the home directory by selecting Save from the
File menu.
Now that the script is saved, we can execute it using the Python executable
at the command line.

4. Open a terminal and enter the following command to execute the


Python script:
python time.py

This will give the following output to the terminal:

One small improvement that could be made to this process is to include a


shebang in the Python script that will tell the shell what to use to execute the
script. This way we do not have to explicitly include the Python command
when we run the script.

5. Go back to the Python script in IDLE and add the following line as the very
first line in the file:
#!/usr/bin/env python

6. Next, we need to give execute permissions to the file in order to execute it


directly (that is, without calling the Python executable first). This is done
using the following command in the terminal:
chmod a+x time.py

7. Now we are able to execute the script using the following command:
./time.py

[ 16 ]
Chapter 1

This gives the following output on the terminal:

Summary
In this chapter, we looked at getting the Pi set up and running using the Raspbian
operating system, and went through the Python development tools and the differences
between the Python versions.

We also looked at our first snippets of Python code and the different ways that Python
can be executed.

In the next chapter, we will focus more on the fundamentals of Python programming
when we look at control flow operations, multiple data types, and the operations
they support.

[ 17 ]
Understanding Control Flow
and Data Types
Now that we are able to run Python code, we will take a look at some of the ways in
which we can store data and control the flow of execution through the Python code.

In this chapter, we will cover:

• The basics of data types in Python


• Using the math module for operations on numerical types
• Using the tring module for string manipulation

As mentioned earlier, all the code used in this chapter is written for Python 2.7,
and is able to be executed on any Python 2.7 interpreter.

Data in Python
Before jumping to the various data types that are available in Python, it is worth
noting that Python is a strong dynamically typed programming language, which
means both that:

• Once a variable (a unit of stored data in a program) has been given a value,
its type is set and will not change until the variable is assigned a value of a
different type (strong)
• A variable can hold a value of any type as the type is given by the value,
not the variable itself (dynamic)

[ 19 ]
Understanding Control Flow and Data Types

This is best explained with an example that can be executed from the interactive
console, assuming we have a variable representing a string:
flan = "flan"

We can query the value held by the variable and the type using the following
code (note that this will only work on an interactive console as return values are
automatically printed to the terminal):
flan
type(flan)

As the following output shows, the variable is of type str which represents a string
in Python:

We can now reassign the variable to a new numerical value and check the type as
done earlier:
flan = 495
flan
type(flan)

Now when we check the type, we see the type has changed to type int, the type
used to store an integer value.

You can also use the isinstance() function to test if a variable holds a value of a
given type, as demonstrated in the following image:

[ 20 ]
Chapter 2

Certain types can be converted by using the type name as a function, as shown in the
following example:
flan = "495"
flan
type(flan)
flan_i = int(flan)
flan_i
type(flan_i)

As the output shows, this converts the original value of the flan variable to an
integer based on the contents of the string:

Numerical types
Python has several different numerical types built in that allow you to represent
integer, floating point, and complex numbers using the following types:

• int: The plain integer type, this has at least 32 bits of precision but is
limited by the architecture of the system
• long: This behaves in the same way as int but has unlimited precision
• float: Floating point numbers
• complex: Complex numbers

There are a range of ways to define a numerical value in Python. Typically, this
can be done by typing the standard representation of a number as shown in the
following example:
a = 42
type(a)
b = 0.009
type(b)
c = 10000000000
type(c)

[ 21 ]
Random documents with unrelated
content Scribd suggests to you:
of the gentlemen who have stayed here during the past year, say, so
we can look up their servants.”
“I can tell you offhand of several of my guests but it will take more
time than I can spare this afternoon to give you a complete list, and
frankly, it is distasteful to me to have my friends annoyed.” Orbit’s
tone was pleasant but firm. “The latest to visit me, whom I can recall,
are Professor Harrowden, from the Smithsonian Institute, Sir Philip
Devereux and Conan Fairclough of London, Sabatiano Maura,
Yareslow Gazdik—”
“Mr. Orbit, would you write the last two?” McCarty interrupted
earnestly. “Where might Professor Harrowden be found?”
“In South America just now, leading an expedition up the Amazon.”
Orbit laid his cigarette in a tray of curiously hammered red gold and
reached obligingly for a pen. “Fairclough’s off for Africa again, I
believe, and Gazdik is playing a series of concerts at Biarritz.”
“Are the others at the ends of the earth, too?” The question was
bland, but McCarty’s smile was a trifle grim.
“Oh, no!” Orbit smiled also in understanding, as he rose and
offered the sheet of paper. “Sir Philip is on his way here from the
West to visit me again for a few days and Maura’s portrait exhibition
closes in Philadelphia before the end of the month when he, too, will
return before sailing again for Madrid. I’ll send the complete list to
headquarters for you, but I’m afraid you won’t find that their
menservants learned much of Hughes’ affairs in the brief time they
were here.”
McCarty thanked him and they took their departure, encountering
Ching Lee in the hall below who showed them out in silence.
“’Tis beyond me what you got out of that interview,” Dennis
declared. “Stalling, is what I’d have called it!”
“The two of us!” McCarty agreed with a chuckle. “Him as well as
me. He’ll not be dragging his friends into this business if he can help
it!... Who’s the lanky, worried-looking guy talking to Bill?”
Halfway down the block, a tall, thin, bespectacled young man was
gesticulating nervously as he confronted the watchman whose
vehement shakes of the head denoted protestation. While they
watched, the young man turned abruptly and made for the Goddard
house. Bill advanced slowly toward them.
“Have you fellows seen the Goddard boy?” he asked. “He’s the
red-headed kid you saw me let in the first day you came. That was
his private teacher who’s been looking for him for an hour but he
didn’t go out either of the gates.”
“Maybe he did awhile back when that one was left open,” McCarty
suggested dryly.
“Good Lord, did you know that!” Bill gasped. “If you let on it’ll cost
me my job, and I only stepped ’round the corner for a smoke! The
kid’s all right, but they treat him like a baby. Did you find out yet who
killed Hughes?”
“We’re waiting for news every minute,” McCarty assured him
gravely as they reached the western gate. “I shouldn’t wonder if it
came to-night.”
“Now what in the world did you give him that bunk for?” demanded
Dennis, when they had left the Mall safely behind them.
“I said ‘news,’ but not of what kind, Denny,” replied his companion
with dignity. “You’re not on duty till morning?”
“No, I was thinking I’d drop in at Molly’s, now the kid has got over
the measles.”
“Well, come to my rooms when you leave your sister’s,” McCarty
invited. “I’ve accepted a bribe from one of my Homevale tenants,
who’s law-breaking in his cellar, and if you’re not afraid of being
poisoned like Hughes——?”
“I’ll be there!” Dennis promised with alacrity.
He was as good as his word but when he arrived no refreshment
awaited him. Instead, McCarty turned from the telephone with a glint
of latent excitement in his blue eyes and announced:
“The news has come, Denny. Horace Goddard has been
kidnapped!”
CHAPTER IX
IN THIN AIR

“G LAD you could come at once, McCarty.” Eustace Goddard’s


ruddy face was pale, and the humorous quirk beneath the
ends of the small, sandy mustache had given place to a tremulous
droop. “Your inspector thought I had some information for you about
that valet’s death when I telephoned headquarters to ask for your
address and I didn’t undeceive him. Don’t want any notoriety about
this while a shadow of doubt remains—but God! I—I’m worried!”
“You’ll recall Special Deputy Riordan from that first talk we had at
Orbit’s?” McCarty indicated his colleague who stood in the doorway.
“You told me over the ’phone that your boy had been kidnapped; he’s
pretty big for that, ain’t he, and in broad day?”
“What else can we think?” Goddard threw out his arms in a
helpless gesture. “Horry vanished in thin air this afternoon! He hadn’t
any idea of going out, in fact, he complained of a headache after
lunch—he has never been very strong—and his mother left him
curled up on the couch in the library here when she went shopping.
She returned late to dress for Orbit’s musicale and didn’t inquire for
him, supposing him to be with Trafford, his tutor. I reached home
from the club about half-past five and found Trafford very much
disturbed—But here he is! He’ll tell you himself. Mr. Trafford, these
are the men for whom I sent. Will you tell them when you first missed
Horry?”
The thin, anxious-looking, bespectacled young man, whom they
had seen in conversation with the watchman that afternoon, came
slowly forward.
“I went to the library at three to tell him it was time for his Latin
lesson,” he began, his voice dazed and shaken. “He wasn’t there
and I searched the house for him, surprised that he should have
gone out without mentioning it. Then it occurred to me that he might
have slipped over to Mr. Orbit’s house next door, where there is an
exceptionally fine collection of paintings which fascinate him. His
ruling ambition is to become an artist and Mr. Orbit has encouraged
him—but I digress. I went there to inquire for him but no one had
seen him, and then, really anxious, I questioned the watchman who
assured me that he had not gone out either gate.”
“H’m!” remarked McCarty as Dennis shuffled his feet uneasily.
“And what did you do after, Mr. Trafford?”
“I concluded that Horace had gone to see the artist who has been
instructing him in drawing and of whom he is very fond; I could think
of nothing else that would account for his disappearance, but it
seemed probable some neighbor with a key to the Mall had entered
just as he left so that the watchman need not have been called upon
to open the gate for him.” The young man’s hands were clenching
and unclenching nervously and beads of moisture stood out upon his
forehead. “I therefore didn’t mention it to Mrs. Goddard before she
went to the musicale but waited, believing Horace would return at
any moment. When the afternoon grew late I searched the house
again, questioned the servants, even went across the street to
inquire at the Sloane house for him; young Mr. Sloane has taken an
interest also in his artistic efforts and it is the only other house on the
block he is privileged to visit by himself, since the Burminsters are
still away. I—I met with no success!—If I had only given the alarm
earlier!”
He was turning away with a groan when McCarty asked:
“Why didn’t you think to ’phone Blaisdell and ask if the lad had
been there, Trafford?”
The wretched tutor stared and Goddard, who had been standing
with his elbows on the mantel and his head in his hands, suddenly
wheeled.
“How did you know Blaisdell is the artist who has been giving him
lessons?” he demanded.
McCarty smiled.
“I heard him say himself that Blaisdell was going on a sketching
tour next month and would take him, only you wouldn’t hear of it,” he
explained. “The boy was wild to go along——”
“Mr. Blaisdell started yesterday,” the tutor interrupted. “I learned
this when I telephoned to his studio this afternoon, as I did as soon
as the idea occurred to me that Horace might have gone there. I
forgot to mention it but my anxiety—! I feel criminally negligent in
having taken the situation so easily!”
“Don’t the boy ever get a chance to play with other lads?” Dennis
spoke for the first time, his tone filled with pitying contempt. “Couldn’t
he have gone to the Park and then home to supper with one or
another of them?”
“My son does not play in the Park,” Goddard responded with
dignity. “He rides there with a class from the Academy on two
mornings of the week but the season does not reopen until next
month. Horace is delicate as I told you and has never cared for
rough, physical exercise, although he is far from being a
mollycoddle. He has a few friends of his own age but they are all still
at their country homes; Mr. Trafford and I have telephoned to every
one we can think of! Mrs. Goddard is prostrated and under the care
of her physician; when she returned from Orbit’s musicale and
learned of Horace’s disappearance she was almost beside herself.
He is our only child, you know. If anything has happened to him—!”
He ran his hand violently through his scanty fringe of hair and
McCarty observed:
“’Tis queer the lad didn’t tell you himself that Blaisdell was going
away yesterday.”
“He hasn’t talked of him very much lately.” Goddard hesitated and
then went on: “Horace is an unusual boy, very sensitive and
reserved. I don’t pretend to understand him. He took it very much to
heart when we declined to allow him to go on this sketching tour but,
of course, it was out of the question; no one but an artist would have
suggested such an impractical thing for a boy of his age, and with his
frail constitution!—Damn that dog! He’ll drive me out of my mind!”
A doleful, long-drawn howl, subdued but eloquent, reached their
ears from below-stairs and McCarty remembered his brief talk with
the boy in that very room three days before.
“Is that Max, the police dog your son was telling me about when I
called here?”
“Yes. He wandered around whining until I couldn’t stand it any
longer and had him shut up. Devilish clever animal and devoted to
Horry—knows there’s something wrong! By God, hear that! Midnight!
What can have happened to my boy?”
He dropped into a chair burying his face in his hands as the clock
struck and once more Dennis spoke.
“Have you any notion how much pocket money the lad had this
day?”
It was Trafford who replied to him.
“Six dollars and seventy-five cents. I am teaching him to keep a
budget and he carefully puts down whatever he spends each day.”
“Little and red-headed, wasn’t he, with a narrow chest and
spindling legs—”
“Riordan means is he small for his age and kind of delicate
looking?” McCarty amended hastily, glaring at the tactless
interrogator. “How was he dressed when you last saw him and
what’s missing from his things?”
“He wore a brown pedestrian suit and brown shoes and golf
stockings,” the tutor answered. “He had a plain platinum wrist watch
on a leather strap and a gold seal ring with the family coat of arms.
Nothing else is missing except a brown cloth cap with the
manufacturer’s name, ‘Knowles,’ inside. Before communicating with
you, Mr. Goddard and I telephoned to every hospital in the city,
fearing that some street accident might have occurred, but no child
whose appearance tallied in the least degree with his had been
brought in. The only remaining possibility is that he is being detained
somewhere for a ransom.”
“Have you any other reason for thinking the lad may have been
kidnapped?” McCarty turned to Goddard. “Know of anybody with a
grudge against you or your family? Had any threatening letters?”
“Great heavens, no!” The bereaved father raised his head. “Horry
is a little chap for fourteen, looks nearer twelve in fact, and Mr.
Trafford usually accompanies him when he leaves the Mall, but he
begged so hard to go to Blaisdell’s studio by himself that I allowed it,
though it was against his mother’s wishes; I wanted him to be manly
and self-reliant, and the Madison Avenue cars pass Blaisdell’s door
near Fiftieth. I thought it was perfectly safe, but he may have been
watched and marked by some criminal as a victim for kidnapping.”
“That don’t explain how or why he passed out of one gate or the
other with not one on the whole block seeing him.” McCarty shook
his head. “You say you’re wishful to avoid notoriety, or I’d advise you
to report the lad’s disappearance to the Bureau of Missing Persons
and let the investigation take its regular course, but there’s a chance
still that he’s not been kidnapped nor yet met with an accident. ’Twas
for Riordan and me to try to locate him and get him back without
having the newspapers getting out extras that you sent for me to-
night?”
Dennis caught his breath audibly at this highly irregular
supposition, but Goddard nodded eagerly.
“That’s it, exactly! It would kill Mrs. Goddard to have the press
make a sensational case of this while there is the slightest hope that
Horace may be restored to us without publicity. You’ll do what you
can? I’ll pay anything, a fortune, to have my son again, safe!”
“We’ll do our best, Mr. Goddard,” McCarty rose. “If we’ve no news
for you by morning can we have a word with Mrs. Goddard then?”
“Of course. I’d take you to her now, but the doctor has given her
something to quiet her. The servants don’t know anything; I’ve
questioned them till I’m hoarse and been in touch with every one to
whom Horry might have gone. For God’s sake, find my boy!”
Young Trafford showed them out and McCarty glanced keenly into
his pale, troubled face as he held the door open. He seemed on the
point of speech but glanced back over his shoulder and then
resolutely closed his lips. McCarty paused.
“Before we come in the morning you’d do well to tell the lad’s
father to come clean with us,” he admonished in a lowered tone. “’Tis
not by keeping anything back that he’ll help!”
Trafford started.
“Do you think he is?” he countered quickly. “I’ve told you all I know,
at any rate, but let me hear if there’s anything more I can do. I’ll sit
up all night by the telephone.”
“Where are we going now?” Dennis asked as his companion
turned toward the east gate. “’Twas to find who killed Hughes that
the inspector made deputies of us, not to be chasing runaway kids,
but I’m trailing right with you.”
“‘Runaway,’ is it? I thought that was your hunch when you asked
what pocket money the lad had and then described him with more
truth than politeness!” McCarty chuckled. “You think he’s gone to join
this artist fellow Blaisdell? ’Twill be easy to settle that when we find
out where that tour was to commence, for Horace could not have
gone far on six seventy-five.”
“And we know how he got out all right,” Dennis supplemented.
“’Twas by that east gate ahead when Bill left it open so convenient!—
Look at Orbit’s house! Do you suppose his afternoon party is lasting
on through the night?”
The awning and carpet were still stretched from the entrance door
to curb, and, seemingly borne upon the subdued radiance of the
glow which filtered through the curtained windows of the
conservatory, there came to them faintly the strains of the organ. It
was no majestic harmony this time, however, but a simple, insistently
repetitive measure. McCarty paused to listen, shaking his head.
“Orbit’s by himself and just kind of thinking through the organ;
can’t you tell, the way he’s just wandering along, amusing himself?
That’s an easy little tune, too, that would stick in your head.—Come
on. I’ve a notion to see part of this Mall we’ve not thought to examine
yet.”
“If there’s a foot of it we’ve not been over, barring the insides of the
other houses—!” began Dennis in obvious disappointment. “I thought
we’d be getting after whoever takes care of Blaisdell’s place to find
where he’s gone—”
“At this time of night?” snorted McCarty. “Has it come to you that
Goddard may not be so far wrong at that, especially if he’s got some
reason he hasn’t told for thinking the lad was stolen? I’m beginning
to see the practical workings of those books of mine you turn your
nose up at and I ask you, did Horace look to have nerve enough to
run away? If he went outside these gates it was of his own free will,
of course, and during the time Bill left the one of them open, but what
if he’d been paid to do it? What if the lad had been decoyed outside?
How do we know there’s not others on the block concerned in it?”
“‘Others on the block!’” repeated Dennis, stopping short as they
passed the dark Bellamy house. “Mac! You’re not thinking there
could be any connection between what happened to Hughes four
days ago and the Goddard kid’s disappearance! You’re not looking to
have him found dead somewhere, poisoned! Glory be! What’s come
to this street all of a sudden?”
“I’m asking myself that,” returned the other grimly. “I’m going no
further in my mind, though, just saying it looks funny, that’s all.
Here’s a handful of rich families living behind their gates in peace
and seclusion for generations, with nothing ever happening except
maybe a funeral now and then, for they could not shut out death.
Then a murder takes place right in their midst, even if the victim did
go far before he dropped in his tracks, and while there’s still no
answer to it somebody in the next house disappears.”
“So that’s why you hinted at notoriety, if Goddard took the case to
headquarters instead of leaving it to us! We’re still on the Hughes
affair after all!” exclaimed Dennis, adding: “What’s down here?”
McCarty had turned down the black passage or court between
Mrs. Bellamy’s and the closed Falkingham house next door on the
east, and he vouchsafed no response to the companion who
followed curiously at his heels until they had reached the rear of the
boarded-up residence. Then he whispered cautiously:
“Got your flashlight?”
For answer Dennis produced the pocket electric torch without
which he seldom went on a nocturnal adventure with McCarty. The
latter took it from him, and, pressing the button, darted a minute but
piercing ray of light along the rear of the houses whose front
sidewalks they had just traversed.
“See that, Denny?” he whispered. “An open court as clear as the
palm of your hand straight past the Bellamys’ and Orbit’s to
Goddard’s on the corner. If the kid had wanted to get out without
being seen he might have left the back of his house and come along
this court to any of the passage-ways that lead out to the sidewalk
nearer the gate.”
“True for you,” Dennis assented. “Turn the light along the back wall
till we see how high it is, and whether there are any little doors in it or
not.”
But the wall, not of brick but of ancient brownstone, was as high as
the city’s regulations permitted, bare save in the rear of Orbit’s
miniature palace, where it was covered by a thick, impenetrable
curtain of ivy, sable and glossy like black satin in the moving finger of
light.
All at once heavy footsteps pounded along the sidewalk to the
mouth of the passage-way they had just left and a brighter beam
was trained suddenly upon them. Dennis dodged instinctively but
McCarty turned and faced it, calling cautiously:
“Is it you, Dave Hollis? We’ve not gone yet, just taking a look
around.”
They had encountered the night watchman when they let
themselves in at the west gate earlier in response to Eustace
Goddard’s summons, and now he merely grunted in
acknowledgment and passed on.
“There’s nothing more to be seen here,” Dennis remarked. “No
one could cross that wall without a ladder and though they might
climb that ivy it could not be done carrying a boy the size of Horace.”
“To say nothing of it being broad day and the back windows of all
the houses in this row looking out at the performance,” McCarty
interjected. “All the same we’ll stroll along to the Goddards’ kitchen
door and back, Denny.”
The rear of Mrs. Bellamy’s mansion was as dark as the front and
in Orbit’s also the lights had by now been extinguished. In the dead
stillness their stealthy footsteps seemed to ring unnaturally loudly to
their own ears. Only in the Goddard house did the dull glow from roof
to cellar gleam forth through shrouded windows like sleepless,
anxious eyes.
“’Tis almost unhealthy, the cleanness of everything!” Dennis
looked about him as the flashlight circled over the spacious,
immaculate court. “Not an ashcan nor so much as a garbage pail
that a cat could hide behind! We’re wasting our time here, Mac!”
But McCarty did not answer. He had gone halfway down the
tradesmen’s passage leading to the sidewalk and paused before a
door in the side wall of the Goddard house. Dennis saw the light play
in narrowing arcs over the paved ground before it and then settle to
a mere pin-point as McCarty stooped. After a moment he
straightened and came swiftly back, cat-footed despite his bulk. He
was holding out some small object in his extended hand and as he
reached his companion’s side he played the light upon it—a small,
plain platinum watch, crushed beyond repair, on a pathetically short
leather wristband.
CHAPTER X
THE MAN IN THE SHADOWS

T HE cold, early light of a clouded morning found McCarty and


Dennis seated over pancakes and coffee in an all-night
restaurant on Sixth Avenue not far from Fiftieth Street. The
intervening hours since they left the New Queen’s Mall had been
fruitlessly spent in a weary round of the ferries and railroad terminals
in search of news of a small, solitary traveler and now they had just
come from an interview with the superintendent of the palatial studio
apartment building in which the artist Blaisdell resided, whose exact
address a nearby druggist had been fortuitously able to supply.
“I always thought those painter guys lived in garrets with never a
square meal nor a second shirt,” Dennis spoke in a slightly dazed
tone. “I mind that day watchman Bill said young Horace told him
Blaisdell was one of the greatest in the country, but he must have
some regular business to be able to live in a place like that! There’s
one thing sure; no matter how much of a fancy he’d took to the kid
he could afford to get into no trouble by taking him on a tour without
his father and mother being willing, and if the boy showed up he’d
bring him back. Where is it again that he’s gone sketching?”
“Up in the She-wan-gunk Mountains,” McCarty pronounced the
name with painstaking care. “Ellenville is his headquarters, the
superintendent said, if you remember; the Detweiler House. Granting
there was a train, and the lad had more money with him than that
four-eyed tutor suspected, he could have got there by early evening,
but no word of any kind had come when I ’phoned the Goddard
house an hour ago.”
“I know,” Dennis drained his cup and held it out to the sleepy
waiter to be refilled. “’Tis too bad you did not tell Trafford about
finding the watch.”
“And send him into hysterics? He’s as bad as a woman now!”
McCarty shrugged. “The doctor give orders Mrs. Goddard wasn’t to
be woke up till eight but we’ll chance it by seven. How do you feel,
Denny?”
Dennis eyed the questioner with swift suspicion.
“There’s nothing the matter with me that I know of!”
“’Tis a pity!” McCarty commented callously. “I was thinking if you
called up the lieutenant at the engine house and told him how sick
you were he’d maybe let you off duty the day. There’s a ’phone over
on the cigar counter.”
“And what’s ailing me?” Dennis’ eyes sparkled but his tone was
flat for his inventive faculties were at low ebb in the early morning.
“From what I’ve learned lately, Denny, about mental defectives—!”
But Dennis had risen and stalking to the counter he took up the
’phone. Presently McCarty heard his voice raised in a harrowing
description of pain but it was abruptly cut short, and, after listening
for a moment with a dazed look on his face, he silently replaced the
receiver and returned to his chair.
“Well?” demanded McCarty expectantly.
“Mike’s out of the hospital and he’ll take my nine-to-six shift.”
“But just what did the lieutenant say to you?”
“He told me,” Dennis replied very slowly and distinctly, “to get the
hell off the ’phone, for I’d be no good at a false alarm while my
crook-chasing side-kick McCarty was on the job again. I gathered
from a few more remarks before he hung up on me that your friend
Jimmie Ballard of the ‘Bulletin’ has been nosing around the engine
house, to get dope from me about what you’re pulling off, and by that
same token running the lieutenant ragged; ’tis what I get for
associating with you.”
It was McCarty’s turn to eye his companion suspiciously but
Dennis’ stolid countenance was quite devoid of humor and he
retorted:
“Is that so? Well, we’d better be associating ourselves with the
Goddards again now or there’ll be no news for Jimmie or the
inspector either, which is worse. Come on.”
“Unless the boy is found as Hughes was,” Dennis suggested
optimistically. “It would let the Lindholms out, but who except a
lunatic would be poisoning children and servants, promiscuous-like?”
McCarty’s reply was a stare and a grunt which the other construed
as derisive and he lapsed into aggrieved silence as they made their
way once more to the gates, behind which so much mystery and
menace brooded.
Trafford opened the door almost before the bell had ceased to
echo through the house and his haggard face was mute evidence
that the suspense had not been lifted.
“Have you—?” He could not voice the rest of the question but
McCarty replied briskly:
“We’ve several possibilities, Trafford, and we’re following every
last one of ’em up. No news is good news just now. Is Mrs. Goddard
awake yet, do you know?”
“Her maid told me when I inquired a few minutes ago that she was
stirring. I’ll go and see.” The young tutor turned dispiritedly away.
“You’ll find Mr. Goddard in the smoking-room at the rear on the
Avenue side.”
In dimensions and ponderous style of furnishing the smoking-room
resembled a club lounge rather than a private apartment and it was a
full minute before they descried Eustace Goddard’s rotund figure
relaxed in the depths of a huge leather armchair. He was apparently
asleep but on their approach he opened widely staring eyes upon
them and sprang up with an inarticulate cry.
“We’ve not located your son yet, Mr. Goddard,” McCarty spoke
quickly before the father could frame words. “We know what every
minute means to you and ’tis for that we’re going to bring the
inspector and some of his other men into it. I can promise you there’ll
be no publicity through us.”
“By God, McCarty, they can blazon it in every paper in the land if it
will bring our boy back to us!” Goddard cried brokenly. “The horror of
this night has made everything else unimportant! You mean you—
you’ve failed?”
“Not exactly, sir, but there are only the two of us now and ’twill
save time if others take up some of the clues we’ve got,” McCarty
explained.
“There’s the telephone,” Goddard waved a shaking hand toward a
stand half concealed behind a lacquered screen. “Get the whole
department if you need it. I’ll offer any reward you suggest—fifty
thousand? A hundred?”
“We’ll settle that when the inspector comes.” McCarty moved to
the screen and took up the receiver, and Dennis cleared his throat.
“How many doors are there to this house?”
“Four!” Goddard replied in a surprised tone. “The one at the front,
two at the rear—kitchen and tradesmen’s entrances—and a smaller
door at the side opening on the court that runs between this house
and Orbit’s. But why do you ask? What are the clues you’ve found?”
Dennis coughed discreetly, and from behind the screen came
McCarty’s voice.
“Is it yourself, Inspector?... Yes, me, McCarty.... No, at Goddard’s
and you’re needed.... Wait a bit! Can you lay hands on both Martin
and Yost?... Can’t talk now, sir. Get me?... All right, bring Martin
along but send Yost over to—to Bill, 0565.... That’s it.... Maybe and
maybe not.... Sure, I’ve been in touch with Bill and he knows the
party I’m looking for. Tell Yost to wait and ’phone here if anything
turns up.... Of course not, Inspector, till you take it in hand! ’Bye.”
The last had been straight blarney, but Dennis shivered as the
receiver clicked on its hook. Well he knew that telephone number
and the grim little house far over toward the river where, for a brief
interval, the bluff, kindly Bill harbored the city’s unknown dead! Had
the sickly little Goddard heir gone the way of Hughes after all?
“Why did you ask about the doors?” The conversation had
evidently held only its obvious meaning for the man before them.
“Horace must have been induced in some way to leave the house,
for no one could have entered with Trafford and all the servants
about!”
“He did leave, and by the side door,” McCarty held out the
shattered little wristwatch. “Does this belong to the lad?”
“Good God, yes! He wore it yesterday!” Goddard seized it and
then sank into his chair. “It’s—smashed! He must have been handled
brutally, perhaps even—!”
“That don’t follow, sir!” McCarty interrupted. “The strap slips out of
the buckle easy, for I tried it, and the lad might have dropped it
without noticing. Anybody going to one of the back doors could have
come along and trod on it after, for ’twas in the alley right in front of
the door that I found it. And now—”
“Mrs. Goddard is awake and ready to see you now,” Trafford’s
voice sounded from the threshold and Goddard started up once
more.
“She knows there is no news?” he asked, and at the tutor’s nod
added: “Come then, but don’t tax her beyond her strength and don’t
mind any—any wild statements which she may make. My poor wife
is almost out of her mind!”
“Of course; we understand,” McCarty darted a quick glance at
Dennis and then turned to the tutor. “Trafford, Inspector Druet and
another man are on their way up from headquarters and you’ll be
helping matters if you tell the both of them what’s happened and all
about them you ’phoned to for trace of the lad.”
In silence they followed Goddard to the tiny jewel-box of an
elevator, whose velvet and gold and glittering crystal mirrors made
Dennis gasp. He gasped again when their guide pressed a button
and they shot abruptly upward and his weatherbeaten face turned a
delicate green as they stopped with a smooth but sickening swoop at
the second floor. He was the first out with the opening of the door,
but there was no time for the aside which trembled on his lips, for
Goddard led the way down the wide hall to the doorway in which the
figure of an elderly maid was silhouetted against the dim light of the
room within.
“Eustace!” A woman’s trembling voice sounded from behind her. “It
can’t be that nothing is known, nothing! Did you tell them about that
—”
“Everything is being done, Clara.” Goddard motioned the maid
aside and McCarty and Dennis followed him into the dressing-room.
They received only a confused impression of mahogany and old-
rose and tall mirrors, of a faint, aromatic perfume and the sound of
deep-drawn, convulsive breathing. The next moment their eyes were
caught and held by the long figure outstretched upon a chaise-
longue, imposing even in the dishevelled abandonment of grief. Mrs.
Goddard was a woman well over forty, but her distraught face still
bore traces of the beauty which must normally have been hers.
There was no touch of gray in the masses of luxuriant dark hair
which the maid had arranged with evident haste, but that night had
etched lines about the fine eyes and the firm though sensitive mouth
that would never be erased.
As her husband went on speaking, her glance swept past him to
the two who waited at his elbow.
“Everything that is humanly possible is being done, my dear!”
Goddard repeated more emphatically. “These are the police officers I
called in, and they want to ask you a few questions. Do you think you
can collect yourself enough to stick to facts and not foolish, morbid
fancies?”
“I am quite collected, Eustace!” There was a note almost of
defiance in Mrs. Goddard’s tones and she sat up among her pillows
with an unconscious dignity, in spite of the emotion which she held in
check with such obvious effort. “Ask me anything you please! I—I
only want my baby safe once more!”
“Of course, ma’am,” McCarty responded soothingly. “You went out
and left the lad on the couch in the library and when you came back
to get ready for the musicale next door you thought he was with his
teacher. Now, what was the first you knew of his disappearance?”
“When I returned from the musicale. It was late, after six, and my
husband met me in the hall with the news. He and Mr. Trafford had
been telephoning everywhere! They thought Horace might have
gone to some of our friends, but he had never done such a thing as
to leave the Mall without our knowledge and I knew that something
terrible had happened. I could feel it—here!” Her slender, very white
hands flew to her breast. “I cannot blame Mr. Trafford for not starting
the search for Horace in the early afternoon; he supposed he had
slipped away to the studio of an artist who has taken a great fancy to
our little boy, but Mr. Blaisdell is not in town.”
The forced composure still held her and only her fluttering hands
and quick-drawn breath gave evidence of her supreme agitation.
“You don’t think the lad has gone to join him, do you?” McCarty
asked.
“Run away, you mean?” Mrs. Goddard shook her head slowly. “Oh,
no! Horace would never dream of such a thing! Mr. Blaisdell wanted
to take him but we would not hear of it and Horace had no idea of
disobeying our wishes. He has never been away from us before—
before yesterday!”
“Then you think he has been kidnapped?”
At the question Goddard, who had moved around to the other side
of the couch, took a step forward, the sagging muscles of his round
face tightening as his jaw tensed but his wife did not take her eyes
from those of McCarty.
“He isn’t here!” her trembling voice broke. “He wouldn’t run away!
The earth didn’t open and—and an avalanche descend upon him! It
must have been that man!”
“What man!” McCarty and Dennis spoke in chorus, and then
Goddard placed his hand on his wife’s shoulder.
“Now, Clara!” he admonished. “You promised—!”
“To give us facts, Mr. Goddard!” interrupted McCarty sternly. “If
Mrs. Goddard can tell us whatever it was you were holding back last
night so much the better! You ’phoned to me that the lad had been
kidnapped but you couldn’t give me any reason for thinking so
except that he was gone, and you didn’t breathe a word about any
‘man’!—Will you tell us, ma’am?”
“There’s nothing to tell!” Goddard insisted obstinately. “My wife is
nervous, imaginative, and so is Horace. He was badly frightened by
a strange man here in the Mall a short time ago and his mother was
quite frantic about it. It was some days before she would allow him to
go out alone again, but personally I think he exaggerated—”
“Our boy would not tell a falsehood!” Mrs. Goddard interrupted. “It
was just at dusk one afternoon about a fortnight ago, or perhaps
less, when Horace had returned alone from Mr. Blaisdell’s studio. He
entered the Mall by the east gate as usual, but stopped to play with a
little white Persian kitten, the pet of Mrs. Bellamy’s baby. Mrs.
Bellamy lives just two doors away, next to Mr. Orbit’s. The watchman
had passed him and gone on toward the west gate when all at once
the kitten darted across the street and Horace followed, afraid that it
might become lost. It ran into the open court between the Parsons
house and the closed one next door belonging to the Quentin estate
and Horace was stooping to coax it to him when he was seized from
behind by a strange man and searched!”
“Searched?” echoed McCarty.
“Yes. The man pressed Horace back against him with one hand
over his mouth and felt in all his pockets with the other, but he took
nothing and never uttered a word! My little son was too startled to
struggle at first, and all at once the man released him—and
disappeared!”
“Did the boy have any money with him?” Dennis could contain
himself no longer.
“Three or four dollars, I believe, but the man left it untouched.”
Mrs. Goddard’s eyes shifted to those of the questioner. “It was quite
dark there in that narrow space between the two houses, but Horace
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookfinal.com

You might also like