Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
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
$9.99 $28.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

Shipping Methods
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
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

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 Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

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
$19.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
$199.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
$279.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 $ 130.97
Raspberry Pi for Secret Agents
$32.99
Mastering Object-oriented Python
$48.99
Raspberry Pi cookbook for Python programmers
$48.99
Total $ 130.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 the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela