Java, Eclipse and Web programming Tutorials
Follow me on twitter About Lars Vogel

Python Development with PyDev and Eclipse - Tutorial

Lars Vogel

Version 1.2

05.02.2010

Revision History
Revision 0.112.01.2009Lars Vogel
First DRAFT
Revision 0.231.01.2009Lars Vogel
Added more information, e.g. about the Windows package
Revision 0.316.06.2009Lars Vogel
Added Eclipse installation and usage
Revision 0.417.06.2009Lars Vogel
Added debugging
Revision 0.518.06.2009Lars Vogel
Added link about Google App Engine development with Python
Revision 0.626.06.2009Lars Vogel
variables in debugging
Revision 0.704.07.2009Lars Vogel
Improved description for debugging (F5, F6, F7, F8)
Revision 0.817.08.2009Lars Vogel
New project creation screenshot
Revision 0.907.09.2009Lars Vogel
Update to Pydev 1.5
Revision 1.003.11.2009Lars Vogel
How to write to files
Revision 1.126.01.2010Lars Vogel
Concatenate strings and numbers, if-clauses, for loop
Revision 1.205.02.2010Lars Vogel
Indentation concept of Python explained

Python, Pydev and Eclipse

This article describes how to write and debug Python programs with Eclipse

This article was developed on Eclipse 3.5 (Galileo), Python 2.6.2 and PyDev version 1.5


Table of Contents

1. Overview
1.1. What is Python
1.2. Block concept in Python- Indentation
2. Installation
2.1. Python
2.2. Eclipse Python Plugin
3. Configuration of Eclipse
4. Your first Python program in Eclipse
5. Debugging
6. Programming in Python
6.1. Comments
6.2. Variables
6.3. Assertions
6.4. Methods / Functions in Python
6.5. Loops and if clauses
6.6. String manipulation
6.7. Concatenate strings and numbers
6.8. Processing files in Python
6.9. Classes in Python
7. Google App Engine
8. Thank you
9. Questions and Discussion
10. Links and Literature

1. Overview

1.1. What is Python

Python was develop from Guido van Rossum. The name Python is based on the the TV show "Monty Python’s Flying Circus".

Python is an interpreted programming language and claims to be a very effective programming language. Key features of Python are:

  • high-level data types, as for example extensible lists

  • statement grouping is done by indentation instead of brackets

  • variable or argument declaration is not necessary

  • supports for object-orientated, procedural and / or functional programming style

During execution the Python source code is translated into byte-code which is then interpreted by the Python interpreter. Python source code can also run on the Java Virtual Machine, in this case you are using Jython.

1.2. Block concept in Python- Indentation

Python follows a different way then other programming languages to identify blocks. A block is identified by indentation. If you have an if statement and the next line is indented then it means that it a block belonging to the if. The most "pythonic" way is to use 4 spaces per indentation level. The Python interpreter will however recognize spaces or tabs. The only gottcha is you must never mix spaces and tabs,

The Python interpreter supports spaces or tabs. The most "pythonic" way is to use 4 spaces per indentation level. You can only use either or you must never mix spaces and tabs.

2. Installation

2.1. Python

Download Python from http://www.python.org . Download version 2.6.x from Python. If you are using Windows you are getting a native installer for Python.

2.2. Eclipse Python Plugin

The following assume that you have already Eclipse installed. For an installation description of Eclipse please see Eclipse IDE for Java .

For Python development under Eclipse you can use the PyDev Plugin. PyDev is an active developed open source project. Install PyDev via the update manager via the following update site. http://pydev.org/updates . See Eclipse update manager for using the update manager.

3. Configuration of Eclipse

You have to maintain in Eclipse the location of your Python installation. Open in the menu Window -> Preference and select Pydev-> Interpreter Python

Press new and maintain the path to "python.exe" in your installation directory.

The result should look like the following.

4. Your first Python program in Eclipse

Select File -> New -> Project. Select Pydev -> Pydev Project.

Create a new project with the name "de.vogella.python.first". Select Python version 2.6 and your interpreter.

Press finish.

Select Window->Open Perspective ->Other. Select the PyDev perspective.

Select the "src" folder of your project, right-click it and select PyDev Modul. Create a module "FirstModule".

Create the following source code.

			
'''
Created on 18.06.2009

@author: Lars Vogel
'''
def add(a,b):
    return a+b

print add(1,2)


		

Right-click your model and select Run As -> Python run.

Congratulations! You created your first (little) Python modul and ran it!

5. Debugging

Just right click in the source code and add a breakpoint.

Then select Debug as -> Python Run

You can now inspect and modify the variables in the variables view.

Via the debug buttons (or shortcuts F5, F6, F7, F8) you cab move in your program.

You can use F5 / F6, F7 and F8 to step through your coding.

Table 1. Debugging Key bindings

CommandDescription
F5 Goes to the next step in your program. If the next step is a method / function this command will jump into the associated code.
F6 F6 will step over the call, e.g. it will call a method / function without entering the associated code.
F7F7 will go to the caller of the method/ function. So this will leave the current code and go to the calling code.
F8Use F8 to go to the next breakpoint. If no further breakpoint is encountered then the program will normally run.

You can of course use the ui to debug. The following displays the keybindings for the debug buttons.

6. Programming in Python

6.1. Comments

The following create a single line comment.

				
# This is a comment
			

6.2. Variables

Python provides dynamic typing of its variables, e.g. you do not have to define a type of the variable Python will take care of this for you.

				
# This is a text
s= "Lars"
# This is an integer
x = 1
y=4
z=x+y
			

6.3. Assertions

Python provides assertions. These assertions are always called.

				
assert(1==2)
			

6.4. Methods / Functions in Python

Python allows to define methods via the keyword def. As the language is interpreted the methods needs to be defined before using it.

				
def add(a,b):
    return a+b

print add(1,2)

			

6.5. Loops and if clauses

The following demonstrates a loop the usage of an if-clause.

				
i = 1
for i in range(1, 10):
    if i <= 5 :
        print 'Smaller or equal then 5.\n',
    else:
        print 'Larger then 5.\n',

			

6.6. String manipulation

Python allows the following String operations.

Table 2. 

OperationsDescription
len(s)Returns the length of string s
s[i]Gets the element on position i in String s, position start with zero
s[-i]Get the i-tes Sign of the string from behind the string, e.g. -1 returns the last element in the string
"abcdefg"[0:4]Gets the first 4 elements (abcd)
"abcdefg"[4:]Gets the elements after the first 4 elements (abcd)
`a`+`b` + `c`Concatenates the int varibles a, b,c, e.g. if a=1, b=2, c=3 then the result is 123.
s.lower()Result will be s in lower cases
s.upper()Result will be s in upper cases
s.startswith(t)True, if s startsWith t
s.rstrip()Removes the end of line sign from the string

For example:

				
s = "abcdefg"
assert (s[0:4]=="abcd")
assert ( s[4:]=="efg")
assert ("abcdefg"[4:0]=="")
assert ("abcdefg"[0:2]=="ab")
			

6.7. Concatenate strings and numbers

Python does not allow to concatenate a string directly with a number. It requires you to turn the number first into a string with the str() function.

If you don't use str() you will get "TypeError: cannot concatenate 'str' and 'int' objects".

For example:

				
print 'this is a text plus a number ' + str(10)

			

6.8. Processing files in Python

The following example is contained in the project "de.vogella.python.files".

The following reads a file, strips out the end of line sign and print each line to the console.

				
'''
Created on 07.10.2009

@author: Lars Vogel
'''

f = open('c:\\temp\\wave1_new.csv', 'r')
print f
for line in f:
    print line.rstrip()
f.close()
			

The following reads the same file but write the output to another file.

				
'''
@author: Lars Vogel
'''

f = open('c:\\temp\\wave1_new.csv', 'r')
output = open('c:\\temp\\sql_script.text', 'w')
for line in f:
    output.write(line.rstrip() + '\n')
f.close()
			

6.9. Classes in Python

The following is a defined class in Python. Python uses the naming convension __name__ for internal functions.

Python allows operator overloading, e.g. you can define what the operator + will to for a specific class.

Table 3. 

__init__Constructor of the class
__str__The method which is called if print is applied to this object
__add__+ Operator
__mul__* Operator

The empty object (null) is called "None" in Python.

				
class Point:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y
    def __str__(self):
        return "x-value" + str(self.x) + " y-value" + str(self.y)
    def __add__(self,other):
        p = Point()
        p.x = self.x+other.x
        p.y = self.y+other.y
        return p
        
p1 = Point(3,4)
p2 = Point(2,3)
print p1
print p1.y
print (p1+p2)

			

7. Google App Engine

Google offers free hosting of small Python based web application. Please see Google App Engine development with Python .

8. Thank you

Thank you for practicing with this tutorial.

Please note that I maintain this website in my private time. If you like the information I'm providing please help me by donating.

9. Questions and Discussion

For questions and discussion around this article please use the www.vogella.de Google Group. Also if you note an error in this article please post the error and if possible the correction to the Group.

I believe the following is a very good guideline for asking questions in general and also for the Google group How To Ask Questions The Smart Way.

10. Links and Literature

http://www.python.org/ Python Homepage

http://www.pydev.org/ PyDev Homepage

http://docs.python.org/tutorial/ Python Tutorial