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

(singke) #1
2: >>> os.getcwd()
3: '/home/pi'
4: >>> import arith
5: Traceback (most recent call last):
6: File "<stdin>", line 1, in <module>
7: ImportError: No module named arith
8: >>>
9: >>> os.chdir('/home/pi/py3prog')
10: >>> import arith
11: >>>
12: >>> arith.dbl(10)
13: 20
14: >>> arith.addem(5,37)
15: 42
16: >>>

After the test directory is reached on line 9, using the os.chdir statement, the import arith on
line 10 works fine. Both functions in the arith module are tested, and no problems result.


By the Way: Multiple Imports?
It doesn’t hurt anything if you accidently import a module a second (or third) time.
When the import command is issued, Python first checks whether the module is
already imported. It the module is already imported, then Python does nothing (and
doesn’t complain, either!).

Moving a Module to a Production Directory


When you have any problems resolved in your module, you should move it to a production directory
location. This is an optional step. If you are the only user of the Raspberry Pi and really don’t care
where you keep your Python code, you can skip this step. However, good form dictates that a module
should be in a standard production directory.


A production directory is a directory where modules can be accessed by all the Python script users.
You can see the current production directories by using the sys module, as shown in Listing 13.10.


LISTING 13.10 Production Directories Used by Python


Click here to view code image


>>> import sys
>>> sys.path
['', '/usr/lib/python3.2', '/usr/lib/python3.2/plat-linux2',
'/usr/lib/python3.2/lib-dynload', '/usr/local/lib/python3.2/dist-packages',
'/usr/lib/python3/dist-packages']
>>>

Notice in Listing 13.10 that the first directory shown is just two single quotes with no directory name
in between the quotes. When Python sees this, it searches your present working directory for the
module. This is why Listing 13.9 is able to use the os.chdir function to switch to
/home/pi/py3prog and test your module.


Also, notice in Listing 13.10 that /usr/lib/python3.2 is listed as a location in the path. This is

Free download pdf