Getting Started with Python

     

Python scripts are interpreted, meaning that no compilation is necessary. You simply create your script and run it through the interpreter. This interpreter can be used interactively, meaning that you can test snippets of code on the fly before integrating them into your overall script. When writing Python scripts, you can utilize modules ”either your own or those written by others ”to perform specific tasks such as system calls and socket usage. This is similar to Perl and the Perl module library that programmers cannot live without.

One main feature of Python is its compact and readable scripts. Even though Python is a similarly powerful object-oriented language to C and C++, its scripts tend to be much shorter. The structure of the language enables you to express complex functionality in a single statement rather than multiple statements over numerous lines of code. Also, unlike in C and C++, variable declarations are not necessary. This point alone removes numerous lines of code from the mix.

In the next few sections, you'll learn about the very basics of Python, such as how scripts are structured and how to use the Python interpreter. If you have a proclivity for programming, these sections should whet your appetite enough to study further on your own; eventually you'll be tying it all together and using your Python skills to extend your Plone application.

Working with the Interpreter

The Python interpreter is just called python and is usually found in the /usr/local/bin/ directory on Linux/Unix machines, or in the default installation directory on Windows machines (usually C:/Python/ ),where it is called python.exe . Other installation locations are possible, however, depending on your Linux/Unix distribution and your own preferences regarding file placement.

Note

The process of downloading and installing Python is not covered here because Python will have already been installed with your Plone installation. However, if you want to try Python on a different machine, you can find downloading options and installers at http://www.python.org/download/.


To begin the interactive interpreter on Linux/Unix, you simply type the following at the shell prompt:

 

 # python 

You also can use one of the various tools that are part of the Windows installation, such as IDLE, the Python GUI. This enables you to write and execute snippets of code.

You can also write scripts as separate files, such as helloworld.py , and invoke the interpreter using this command on Linux/Unix machines:

 

 # python helloworld.py 

This interprets the file called helloworld.py .

Finally, on Linux/Unix machines your scripts can be made executable just like shell scripts, by beginning the file with the following and granting executable permissions to the file:

 

 #!/path/to/python 

At that point, you can simply type the name of the file at the shell prompt, and the script will be interpreted.

Note

The previous concepts described for Linux/Unix systems are applicable to Windows systems as well ”substitute the Windows path to python.exe .


When working directly within the Python interpreter, two different prompts are used:

  • >>> is the primary prompt.

  • ... is the secondary prompt.

Note

The secondary prompt is used to indicate a continuation of a line in your script.


Lines output from the interpreter are not preceded by a prompt.

The last item that you need to know about when working within the interpreter is how comments are used. Comments are preceded by the # character:

 

 >>> # this is a comment >>> TEST = 1 # this is also a comment 

The Python interpreter ignores comments, whether they are part of interactive coding or part of a standalone script.

A quick way to get accustomed to using the Python interpreter is to try some mathematical expressions. The mathematical operators in Python are not unlike those of other languages: The + operator performs addition, - performs subtraction, * is used for multiplication, and / is used for division.

For example, type the following at the primary prompt:

 

 >>> (142*4-12)/7 

You will see this result:

 

 79 

Note

In integer division, the result is always rounded toward minus infinity.


You can use the = operator to assign values to variables and then use them ”for example:

 

 >>> x = 15 >>> y = 12 >>> x * y 180 

Working with Strings

Python can also work with strings such as the following, which assigns a value to a variable called message :

 

 >>> message = "I like Python" 

Strings can be enclosed in single or double quotes, with the applicable escaping of these quotes, if you need to use them within your string:

 

 >>> message = 'He\'s a smart guy' 

or

 

 >>> message = "Did you say \"Hi\"?" 

Typing this:

 

 >>> print message 

results in this:

 

 Did you say "Hi"? 

Note

There is no functional difference whether you enclose your strings in single or double quotes. When the interpreter prints a result string, it encloses it in double quotes if it contains a single quote, and it encloses it in single quotes if it contains double quotes, so no character escaping is shown in a result. You can also enclose your strings in triple quotes (""") ”and if you do that, you get around having to escape single or double quotes that you use within your string.


If you need to enter line breaks in your strings, use the newline character ( \n ):

 

 >>> message  = "This is a long line. \nBlah Blah" >>> print message This is a long line. Blah Blah 

Similarly, use the tab character ( \t ) to display tabs:

 

 >>> sampletext = "test\ttest\ttest" >>> print sampletext test test     test 

In Python, the concatenation operator ( + ) is used to put strings together:

 

 >>> smushed = "Test" + "String" >>> print smushed TestString 

Strings can also be indexed, meaning that each character in a string has an assigned number, beginning with 0 for the first character. Continuing with the TestString example, the first letter is accessible via this code:

 

 >>> smushed[0] 'T' 

You can slice the word into parts , such as starting at the first position and selecting the next three characters :

 

 >>> smushed[0:3] 'Tes' 

You can even start at the end and select the last five characters:

 

 >>> smushed[-5:] 'tring' 

As with the numerical and mathematical examples, these are very brief examples of how Python works with strings, but hopefully you're starting to get the picture. Conceptually, Python is not unlike other programming languages you've likely encountered .

Working with Lists

In Python, a list is akin to something you might have encountered in other languages, called an array. A list is a compound data type used to group values. The syntax of a list is shown here:

 

 >>> myList = ['apple', 'orange', 'banana', 'python'] 

As with indexed words, lists are indexed and start at position 0. Thus, this input:

 

 >>> print myList[3] 

will print the following:

 

 python 

The same type of slicing that you saw with strings is also possible with lists. One difference, however, is that you can change an individual element of a list, whereas you cannot change an individual element in a string.

For example, the following does not produce the new string bolt :

 

 >>> myString = 'boot' >>> myString[2] = 'l' 

In fact, you would get an error:

 

 TypeError: object doesn't support item assignment 

However, you could use this to replace orange with peach in the original list example:

 

 >>> myList[1] = 'peach' 

The new list would be this:

 

 >>> print myList ['apple', 'peach', 'banana', 'python'] 

You can do plenty of other things with lists. In fact Python has some handy built-in methods for dealing with them:

  • append ” Adds an item to the end of a list:

     

     >>> myList = ['apple', 'orange', 'banana', 'python'] >>> myList.append('grapes') >>> print myList ['apple', 'peach', 'banana', 'python', 'grapes'] 

  • extend ” Extends the list by appending the items in another given list:

     

     >>> myList = ['apple', 'orange', 'banana', 'python'] >>> myOtherList = ['red', 'blue', 'black'] >>> myList.extend(myOtherList) >>> print myList ['apple', 'peach', 'banana', 'python', 'grapes', 'red', 'blue', 'black'] 

  • insert(i,x) ” Inserts an item into a list at a given position, where i is the index before which the new item should be inserted and x is the item itself:

     

     >>> myOtherList = ['red', 'blue', 'black'] >>> myOtherList.insert(2,'yellow') >>> print myOtherList ['red', 'blue', 'yellow', 'black'] 

  • remove(x) ” Removes the first instance of x from the list:

     

     >>> myOtherList = ['red', 'blue', 'black'] >>> myOtherList.remove('yellow') >>> print myOtherList ['red', 'blue', 'black'] 

  • pop(i) ” Removes the item at index i from the list:

     

     >>> myOtherList = ['red', 'blue', 'black'] >>> myOtherList.pop(2) 'black' >>> print myOtherList ['red', 'blue'] 

  • index(x) ” Provides the index of value x in the list:

     

     >>> myOtherList = ['red', 'blue', 'black'] >>> myOtherList.index('blue') 1 

  • count(x) ” Provides the number of times that value x appears in a list:

     

     >>> myOtherList = ['red', 'blue', 'black'] >>> myOtherList.count('blue') 1 

  • sort () ” Sorts the items in a list:

     

     >>> myOtherList = ['red', 'blue', 'black'] >>> myOtherList.sort() >>> print myOtherList ['blue', 'red'] 

    The sort() method sorts in ascending order, by default. However, you can define a custom sort order. The following creates a reverse sort by defining reverse_numeric and then using it within the call to the sort() method:

     

     >>> myNumList = [1, 5, 2, 6, 9] >>> def reverse_numeric (x,y): >>> return y-x >>> myNumList.sort(reverse_numeric) >>> print myNumList [9, 6, 5, 2, 1] 

    Or, you could just use the reverse() function, which sorts items in reverse alphabetical order, as you'll see next.

    Note

    The reverse_numeric example is one of many sorting examples that appear in the sorting HOWTO at http://www.amk.ca/python/howto/sorting/ .


  • reverse() ” Reverses the elements of the list:

     

     >>> myOtherList = ['red', 'blue', 'black'] >>> myOtherList.reverse() >>> print myOtherList ['black', 'blue', 'red'] 

In other programming languages, you might have come across what are known as associative arrays, which are key/value pairs instead of index/value pairs. In Python, these are called dictionaries. In this example, a dictionary called products is created, containing keys that are product names , and values that are product prices:

 

 >>> products = {'book': 19.99, 'CD': 12.99, 'water': 1.00} 

Different methods of accessing dictionary elements include:

 

 >>> products.keys() # shows all keys ['water', 'book', 'CD'] >>> products.values() # shows all values [1.00, 19.99, 12.99] >>> products['CD'] # will print the value of this key 12.99 

Wasn't that exciting? Now that you've seen some simple one-liners, the next section provides you with an overview of flow control in Python scripts.

Operator Overview

Before moving on to flow control, this section provides a very brief refresher on standard operators. Operators tell the Python interpreter to "do something" with a variable: assign a value, change a value, compare two more values, and so on. Operators can be categorized as follows :

  • Assignment ” Used to assign values to variables

  • Arithmetic ” Used to perform arithmetic operations on variables

  • Comparison ” Used to compare two values and return either true or false

  • Logical ” Used to determine the status of conditions

You've already used an assignment operator if you've been following along in this appendix: The equals sign ( = ) is the basic assignment operator. Remember, = does not mean "equal to." Instead, == (two equals signs) means "equal to," and the single = means "is assigned to." Additionally, the + operator can be used for concatenation (and assignment) purposes. For example:

 

 >>> a = 'hi' >>> b = ' there' >>> c = a + b >>> print c hi there 

You've also seen some arithmetic operators in the previous examples; these simply perform basic mathematical tasks, as shown in Table A.1

Table A.1. Arithmetic Operators

OPERATOR

NAME

EXAMPLE

+

Addition

10+3

-

Subtraction

10-3

/

Division

10/3

*

Multiplication

10*3

%

Modulus

10%3


Next come the comparison operators, which compare two or more values. Table A.2 shows the comparison operators. The result of a comparison is either true or false .

Table A.2. Comparison Operators

OPERATOR

NAME

RETURNS TRUE IF

==

Equivalence

Left is equivalent to right

!=

Non-equivalence

Left is not equivalent to right

>

Greater than

Left is greater than right

>=

Greater than or equal to

Left is greater than or equal to right

<

Less than

Left is less than right

<=

Less than or equal to

Left is less than or equal to right


Finally, the logical operators are used in conditions. These operators ” or , not , and and ”are often found in flow-control structures, which you'll learn about in the next section.

Basic Flow Control in Python

Again, if you've used other programming languages, you'll recognize the basic flow-control constructs:

  • if ... elif ... else statements

  • for statements

  • while statements

The if ... elif ... else statement begins with just the simple if construct ”if something is true, do something else:

 

 >>> num = 10 >>> if num == 10:  print "you got it!" 

This results in:

 

 you got it! 

Suppose that the value of num was 5 ; the output would be nothing because although the if statement is not true, there is nothing else for the script to do. This is where elif or else comes in:

 

 >>> num = 5 >>> if x > 5: ...      print 'too large!' ... elif x < 5: ...      print 'too small!' ... else: ...      print 'just right!' just right! 

Next, the for statement iterates over a list of items and performs a specific task. For example, given a list containing four numbers , this for statement prints the number and then the square root of all the numbers:

 

 >>> import math >>> numList = [2, 34, 5354, 1034939] >>> for x in numList:      print x, math.sqrt(x) 2 1.41421356237 34 5.83095189485 5354 73.1710325197 1034939 1017.31951716 

The while loop is also likely familiar to you. This construct continues to loop for as long as the given condition is true. For example, for as long as the value of i is less than 5 , the while loop will print the value of i :

 

 >>> i = 0 >>> while i < 5:       print i >>> i = i + 1 0 1 2 3 4 

When using for and while loops, additional constructs can control the iteration of these loops : break and continue . When encountered, the break statement breaks out of the current loop. Similarly, the continue statement continues with the iteration of the current loop.

Nesting of loops is perfectly fine ”just don't get all crazy with them (that's true with any language, not just Python). For example, this example of nested loops displays a few multiplication tables:

 

 >>> for multiplier in range(2,6):     for t in range(1,6):         print "%d times %d equals %d" % (t, multiplier, t*multiplier)     print "\n"; 

In English, this script says that, given a multiplier (2,3,4,5) and a base number (1,2,3,4,5), multiply the two together and display the base number ( t ), the multiplier, and then the result ( t*multiplier ), followed by a new line.

The result is this:1 times 2 equals 2

 

 2 times 2 equals 4 3 times 2 equals 6 4 times 2 equals 8 5 times 2 equals 10 1 times 3 equals 3 2 times 3 equals 6 3 times 3 equals 9 4 times 3 equals 12 5 times 3 equals 15 1 times 4 equals 4 2 times 4 equals 8 3 times 4 equals 12 4 times 4 equals 16 5 times 4 equals 20 1 times 5 equals 5 2 times 5 equals 10 3 times 5 equals 15 4 times 5 equals 20 5 times 5 equals 25 

You can nest any looping condition, but remember to break out of your loop where necessary, or you'll have programmed an infinite loop that does nothing more than suck away all your resources.

File Access with Python

One common programming task ”with any language, not just Python ”is accessing (creating, reading, writing to) files on your system. In Python, the open () function is used to open a file, and this must be done before any other actions, such as reading and writing, are performed. The function takes two arguments: the full file pathname and the mode. The common modes are listed here:

  • w ” Opens the file for writing. An existing file of the same name is overwritten.

  • a ” Opens the file for appending, starting at the end of the current file.

  • r ” Opens the file for reading.

  • r+ ” Opens the file for both reading and writing.

So, if you wanted to open the file myFile in the /home/me/ directory for reading only, the command would be this:

 

 >>> f = open('/home/me/myFile', r) 

Similarly, to open a new file for writing, you would use this:

 

 >>> f = open('/home/me/newFile', w) 

The f used in the previous examples is called the file object. After this is created, you can use one or more of the numerous built-in file- related methods to read data, append data, and do countless other things. For example, if the contents of the file in question are Python is cool , the following outputs this information:

 

 >>>  f = open('/home/me/myFile', r+) >>> f.read() 'Python is cool.' 

Other file-related methods are listed here:

  • readline() ” Returns a list of all the lines in the file.

  • write(string) ” Writes the content of string to the file.

  • tell() ” Displays the current position within the file object, in bytes. It can be changed using the seek(offset,reference_point) method

  • close() ” Used to close the file when you are finished using it, to free up system resources.

These are not the only file-related actions that you can perform; you'll learn more by reading the Python Language Reference at http://www.python.org/doc/.

Defining Your Own Functions and Modules in Python

When you have familiarized yourself with coding in Python, you can begin to create reusable elements such as functions and modules. In Python, a basic function begins with the definition:

 

 >>> def myFunction(n): 

This is followed by the code in the function:

 

 >>> i = 0 >>> while i < n:      print i i = i_+ 1 

Then you call the function:

 

 >>> myFunction(7) 

Finally, you watch the output:

 

 0 1 2 3 4 5 6 

The return statement is used within functions to break out of a function and return a value from it. For example:

 

 >>> def mult(x,y):      return x*y >>> print mult(6,7) 42 

These are very simple examples and do not delve into the intricacies of writing functions; it just shows you the structure. At the end of this appendix, you will find links to far more documentation than you ever thought imaginable for a programming language, and you can learn all about the inner workings of user -created functions.

Modules are different from functions. They contain definitions and statements external to the code that you are typing or the script that you are calling, and you import them when you need them. You can write your own modules or use open-source modules written by others. For example, suppose that the myFunction function lives in a module called mine. Before using the myFunction function, you would have to import the mine module:

 

 >>> import mine >>> myFunction(3) 0 1 2 

You can learn much more about creating functions and modules, in the Python documentation. In the next section, you'll learn a bit about the standard library that comes along with Python; it contains many useful elements that will help you avoid reinventing the wheel, so to speak.

What's in the Standard Library?

The Python standard library contains several modules, each containing numerous functions that enable you to quickly write scripts without duplicating your efforts. With all of the modules listed next, you can use the dir() command to show a list of the functions in the module, and you can use the help() command to show the manual page for that module. For example, the os module provides numerous functions related to the operating system. First, you import the module:

 

 >>> import os 

Next, you can show a list of the module functions, using dir():

 

 >>> dir(os) ['F_OK', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', 'O_RANDOM', graphics/ccc.gif 'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL', 'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT', 'O_TRUNC', graphics/ccc.gif 'O_WRONLY', 'P_DETACH', 'P_NOWAIT', 'P_NOWAITO', 'P_OVERLAY', 'P_WAIT', 'R_OK', 'TMP_MAX', graphics/ccc.gif 'UserDict', 'W_OK', 'X_OK', '_Environ', '__all__', '__builtins__', '__doc__', '__file__', graphics/ccc.gif '__name__', '_copy_reg', '_execvpe', '_exists', '_exit', '_get_exports_list', graphics/ccc.gif '_make_stat_result', '_make_statvfs_result', '_pickle_stat_result', graphics/ccc.gif '_pickle_statvfs_result', 'abort', 'access', 'altsep', 'chdir', 'chmod', 'close', 'curdir' graphics/ccc.gif , 'defpath', 'dup', 'dup2', 'environ', 'error', 'execl', 'execle', 'execlp', 'execlpe', graphics/ccc.gif 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fdopen', 'fstat', 'fsync', 'getcwd', graphics/ccc.gif 'getcwdu', 'getenv', 'getpid', 'isatty', 'linesep', 'listdir', 'lseek', 'lstat', graphics/ccc.gif 'makedirs', 'mkdir', 'name', 'open', 'pardir', 'path', 'pathsep', 'pipe', 'popen', graphics/ccc.gif 'popen2', 'popen3', 'popen4', 'putenv', 'read', 'remove', 'removedirs', 'rename', graphics/ccc.gif 'renames', 'rmdir', 'sep', 'spawnl', 'spawnle', 'spawnv', 'spawnve', 'startfile', 'stat', graphics/ccc.gif 'stat_float_times', 'stat_result', 'statvfs_result', 'strerror', 'sys', 'system', graphics/ccc.gif 'tempnam', 'times', 'tmpfile', 'tmpnam', 'umask', 'unlink', 'unsetenv', 'utime', 'waitpid' graphics/ccc.gif , 'walk', 'write'] 

For information about the module itself and documentation for all of the functions listed, use help() :

 

 >>> help(os) 

The resulting output is quite long, but here is an example of something you will see in the manual page for the os module:

 

 getcwd(...)     getcwd() -> path     Return a string representing the current working directory. 

You can test this (results will vary):

 

 >>> import os >>> os.getcwd() 'C:\Python' 

Other modules in the standard library include these:

  • datetime , which contains functions used to manipulate dates and times.

  • glob , which contains a function for making file lists from directory searches.

  • math , which contains all mathematics-related functions defined by the C standard.

  • random , which provides access to a plethora of random variable “generation functions.

  • re , which provides access to regular expression tools.

  • shutil , which contains functions for use with file and directory management.

  • smtplib , which contains functions used to interface with SMTP.

  • sys , which contains numerous functions used to interact with the interpreter, including stdin, stdout , and stderr for program input and output.

  • urllib2 , which contains functions used to open and read from URLs using multiple protocols.

  • zlib, gzip, bz2, zipifile, and tarfile , each containing functions used for their respective compression format. For example, the gzip module contains functions used to gzip files, while tarfile contains functions used to tar / untar archives.

These are just a few of the modules included in the standard library, but they are the most commonly used. If you have aspirations of modifying the code used to create elements of Plone or Plone-related add-on packages, as you've seen in this book, you'll need to refer to much more of the Python documentation than what is found here. But this appendix should have given you enough of an introduction for you to determine whether it's something you want to try. In the next section, you'll find a partial listing of all the freely available reference information and outlets for help within the world of Python.



Plone Content Management Essentials
Plone Content Management Essentials
ISBN: 0672326876
EAN: 2147483647
Year: 2003
Pages: 107
Authors: Julie Meloni

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net