Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Raspberry Pi cookbook for Python programmers
Raspberry Pi cookbook for Python programmers

Raspberry Pi cookbook for Python programmers: The Raspberry Pi Cookbook has over 50 tailor-made recipes for programmers to get the most out of Raspberry Pi using Python to unleash its huge potential.

eBook
€8.99 €28.99
Paperback
€37.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Raspberry Pi cookbook for Python programmers

Chapter 2. Starting with Python Strings, Files, and Menus

In this chapter, we will cover:

  • Working with text and strings

  • Using files and handling errors

  • Creating a boot-up menu

  • Creating a self-defining menu

Introduction


In this chapter, we shall jump into using Python to perform some basic encryption by scrambling letters. This will introduce some basic string manipulation, user input, progressing on to creating reusable modules, and finally graphical user interfaces.

To follow, we shall create some useful Python scripts that can be added to run as the Raspberry Pi boots or as an easy-to-run command that will provide quick shortcuts to common or frequently used commands. Taking this further, we shall make use of threading to run multiple tasks and introduce classes to define multiple objects.

Since it is traditional to start any programming exercise with a Hello World example, we shall kick off with that now.

Create the hellopi.py file using nano as follows:

nano -c hellopi.py

Within our hellopi.py file, add the following code:

#!/usr/bin/python
#hellopi.py
print ("Hello Raspberry Pi")

When done, save and exit (Ctrl + X, Y, and Enter). To run the file, use the following command:

python3 hellopi...

Working with text and strings


A good starting point with Python is to get to grips with basic text handling and strings. A string is a block of characters stored together as a value. As you will see, they can be viewed as a simple list of characters.

We will create a script to obtain the user's input, use string manipulation to switch around the letters, and print out a coded version of the message. We then extend this example by demonstrating how encoded messages can be passed between parties without revealing the encoding methods, while also showing how we can reuse sections of code within other Python modules.

Getting ready

You can use most text editors to write Python code. They can be used directly on the Raspberry Pi or remotely through VNC or SSH.

The following are a few text editors that are available with the Raspberry Pi:

  • nano: This text editor is available from the terminal and includes syntax highlighting and line numbers (with the -c option). Refer to the following screenshot:

    The...

Using files and handling errors


In addition to easy string handling, Python allows you to read, edit, and create files easily. So, by building upon the previous scripts, we can make use of our encryptText() function to encode whole files.

Since reading and writing to files can be quite dependent on factors that are outside of the direct control of the script, such as if the file we are trying to open exists or if the filesystem has space to store a new file, we will also take a look at how to handle exceptions and protect operations that may result in errors.

Getting ready

The following script will allow you to specify a file through the command line, which will be read and encoded to produce an output file. Create a small text file named infile.txt and save it so that we can test the script. It should include a short message like the following:

This is a short message to test our file encryption program.

How to do it…

Create the fileencrypt.py script using the following code:

#!/usr/bin/python3...

Creating a boot-up menu


We shall now apply the methods introduced in the previous scripts and reapply them to create a menu that we can customize to present a range of quick-to-run commands and programs.

How to do it…

Create the menu.py script using the following code:

#!/usr/bin/python3
#menu.py
from subprocess import call

filename="menu.ini"
DESC=0
KEY=1
CMD=2

print ("Start Menu:")
try:
  with open(filename) as f:
    menufile = f.readlines()
except IOError:
  print ("Unable to open %s" % (filename))
for item in menufile:
  line = item.split(',')
  print ("(%s):%s" % (line[KEY],line[DESC]))
#Get user input
running = True
while(running):
  user_input = input()
  #Check input, and execute command
  for item in menufile:
    line = item.split(',')
    if (user_input == line[KEY]):
      print ("Command: " + line[CMD])
      #call the script
      #e.g. call(["ls", "-l"])
      commands = line[CMD].rstrip().split()
      print (commands)
      running = False
      #Only run command is one...

Creating a self-defining menu


While the previous menu is very useful for defining the most common commands and functions we may use when running the Raspberry Pi, we will often change what we are doing or develop scripts to automate complex tasks.

To avoid the need to continuously update and edit the menu.ini file, we can create a menu that can list installed scripts and dynamically build a menu from it. Refer to the following screenshot:

A menu of all the Python scripts in the current directory

How to do it…

Create the menuadv.py script using the following code:

#!/usr/bin/python3
#menuadv.py
import os
from subprocess import call

SCRIPT_DIR="." #Use current directory
SCRIPT_NAME=os.path.basename(__file__)

print ("Start Menu:")
scripts=[]
item_num=1
for files in os.listdir(SCRIPT_DIR):
  if files.endswith(".py"):
    if files != SCRIPT_NAME:
      print ("%s:%s"%(item_num,files))
      scripts.append(files)
      item_num+=1
running = True
while (running):
  print ("Enter script number to run...
Left arrow icon Right arrow icon

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Apr 16, 2014
Length: 402 pages
Edition : 1st
Language : English
ISBN-13 : 9781849696630
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Apr 16, 2014
Length: 402 pages
Edition : 1st
Language : English
ISBN-13 : 9781849696630
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 100.97
Raspberry Pi for Secret Agents
€24.99
Mastering Object-oriented Python
€37.99
Raspberry Pi cookbook for Python programmers
€37.99
Total 100.97 Stars icon
Banner background image

Table of Contents

10 Chapters
Getting Started with a Raspberry Pi Computer Chevron down icon Chevron up icon
Starting with Python Strings, Files, and Menus Chevron down icon Chevron up icon
Using Python for Automation and Productivity Chevron down icon Chevron up icon
Creating Games and Graphics Chevron down icon Chevron up icon
Creating 3D Graphics Chevron down icon Chevron up icon
Using Python to Drive Hardware Chevron down icon Chevron up icon
Sense and Display Real-world Data Chevron down icon Chevron up icon
Creating Projects with the Raspberry Pi Camera Module Chevron down icon Chevron up icon
Building Robots Chevron down icon Chevron up icon
Interfacing with Technology Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.8
(13 Ratings)
5 star 76.9%
4 star 23.1%
3 star 0%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Niel Jul 29, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Finally! Hands down one of my most important raspberry pi books.
Amazon Verified review Amazon
colin bolton Dec 04, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Good beginers reference
Amazon Verified review Amazon
Client d'Amazon Oct 12, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Top material
Amazon Verified review Amazon
Daniel Feb 16, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
One of the best books on Raspberry Pi projects. Some very different projects of value to users. i.e good program on a camera module GUI - to preview and take a photo with a shutter button. ) I am using this with a multi camera system on a microscope and self view. The downloaded script for the projects makes it easy to use.
Amazon Verified review Amazon
Alexandru Emilian Susu Jul 30, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is by far the best book I read on Raspberry Pi, presenting a lot of interesting projects ranging from creating 3D games, publishing in the cloud sensory data, using camera to view at a remote site, building robots controlled by RPi, controlling a LED matrix to display words, and so on. This book requires I would say one a beginner's level knowledge of electronics, which even I have. And I guess that people that are better in electronics would appreciate the simpler programming alternative offered by Python and the many programming resources available on the Internet. Some concrete comments on the chapter: - regarding Chapter 10, I know somebody who worked on a similar project with an LED matrix for an industrial clock (see details at http://www.omega-it.ro/products/smartclock/SmartClock.pdf); - regarding Chapter 7, myself I was interested in publishing sensor data with RPi and I was very glad to see an extensive chapter on how to collect data and how to publish them on online services like Xively, etc, in order to view them later. Note there is also another project, DaisyPi, available at http://daisypi.ro/, which creates an extensive sensing device out of RPi. There are a few other interesting applications I didn't see in the book and I am very much interested in getting more info on: - transforming your TV in a SmartTV I found it a great value-added extension, only by buying the ~70 Euros RPi device. See http://www.robofun.ro/raspberry-pi-si-componente/kit-smarttv-raspberry-pi for more information. - using an USB TV Tuner with RPi in order to capture signal from a professional analogue surveillance camera (or to watch TV channels on a TV to which RPi is connected to.) Aside from that, I am happy to see Python becoming more and more of a RAD (Rapid Application Dev) systems language. On a side note, there is also the "Mobile Python" book (http://www.amazon.com/Mobile-Python-prototyping-applications-platform/dp/0470515058) which is really great, and one of the first. And the list can continue. I was already familiar with books on Open Hardware platforms, like Arduino. While Arduino uses a microcontroller (making it more low power than RPi and able to use analogue sensors, etc), RPi is basically a small computer (embedded platform) based on an ARM processor able to run Linux, connect to the Internet, capture a camera stream and process it, etc. There are other open boards these days: Olimex Olinuxino (which is more industrial and even if it claims to be even more open platform that RPi it lacks the many users and resources RPi has on the Internet), Intel Galileo, etc.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.