16.01.2014 Views

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 10<br />

■ ■ ■<br />

Batteries Included<br />

You now know most of the basic <strong>Python</strong> language. While the core language is powerful in<br />

itself, <strong>Python</strong> gives you more <strong>to</strong>ols <strong>to</strong> play with. A standard installation includes a set of modules<br />

called the standard library. You have already seen some of them (math and cmath, containing<br />

mathematical functions for real and complex numbers, for example), but there are many more.<br />

This chapter shows you a bit about how modules work, and how <strong>to</strong> explore them and learn<br />

what they have <strong>to</strong> offer. Then the chapter offers an overview of the standard library focusing on<br />

a few selected useful modules.<br />

Modules<br />

You already know about making your own programs (or scripts) and executing them. You have<br />

also seen how you can fetch functions in<strong>to</strong> your programs from external modules using import:<br />

>>> import math<br />

>>> math.sin(0)<br />

0.0<br />

Let’s take a look at how you can write your own modules.<br />

Modules Are Programs<br />

Any <strong>Python</strong> program can be imported as a module. Let’s say you have written the program in<br />

Listing 10-1 and s<strong>to</strong>red it in a file called hello.py (the name is important).<br />

Listing 10-1. A Simple Module<br />

# hello.py<br />

print "Hello, world!"<br />

Where you save it is also important; in the next section you learn more about that, but for<br />

now let’s say you save it in the direc<strong>to</strong>ry C:\python (Windows) or ~/python (UNIX). Then you<br />

can tell your interpreter where <strong>to</strong> look for the module by executing the following (using the<br />

Windows direc<strong>to</strong>ry):<br />

>>> import sys<br />

>>> sys.path.append('c:/python')<br />

203

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!