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 a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 : 9781849696623
Category :
Languages :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Apr 16, 2014
Length: 402 pages
Edition : 1st
Language : English
ISBN-13 : 9781849696623
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

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.