Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1
modules to download and install on your system. PyPi used to be called the “cheese shop,”
after a Monty Python’s Flying Circus skit concerning a cheese shop that had no cheese. PyPi
is full of cheese...err...modules and is located at pypi.python.org/pypi.
Q. I’m not a Linux guru, but I want to change the PYTHONPATH variable. How do I do this?
A. First, you must make a change to a file in the home directory—that is, the present working
directory when you log into the Raspberry Pi. Edit the file .profile by typing
nano.profile and pressing Enter. Navigate to the very bottom of the file and then add the
following two lines:

Click here to view code image


PYTHONPATH=/usr/local/lib/pythonversion/site-packages
export PYTHONPATH
In place of version, type the version of Python on your Raspbian system, such as
/usr/local/lib/python3.2/site-packages.
When you have these two lines, save the file by pressing Ctrl+O and then Enter. Then exit the
editor by pressing Ctrl+X.
Test the change by logging out (typing exit and pressing Enter) logging back in, and jumping
into the Python interactive shell (by typing python3 and pressing Enter). Check the path
variable by importing the sys module (by typing import sys and pressing Enter). Now see
if the /usr/local/lib/pythonversion/site-packages directory is in the path
by typing sys.path and pressing Enter.
Q. How can I add some sort of help to my custom module?
A. You can add help to your module by putting a triple-quoted string at the top of your custom
module file. Between the quotes add a sentence or two about the purpose of the module and
give a few examples of using the module’s functions.

Workshop


Quiz


1. A Python script and a module are in essence the same thing because their file names both end
in .py. True or false?
2. What must you do to a module if it is linked with the Python interpreter and you need to use it
in a Python script?
3. In which directory should you store third-party public modules that have been downloaded and
installed?
a. /usr/lib/pythonversion
b. /usr/local/lib/pythonversion/dist-packages
c. /usr/local/lib/pythonversion/site-packages

Answers


1. False. A Python script is designed to be run on its own. A Python module must be imported into
a script or an interactive session before it can be used.
2. It must be imported before it can be used. It does not matter that the module is linked with the
Free download pdf